Python For Loop-Programs
Python For Loop-Programs
1. # Code to find the sum of squares of each element of the list using for loop
2.
3. # creating the list of numbers
4. numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
5.
6. # initializing a variable that will store the sum
7. sum_ = 0
8.
9. # using for loop to iterate over the list
10. for num in numbers:
11.
12. sum_ = sum_ + num ** 2
13.
14. print("The sum of squares is: ", sum_)
Output:
1. my_list = [3, 5, 6, 8, 4]
2. for iter_var in range( len( my_list ) ):
3. my_list.append(my_list[iter_var] + 2)
4. print( my_list )
Output:
[3, 5, 6, 8, 4, 5, 7, 8, 10, 6]
Code
1. # Code to find the sum of squares of each element of the list using for loop
2.
1
3. # creating the list of numbers
4. numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
5.
6. # initializing a variable that will store the sum
7. sum_ = 0
8.
9. # using for loop to iterate over list
10. for num in range( len(numbers) ):
11.
12. sum_ = sum_ + numbers[num] ** 2
13.
14. print("The sum of squares is: ", sum_)
Output:
Output:
2
Marks of Itika are: 90
Marks of Parker are: There is no student of name Parker in the records
Nested Loops
If we have a piece of content that we need to run various times and, afterward, one
more piece of content inside that script that we need to run B several times, we
utilize a "settled circle." While working with an iterable in the rundowns, Python
broadly uses these.
Code
1. import random
2. numbers = [ ]
3. for val in range(0, 11):
4. numbers.append( random.randint( 0, 11 ) )
5. for num in range( 0, 11 ):
6. for i in numbers:
7. if num == i:
8. print( num, end = " " )
Output:
0 2 4 5 6 7 8 8 9 10
Program code 1:
Now we give code examples of while loops in Python for printing numbers from 1 to
10. The code is given below -
1. i=1
2. while i<=10:
3. print(i, end=' ')
4. i+=1
Output:
Now we compile the above code in python, and after successful compilation, we run
it. Then the output is given below -
1 2 3 4 5 6 7 8 9 10
Program Code 2:
Now we give code examples of while loops in Python for Printing those numbers
divisible by either 5 or 7 within 1 to 50 using a while loop. The code is given below -
3
1. i=1
2. while i<51:
3. if i%5 == 0 or i%7==0 :
4. print(i, end=' ')
5. i+=1
Output:
Now we compile the above code in python, and after successful compilation, we run
it. Then the output is given below -
5 7 10 14 15 20 21 25 28 30 35 40 42 45 49 50
In this example, we will use the while loop for printing the multiplication table of a
given number. The code is given below -
ADVERTISEMENT
1. num = 21
2. counter = 1
3. # we will use a while loop for iterating 10 times for the multiplication table
4. print("The Multiplication Table of: ", num)
5. while counter <= 10: # specifying the condition
6. ans = num * counter
7. print (num, 'x', counter, '=', ans)
8. counter += 1 # expression to increment the counter
Output:
Now we compile the above code in python, and after successful compilation, we run
it. Then the output is given below -
4
Now we give code examples of while loops in Python for square every number of a
list. The code is given below -
Output:
Now we compile the above code in python, and after successful compilation, we run
it. Then the output is given below -
In the preceding example, we execute a while loop over a given list of integers that
will repeatedly run if an element in the list is found.
Program Code 2:
Now we give code examples of while loops in Python for determine odd and even
number from every number of a list. The code is given below -
Output:
Now we compile the above code in python, and after successful compilation, we run
it. Then the output is given below -
It is an odd number
It is an even number
It is an even number
It is an even number
5
It is an even number
It is an odd number
It is an odd number
It is an even number
Program Code 3:
Now we give code examples of while loops in Python for determine the number
letters of every word from the given list. The code is given below -
Output:
Now we compile the above code in python, and after successful compilation, we run
it. Then the output is given below -
5
4
3
2
We can construct a while loop with multiple conditions in this example. We have
given two conditions and a and keyword, meaning the Loop will execute the
statements until both conditions give Boolean True.
Program Code:
Now we give code examples of while loops in Python for multiple condition. The
code is given below -
1. num1 = 17
2. num2 = -12
3.
4. while num1 > 5 and num2 < -5 : # multiple conditions in a single while loop
5. num1 -= 2
6. num2 += 3
7. print( (num1, num2) )
6
Output:
Now we compile the above code in python, and after successful compilation, we run
it. Then the output is given below -
(15, -9)
(13, -6)
(11, -3)
Code
1. num1 = 17
2. num2 = -12
3.
4. while num1 > 5 or num2 < -5 :
5. num1 -= 2
6. num2 += 3
7. print( (num1, num2) )
Output:
Now we compile the above code in python, and after successful compilation, we run
it. Then the output is given below -
(15, -9)
(13, -6)
(11, -3)
(9, 0)
(7, 3)
(5, 6)
We can also group multiple logical expressions in the while loop, as shown in this
example.
Code
1. num1 = 9
2. num = 14
3. maximum_value = 4
4. counter = 0
5. while (counter < num1 or counter < num2) and not counter >= maximum_value: # g
rouping multiple conditions
6. print(f"Number of iterations: {counter}")
7. counter += 1
Output:
7
Now we compile the above code in python, and after successful compilation, we run
it. Then the output is given below -
Number of iterations: 0
Number of iterations: 1
Number of iterations: 2
Number of iterations: 3
Continue Statement
It returns the control of the Python interpreter to the beginning of the loop.
Code
Now we compile the above code in python, and after successful compilation, we run
it. Then the output is given below -
Output:
Current Letter: W
Current Letter: h
Current Letter: l
Current Letter:
Current Letter: L
Current Letter: p
Current Letter: s
8
Break Statement
It stops the execution of the loop when the break statement is reached.
Code
Output:
Now we compile the above code in python, and after successful compilation, we run
it. Then the output is given below -
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for
classes, functions, and empty control statements.
Code
Now we compile the above code in python, and after successful compilation, we run
it. Then the output is given below -
Output:
9
Content
Example 1: Print the first 10 natural numbers using for loop.
Example 2: Python program to print all the even numbers within the given range.
Example 3: Python program to calculate the sum of all numbers from 1 to a given number.
Example 4: Python program to calculate the sum of all the odd numbers within the given
range.
Example 5: Python program to print a multiplication table of a given number
Example 6: Python program to display numbers from a list using a for loop.
Example 7: Python program to count the total number of digits in a number.
Example 8: Python program to check if the given string is a palindrome.
Example 9: Python program that accepts a word from the user and reverses it.
Example 10: Python program to check if a given number is an Armstrong number
Example 11: Python program to count the number of even and odd numbers from a series of
numbers.
Example 12: Python program to display all numbers within a range except the prime numbers.
Example 13: Python program to get the Fibonacci series between 0 to 50.
Example 14: Python program to find the factorial of a given number.
Example 15: Python program that accepts a string and calculates the number of digits and
letters.
Example 16: Write a Python program that iterates the integers from 1 to 25.
Example 17: Python program to check the validity of password input by users.
Example 18: Python program to convert the month name to a number of days.
Example 3:
# if the given number is 10
given_number = 10
sum = 0
for i in range(1,given_number+1):
sum+=i
print(sum)
given_range = 10
sum = 0
for i in range(given_range):
# if i is odd, add it
10
# to the sum variable
if i%2!=0:
sum+=i
print(sum)
given_number = 129475
# str() function
given_number = str(given_number)
count=0
for i in given_number:
count += 1
print(count)
given_string = "madam"
reverse_string = ""
for i in given_string:
reverse_string = i + reverse_string
if(given_string == reverse_string):
else:
given_number= 5
# since 1 is a factor
# of all number
factorial = 1
factorial = factorial * i
Example 15: Python program that accepts a string and calculates the
number of digits and letters.
# take string input from user
user_input = input()
digits = 0
letters = 0
for i in user_input:
# is a digit using
12
# the isdigit() method
if i.isdigit():
# of digits variable by 1
digits=digits+1
# is an alphabet using
elif i.isalpha():
# of letters variable by 1
letters=letters+1
Input
Naukri1234
Output
The input string Naukri12345 has 6 letters and 5 digits.
Example 17: Python program to check the validity of password input
by users.
# input password from user
password = input()
# of a valid password
has_valid_length = False
has_lower_case = False
has_upper_case = False
has_digits = False
has_special_characters = False
has_valid_length = True
# of the password
13
for i in password:
if (i.islower()):
has_lower_case = True
if (i.isupper()):
has_upper_case = True
if (i.isdigit()):
has_digits = True
has_special_characters = True
print("Valid Password")
else:
print("Invalid Password")
for i in month:
if i == "February":
else:
Output
The month of January has 31 days.
The month of April has 30 days.
The month of August has 31 days.
14
The month of June has 30 days.
November is not a valid month name
15