[go: up one dir, main page]

0% found this document useful (0 votes)
7 views7 pages

For Loop Program

Uploaded by

Aruna Simsarah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views7 pages

For Loop Program

Uploaded by

Aruna Simsarah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

1.

Print individual letters of a string using the for loop n=2


word="anaconda" found = False
for letter in word: for num in nums:
print (letter) if n == num:
2. Using the for loop to iterate over a Python list or tuple found = True
words= ["Apple", "Banana", "Car", "Dolphin" ]
break
for word in words:
print(found)
print (word)
2a 7The continue statement with for loop
nums = (1, 2, 3, 4) nums = [1, 2, -3, 4, -5, 6]
sum_nums = 0 sum_positives = 0
for num in nums: for num in nums:
sum_nums = sum_nums + num if num < 0:
print(sum_nums) continue
sum_positives += num
3. Nesting Python for loops print(sum_positives)
words= ["Apple", "Banana", "Car", "Dolphin" ]
for word in words: 8 Python for loop with an else block
#This loop is fetching word from the list def print_sum_even_nums(even_nums):
print ("The following lines will print each letters of "+word) total = 0
for letter in word: for x in even_nums:
#This loop is fetching letter for the word if x % 2 != 0:
print (letter) break
print("") #This print is used to print a blank line total += x
else:
4 Python for loop with range() function print("For loop executed normally")
for x in range(3):
print(total)
print("Printing:", x)
# this will print the sum
5
print_sum_even_nums([2, 4, 6, 8])
for n in range(1, 10, 3):
# this won't print the sum because of an odd number in the
print("Printing with step:", n)
sequence
print_sum_even_nums([2, 4, 5, 8])
6 break statement with for loop
nums = [1, 2, 3, 4, 5, 6]
Example 1: Print the first 10 natural numbers using for loop. sum+=i
n = 11 # print the total sum at the end
for i in range(1,n): print(sum)
print(i)
Example 5: Python program to print a multiplication table
Example 2: Python program to print all the even numbers within the given of a given number
range. # if the given range is 10
given_range = 10 given_number = 5
for i in range(given_range): for i in range(11):
# if number is divisble by 2 print (given_number," x",i," =",5*i)
# then it's even
if i%2==0: Example 6: Python program to display numbers from a list
# if above condition is true using a for loop.
# print the number # if the below list is given
print(i) list = [1,2,4,6,88,125]
for i in list:
Example 3: Python program to calculate the sum of all numbers from 1 to print(i)
a given number.
# if the given number is 10 Example 7: Python program to count the total number of
given_number = 10 digits in a number.
# set up a variable to store the sum # if the given number is 129475
# with initial value of 0 given_number = 129475
sum = 0 # since we cannot iterate over an integer
# since we want to include the number 10 in the sum # in python, we need to convert the
# increment given number by 1 in the for loop # integer into string first using the
for i in range(1,given_number+1): # str() function
sum+=i given_number = str(given_number)
# print the total sum at the end # declare a variable to store
print(sum) # the count of digits in the
# given number with value 0
Example 4: Python program to calculate the sum of all the odd numbers count=0
within the given range. for i in given_number:
given_range = 10 count += 1
# set up a variable to store the sum # print the total count at the end
# with initial value of 0 print(count)
sum = 0
for i in range(given_range): Example 8: Python program to check if the given string is a
# if i is odd, add it palindrome.
# to the sum variable # given string
if i%2!=0: given_string = "madam"
# an empty string variable to store # initialize a sum variable with
# the given string in reverse # 0 value to store the sum of the product of
reverse_string = "" # each digit
# iterate through the given string sum = 0
# and append each element of the given string # iterate through the given string
# to the reverse_string variable for i in given_number:
for i in given_string: sum += int(i)**string_length
reverse_string = i + reverse_string # if the sum matches the given string
# if given_string matches the reverse_srting exactly # its an amstrong number
# the given string is a palindrome if sum == int(given_number):
if(given_string == reverse_string): print("The given number",given_number,"is an Amstrong
print("The string", given_string,"is a Palindrome.") number.")
# else the given string is not a palindrome # if the sum do not match with the given string
else: # its an amstrong number
print("The string",given_string,"is NOT a Palindrome.") else:
print("The given number",given_number,"is Not an
Example 9: Python program that accepts a word from the user and Amstrong number.")
reverses it.
# input string from user (1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208,
given_string = input() 9474, 54748, 92727, 93084, 548834, 1741725, 4210818,
# an empty string variable to store 9800817, 9926315, 24678050 etc.,)
# the given string in reverse Example 11: Python program to count the number of even
reverse_string = "" and odd numbers from a series of numbers.
# iterate through the given string # given list of numbers
# and append each element of the given string num_list = [1,3,5,6,99,134,55]
# to the reverse_string variable # iterate through the list elemets
for i in given_string: # using for loop
reverse_string = i + reverse_string for i in num_list:
# print the reverse_string variable # if divided by 2, all even
print(reverse_string) # number leave a remainder of 0
if i%2==0:
Example 10: Python program to check if a given number is an Armstrong print(i,"is an even number.")
number # if remainder is not zero
the given number # then it's an odd number
given_number = 153 else:
# convert given number to string print(i,"is an odd number.")
# so that we can iterate through it
given_number = str(given_number) Example 12: Python program to display all numbers within
# store the lenght of the string for future use a range except the prime numbers.
string_length = len(given_number) # import the math library
import math # if number is within range
# function to print all # execute the below code block
# non-primes in a range if nextnum:
def is_not_prime(n): break
# flag to track # print each element that
# if no. is prime or not # satisfies all the above conditions
# initially assume all numbers are print(next)
# non prime
flag = False Example 14: Python program to find the factorial of a given
# iterate in the given range number.
# using for loop starting from 2 # given number
# as 0 & 1 are neither prime given_number= 5
# nor composite # since 1 is a factor
for i in range(2, int(math.sqrt(n)) + 1): # of all number
# condition to check if a # set the factorial to 1
# number is prime or not factorial = 1
if n % i == 0:
flag = True # iterate till the given number
return flag for i in range(1, given_number + 1):
# lower bound of the range factorial = factorial * i
range_starts = 10 print("The factorial of ", given_number, " is ", factorial)
# upper bound of the range
range_ends = 30 Example 15: Python program that accepts a string and
print("Non-prime numbers between",range_starts,"and", range_ends,"are:") calculates the number of digits and letters.
# take string input from user
for number in filter(is_not_prime, range(range_starts, range_ends)): user_input = input()
print(number) # declare 2 variable to store
# letters and digits
Example 13: Python program to get the Fibonacci series between 0 to 50. digits = 0
# given upper bound letters = 0
num = 50 # iterate through the input string
# initial values in the series for i in user_input:
first_value,second_value = 0, 1 # check if the character
# iterate in the given range # is a digit using
# of numbers # the isdigit() method
for n in range(0, num): if i.isdigit():
# if no. is less than 1 # if true, increment the value
# move to next number # of digits variable by 1
if(n <= 1): digits=digits+1
next = n # check if the character
# is an alphabet using Example 17: Python program to check the validity of
# the isalpha() method password input by users.
elif i.isalpha(): # input password from user
# if true, increment the value password = input()
# of letters variable by 1
letters=letters+1 # set up flags for each criteria
print(" The input string",user_input, "has", letters, "letters and", # of a valid password
digits,"digits.") 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
Example 16: Write a Python program that # higher or equal to 8 and lower or equal to 16
iterates the integers from 1 to 25. if (len(password) >= 8) and (len(password)<=16):
# given range has_valid_length = True
given_range = 25 # iterate through each characters
# iterate using a for loop till the # of the password
# given range for i in password:
for i in range(given_range+1): # check if there are lowercase alphabets
# if no. is multiple of 4 and 5 if (i.islower()):
# print fizzbuzz has_lower_case = True
if i % 4 == 0 and i % 5 == 0: # check if there are uppercase alphabets
print("fizzbuzz") if (i.isupper()):
# continue with the loop has_upper_case = True
continue # check if the password has digits
# if no. is divisible by 4 if (i.isdigit()):
# print fizz and no by 5 has_digits = True
if i % 4 == 0 and i%5!=0: # check if the password has special characters
print("fizz") if(i=="@" or i=="$" or i=="_"or i=="#" or i=="^" or
# continue with the loop i=="&" or i=="*"):
continue has_special_characters = True
# if no. is divisible by 5
# print buzz and not by 4 if (has_valid_length==True and has_lower_case ==True and
if i % 5 == 0 and i % 4!= 0: has_upper_case == True and has_digits == True and
print("buzz") has_special_characters == True):
else: print("Valid Password")
# else just print the no. else:
print(i) 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
1.Find the error from the following code:
for i in month:
if i == "February": a = int(input("Enter the value of a:"))
print("The month of February has 28/29 days") for i in range 1 to 11:
elif i in ("April", "June", "September", "November"): if a = i
print("The month of",i,"has 30 days.") a+=i
elif i in ("January", "March", "May", "July", "August", "October", else
"December"): a*=2
print("The month of",i,"has 31 days.")
else:
print(i,"is not a valid month name.") 2.
while i>j;
print(i*j)
i++1

3.
f=1
for i in range(30,70,-3)
print(f*i)

4.
m=1
n=0
for m in range(n:-5:1)
print(m+=5)
5.
c=1
while(c=!0)
sum=sum+c
c++

Output Questions
1.
a = 10
while a<=25: if i==25:
a+10 break
print(a) print(x)
2. 8.
for i in '678': for a in range(50,60):
print('CS Class XI') if a%4==3:
3. continue
for i in range(10,20,6): print(a)
print(i**2)
9.
4.
i,j,n=1,0,0 10.
while i<4: a=0
for j in range(i): for i in range(1,3):
n+=1 for j in range(1,i):
i+=1 x=i+j-1
print(n) if x%2==0:
5. y+=x
i,n=2,0 elif z%3==0:
while i<4: y+=z-2
n+=1 print(y)
i-=1
print(n)

6.
i=1
s=0
while i<10:
print(j,"+")
s=s+j
j=j+j%3
print("=",s)

7.
for i in range(30,40):

You might also like