Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
370 views

Python For Loop-Programs

The document discusses Python for loops and while loops. It provides examples of using for loops to iterate over lists, find sums and append values. Examples are given for while loops to print numbers, check for even/odd, and multiply tables. Loop control statements like continue and break are also discussed.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
370 views

Python For Loop-Programs

The document discusses Python for loops and while loops. It provides examples of using for loops to iterate over lists, find sums and append values. Examples are given for while loops to print numbers, check for even/odd, and multiply tables. Loop control statements like continue and break are also discussed.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Python for loop

Example of Python for Loop

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:

The sum of squares is: 774

The range() Function


Code

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]

Iterating by Using Index of Sequence


Another method of iterating through every item is to use an index offset within the
sequence. Here's a simple illustration:

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:

The sum of squares is: 774

Using else Statement with for Loop


Code

1. # code to print marks of a student from the record


2. student_name_1 = 'Itika'
3. student_name_2 = 'Parker'
4.
5.
6. # Creating a dictionary of records of the students
7. records = {'Itika': 90, 'Arshia': 92, 'Peter': 46}
8. def marks( student_name ):
9. for a_student in record: # for loop will iterate over the keys of the dictionary
10. if a_student == student_name:
11. return records[ a_student ]
12. break
13. else:
14. return f'There is no student of name {student_name} in the records'
15.
16. # giving the function marks() name of two students
17. print( f"Marks of {student_name_1} are: ", marks( student_name_1 ) )
18. print( f"Marks of {student_name_2} are: ", marks( student_name_2 ) )

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 -

The Multiplication Table of: 21


21 x 1 = 21
21 x 2 = 42
21 x 3 = 63
21 x 4 = 84
21 x 5 = 105
21 x 6 = 126
21 x 7 = 147
21 x 8 = 168
21 x 9 = 189
21 x 10 = 210

Python While Loop with List


Program Code 1:

4
Now we give code examples of while loops in Python for square every number of a
list. The code is given below -

1. # Python program to square every number of a list


2. # initializing a list
3. list_ = [3, 5, 1, 4, 6]
4. squares = []
5. # programing a while loop
6. while list_: # until list is not empty this expression will give boolean True after that False
7. squares.append( (list_.pop())**2)
8. # Print the squares of all numbers.
9. print( squares )

Output:

Now we compile the above code in python, and after successful compilation, we run
it. Then the output is given below -

[36, 16, 1, 25, 9]

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 -

1. list_ = [3, 4, 8, 10, 34, 45, 67,80] # Initialize the list


2. index = 0
3. while index < len(list_):
4. element = list_[index]
5. if element % 2 == 0:
6. print('It is an even number') # Print if the number is even.
7. else:
8. print('It is an odd number') # Print if the number is odd.
9. index += 1

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 -

1. List_= ['Priya', 'Neha', 'Cow', 'To']


2. index = 0
3. while index < len(List_):
4. element = List_[index]
5. print(len(element))
6. index += 1

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

Python While Loop Multiple Conditions


We must recruit logical operators to combine two or more expressions specifying
conditions into a single while loop. This instructs Python on collectively analyzing all
the given expressions of conditions.

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)

Let's look at another example of multiple conditions with an OR operator.

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

Single Statement While Loop


Similar to the if statement syntax, if our while clause consists of one statement, it may
be written on the same line as the while keyword.

Here is the syntax and example of a one-line while clause -

1. # Python program to show how to create a single statement while loop


2. counter = 1
3. while counter: print('Python While Loops')

Loop Control Statements


Now we will discuss the loop control statements in detail. We will see an example of
each control statement.

Continue Statement
It returns the control of the Python interpreter to the beginning of the loop.

Code

1. # Python program to show how to use continue loop control


2.
3. # Initiating the loop
4. for string in "While Loops":
5. if string == "o" or string == "i" or string == "e":
6. continue
7. print('Current Letter:', string)

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

1. # Python program to show how to use the break statement


2.
3. # Initiating the loop
4. for string in "Python Loops":
5. if string == 'n':
6. break
7. print('Current Letter: ', string)

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

1. # Python program to show how to use the pass statement


2. for a string in "Python Loops":
3. pass
4. print( 'The Last Letter of given string is:', string)

Now we compile the above code in python, and after successful compilation, we run
it. Then the output is given below -

Output:

The Last Letter of given string is: s

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

# 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

given_range = 10

# 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

10
# 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


11
# 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

if(given_string == reverse_string):

print("The string", given_string,"is a Palindrome.")

# else the given string is not a palindrome

else:

print("The string",given_string,"is NOT a Palindrome.")

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
12
# 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.")

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()

# 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

13
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.")

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

You might also like