Python_For_answers
-->If we want to execute some action for every element present in some sequence(It may be string or collection) then we should go for 'for loop'.
Syn:
for variable in sequence:
body
------
-------
Ex:Write a program To print Hello 10-times
for i in range(10):
print('Hello')
________________________________________________________________________
#Ex: write a program to display the first 10 numbers
for i in range(10):
print(i)
________________________________________________________________________
#Ex: write a program to display the numbers from 5 to 20 using the start parameter 5 in range():
for x in range(5, 20):
print(x)
________________________________________________________________________
# Ex: write a program to display the numbers from 5 to 20 using the start parameter 1, increment the sequence with 5:
for i in range(1,100,5):
print(i)
________________________________________________________________________
#Ex: write a program to display numbers from 10 to 1 reverse order.
for i in range(10,0,-1):
print(i)
________________________________________________________________________
#Ex: write a program to display the first 10 numbers, add the $ end of line
number_list = [ 1,2,3,4,5]
for i in number_list:
print(i, end='$')
print()
________________________________________________________________________
# Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("For Loop finally finished!")
________________________________________________________________________
#Ex: write a program to display Even numbers from 0-20
for i in range(21):
if ( i%2 == 0):
print(i, "is Even number")
or
for i in range(1,21,2):
print(i)
________________________________________________________________________
#Ex: write a program to display odd numbers from 0-20
# Odd numbers
for i in range(21):
if ( i%2 == 1):
print(i, "is Odd number")
________________________________________________________________________
#Ex: write a program to display both even and odd numbers from 0-20
for i in range(21):
if ( i%2 == 0):
print(i, "is Even number")
else:
print(i, "is Odd number")
________________________________________________________________________
# write a program to find the leap years between 2000 and 2100 years using the range()
number_str = input ("Enter the number: ")
given_number = int(number_str)
for i in range(2000, 2100):
if( i %4 ==0):
print("Leap Year")
________________________________________________________________________
#Ex: write a program to display the numbers divisible by 3, 5 and both 3 and 5 using if condition in loop
for n in range(1, 101):
if n % 3 == 0 and n % 5 == 0:
print("Three and 5 are friends")
elif n % 3 == 0:
print("Three alone")
else:
print("5 alone")
________________________________________________________________________
#Ex: write a program to read the number from user and display the first 'N' numbers
number_str = input ("Enter the number: ")
number = int(number_str)
# since for loop starts with the zero indexes we need to skip it and start the loop from the first index.
for i in range(1,number):
print(i)
________________________________________________________________________
#Ex: write a program to display number pyramid like
5
55
555
5555
num = input("Enter the number")
for i in range (11):
val = num * i
print("%s X %s = %s" %(num, i, val))
________________________________________________________________________
#Ex: Python program to add 50 for each number in the list
# Write the flow chart using counter loop
number_str = input ("Enter the number: ")
given_number = int(number_str)
for i in range(11):
print (given_number," + ", i , " =" ,50 + i)
________________________________________________________________________
#Ex: Python program to print a multiplication table of a given number
# Write the flow chart using counter loop
number_str = input ("Enter the number: ")
given_number = int(number_str)
# Multiplication Table generally have 10 entries so taking range 11
for i in range(11):
val = num * i
print("%d X %d = %d" %(num, i, val))
print (given_number," x ", i , " =" ,5*i)
print (f' {given_number} X {i} = {given_number*i}')
________________________________________________________________________
# write a program to write the 2 multiplication table using the range()
# write a program to write the 5 multiplication table using the range()
# write a program to write the 2, 3 and 4 multiplication tables at a time range() and nested for loops
#Ex: write a program to sum of all numbers from 1 to a given number
# if the given number is 10
number_str = input ("Enter the number: ")
given_number = int(number_str)
# set up a variable to store the sum with initial value of 0
sum = 0
# since we want to include the number 10 in the sum increment given number by 1 in the for loop
for i in range(1,given_number+1):
sum+=i
# print the total sum at the end
print(sum)
---------------------------------------------------------------------------
Example 4: Python program to calculate the sum of all the odd numbers within the given range.
# if the given range is 10
number_str = input ("Enter the range: ")
given_range = int(number_str)
# set up a variable to store the sum
# with initial value of 0
sum = 0
for i in range(given_range):
# if i is odd, add it
# to the sum variable
if i%2!=0:
sum+=i
# print the total sum at the end
print(sum)
---------------------------------------------------------------------------
Example 4: Python program to calculate the sum of all the even numbers within the given range.
---------------------------------------------------------------------------
# if the given range is 10
number_str = input ("Enter the range: ")
given_range = int(number_str)
# set up a variable to store the sum
# with initial value of 0
sum = 0
for i in range(given_range):
# if i is odd, add it
# to the sum variable
if i%2==0:
sum+=i
# print the total sum at the end
print(sum)
---------------------------------------------------------------------------
Example 7: Python program to count the total number of digits in a number.
# if the given number is 129475
given_number = 129475
# since we cannot iterate over an integer in python, we need to convert the integer into string first using the str() function
given_number = str(given_number)
# declare a variable to store the count of digits in the given number with value 0
count=0
for i in given_number:
count += 1
# print the total count at the end
print(count)
---------------------------------------------------------------------------
Example 8: Python program to check if the given string is a palindrome.
# given string
given_string = "madam"
# an empty string variable to store the given string in reverse
reverse_string = ""
# iterate through the given string and append each element of the given string to the reverse_string variable
for i in given_string:
reverse_string = i + reverse_string
# if given_string matches the reverse_srting exactly the given string is a palindrome else the given string is not a palindrome
if(given_string == reverse_string):
print("The string", given_string,"is a Palindrome.")
else:
print("The string",given_string,"is NOT a Palindrome.")
---------------------------------------------------------------------------
Example 9: Python program that accepts a word from the user and reverses it.
# input string from user
given_string = input()
# an empty string variable to store
# the given string in reverse
reverse_string = ""
# iterate through the given string
# and append each element of the given string
# to the reverse_string variable
for i in given_string:
reverse_string = i + reverse_string
# print the reverse_string variable
print(reverse_string)
---------------------------------------------------------------------------
Example 10: Python program to check if a given number is an Armstrong number
# the given number
given_number = 153
# convert given number to string so that we can iterate through it
given_number = str(given_number)
# store the length of the string for future use
string_length = len(given_number)
# initialize a sum variable with 0 value to store the sum of the product of each digit
sum = 0
# iterate through the given string
for i in given_number:
sum += int(i)**string_length
# if the sum matches the given string its an Armstrong number
if sum == int(given_number):
print("The given number",given_number,"is an Armstrong number.")
else:
print("The given number",given_number,"is Not an Armstrong number.")
---------------------------------------------------------------------------
Example 6: Python program to display numbers from a list using a for loop.
# if the below list is given
list = [1,2,4,6,88,125]
for i in list:
print(i)
---------------------------------------------------------------------------
Example 11: Python program to count the number of even and odd numbers from a series of numbers.
# given list of numbers
num_list = [1,3,5,6,99,134,55]
# iterate through the list elements
# using for loop
for i in num_list:
# if divided by 2, all even number leave a remainder of 0
if i%2==0:
print(i,"is an even number.")
# if remainder is not zero then it's an odd number
else:
print(i,"is an odd number.")
---------------------------------------------------------------------------
Example 12: Python program to display all numbers within a range except the prime numbers.
# Prime numbers
print(f"Prime number \t\t\t Not a prime")
for n in range(2, 101):
for x in range(2, int(n/2)):
if n % x == 0:
print(f"\t\t\t {n} equals {x} X {n / x} hence its not a prime")
break
else:
print(f"{n} is a prime number")
# import the math library
import math
# function to print all
# non-primes in a range
def is_not_prime(n):
# flag to track
# if no. is prime or not
# initially assume all numbers are
# non prime
flag = False
# iterate in the given range
# using for loop starting from 2
# as 0 & 1 are neither prime
# nor composite
for i in range(2, int(math.sqrt(n)) + 1):
# condition to check if a
# number is prime or not
if n % i == 0:
flag = True
return flag
# lower bound of the range
range_starts = 10
# upper bound of the range
range_ends = 30
print("Non-prime numbers between",range_starts,"and", range_ends,"are:")
for number in filter(is_not_prime, range(range_starts, range_ends)):
print(number)
---------------------------------------------------------------------------
Example 13: Python program to get the Fibonacci series between 0 and 50.
# given upper bound
num = 50
# initial values in the series
first_value,second_value = 0, 1
# iterate in the given range
# of numbers
for n in range(0, num):
# if no. is less than 1
# move to next number
if(n <= 1):
next = n
# if number is within range
# execute the below code block
if nextnum:
break
# print each element that
# satisfies all the above conditions
print(next)
---------------------------------------------------------------------------
Example 14: Python program to find the factorial of a given number.
# given number
given_number= 5
# since 1 is a factor
# of all number
# set the factorial to 1
factorial = 1
# iterate till the given number
for i in range(1, given_number + 1):
factorial = factorial * i
print("The factorial of ", given_number, " is ", factorial)
---------------------------------------------------------------------------
Example 15: Python program that accepts a string and calculates the number of digits and letters.
# take string input from user
user_input = input()
# declare 2 variable to store
# letters and digits
digits = 0
letters = 0
# iterate through the input string
for i in user_input:
# check if the character
# is a digit using
# the isdigit() method
if i.isdigit():
# if true, increment the value
# of digits variable by 1
digits=digits+1
# check if the character
# is an alphabet using
# the isalpha() method
elif i.isalpha():
# if true, increment the value
# of letters variable by 1
letters=letters+1
print(" The input string",user_input, "has", letters, "letters and", digits,"digits.")
---------------------------------------------------------------------------
Example 16: Write a Python program that iterates the integers from 1 to 25.
# given range
given_range = 25
# iterate using a for loop till the
# given range
for i in range(given_range+1):
# if no. is multiple of 4 and 5
# print fizzbuzz
if i % 4 == 0 and i % 5 == 0:
print("fizzbuzz")
# continue with the loop
continue
# if no. is divisible by 4
# print fizz and no by 5
if i % 4 == 0 and i%5!=0:
print("fizz")
# continue with the loop
continue
# if no. is divisible by 5
# print buzz and not by 4
if i % 5 == 0 and i % 4!= 0:
print("buzz")
else:
# else just print the no.
print(i)
---------------------------------------------------------------------------
Example 17: Python program to check the validity of password input by users.
# input password from user
password = input()
# set up flags for each criteria
# of a valid password
has_valid_length = False
has_lower_case = False
has_upper_case = False
has_digits = False
has_special_characters = False
# first verify if the length of password is
# higher or equal to 8 and lower or equal to 16
if (len(password) >= 8) and (len(password)<=16):
has_valid_length = True
# iterate through each characters
# of the password
for i in password:
# check if there are lowercase alphabets
if (i.islower()):
has_lower_case = True
# check if there are uppercase alphabets
if (i.isupper()):
has_upper_case = True
# check if the password has digits
if (i.isdigit()):
has_digits = True
# check if the password has special characters
if(i=="@" or i=="$" or i=="_"or i=="#" or i=="^" or i=="&" or i=="*"):
has_special_characters = True
if (has_valid_length==True and has_lower_case ==True and has_upper_case == True and has_digits == True and has_special_characters == True):
print("Valid Password")
else:
print("Invalid Password")
---------------------------------------------------------------------------
Example 18: Python program to convert the month name to a number of days.
# given list of month name
month = ["January", "April", "August","June","Dovember"]
# iterate through each mont in the list
for i in month:
if i == "February":
print("The month of February has 28/29 days")
elif i in ("April", "June", "September", "November"):
print("The month of",i,"has 30 days.")
elif i in ("January", "March", "May", "July", "August", "October", "December"):
print("The month of",i,"has 31 days.")
else:
print(i,"is not a valid month name.")
---------------------------------------------------------------------------
Ex:To print characters present in the given string
---------------------------------------------------------------------------
s = 'sunny'
for x in s:
print(x)
Ex:To print characters present in string index wise
----------------------------------------------------------------------------
s = 'lilly'
i = 0
for x in s:
print('The character present at',i,'index:',x)
i += 1
_______________________________________________________________________________________
# Loop through the string characters, eg - "banana":
for x in "banana":
print(x)
# Loop through the string list : # Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Loop through the number list : # Print each fruit in a fruit list:
number_list = [68, 78, 88 , 8, 18, 28, 38, 48, 58 ]
for number in number_list:
print(number)
# Loop through the tuple
tuple1 = (4,5,3,6,7,8,1,2,6)
tuple1
for i in tuple1:
print(i)
________________________________________________________________________
# Loop through the set
set1 = {44,5,3,6,7,8,1,2,6,44,44}
print(set1) # it displays unique items in unordered
for i in set1:
print(i)
________________________________________________________________________
# Loop through the dictionary
d = dict()
d['duration'] = 120
d['fee'] = 25000
d['rating'] = 4
________________________________________________________________________
for i in d:
print("%s %d" % (i, d[i]))
________________________________________________________________________
d = dict()
d['name'] = 'Test_Name'
d['course'] = 'AI'
d['Loc'] = 'Hyd'
for i in d:
print("%s %s" % (i, d[i]))
#________________________________________________________________________________________
# loop breaks , break loop if you encounter value 5
numlist = [ 1,2,3,4,5,6,7,8,9]
for i in numlist:
if i == 5 :
break
print(i)
# output is - 1
# 2
# 3
# 4
#Break Vs Continue the loop
for i in numlist:
if (i == 5):
continue
print(i)
#output is -
# 1
# 2
# 3
# 4
# 6
# 7
# 8
# 9
# Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
# With the continue statement we can stop the current iteration of the loop, and continue with the next:
# Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
for i in "Python":
if( i == 't'):
break
print(i)
for i in "Python":
if( i == 't'):
continue
print(i)
# Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
# for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error.
for x in [0, 1, 2]:
pass
#Interview question - How to execute the for loop without body? use the pass statement.
str1 = "banana"
for x in str1:
pass
## Nested Loops
# Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
# Nested with lists
nested_list=[[1,2,3],['a','b','c'],[1.1,2.2,3.3]]
for i in nested_list:
print(i)
for j in i:
print(j)
# Nested with dictionaries
d = {'name': ['a','b','c'], 'Age': [10,20,30], 'Sal':[1,2,3]}
for i in d.values():
print (i)
for j in i:
print(j)
##########################################################################
cars = ["ok", "ok", "faulty", "ok", "faulty", "ok"]
for status in cars:
if status == "faulty":
print("Stopping the production Line")
break
elif status == "ok":
print(f"The car is {status}")
print("Shipping new car")
cars = ["ok", "ok", "ok", "faulty", "ok"]
for status in cars:
if status == "faulty":
print("Stopping the production Line")
break
elif status == "ok":
print(f"The car is {status}")
print("Shipping new car")
else:
print("All cars built successfully")
cars = ["ok", "ok", "faulty", "ok", "faulty", "ok"]
all_succesful = True
for status in cars:
if status == "faulty":
print("Stopping the production Line")
all_succesful = False
break
elif status == "ok":
print(f"The car is {status}")
print("Shipping new car")
if all_succesful:
print("All cars built successfully")
____________________________________________________________________________________________
Quiz:
Ex:
-----
a = [0,1,2,3]
for a[-1] in a:
print(a[-1])#0 1 2 2
Q.
list = [1,0,2,0,3,0]
for i in list:
if i == 0:
list.remove(i)
list.append(i)
print(list)#[1,2,3,0,0,0]
Q.
a = [1,2,3,4,5]
for i in a:
a.remove(i)
print(a)#[2,4]
Q.
a,b = '06'
b,c = '26'
print(a+b+c)#026
Q.
s = 'python'
for i in range(len(s)):
print(s)
s = 'a'
Q.
name = 'Python'
if name == 'java' or 'html' or 'css':
print('login successful')
else:
print('Not valid')
Q.
a=['a','b','c','d']
for i in a:
a.append(i.upper())
print(a)
What is the result?
A) ['a','b','c','d']
B) ['A','B','C','D']
C) SyntaxError
D) MemoryError thrown at runtime
67804202
____________________________________________________________________________________________
1) Apply the leaves before March
2) Performance goals and career development goals - April
mentors from different LOB [ go/imentor ; speak to avinash for mentor]
speak to senior vps
Portfolio
horizontal [ across the passion ]
Vertical [ AI; curiosity ]
Devlopment plan
certifications
3) Performance goals
Accomplishments
____________________________________________________________________________________________
Comments
Post a Comment