0% found this document useful (0 votes)
844 views15 pages

Python For Loop Examples and Outputs

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
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)
844 views15 pages

Python For Loop Examples and Outputs

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
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
  • Python for Loop
  • Nested Loops
  • Python While Loop
  • Loop Control Statements
  • Examples of Python Programs

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. [Link]( [Link]( 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. [Link]( (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 [Link]():

# 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 [Link]():

# 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 ([Link]()):

has_lower_case = True

# check if there are uppercase alphabets

if ([Link]()):

has_upper_case = True

# check if the password has digits

if ([Link]()):

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

Common questions

Powered by AI

The complexity of loop operations directly impacts code efficiency in Python, particularly in loop-intensive tasks. Complex operations within loops, such as nested iterations or multi-condition evaluations, can lead to increased computational expenses in terms of time and resources. For instance, iterating over lists with multiple logical operators or nested loops could result in higher time complexity . To enhance performance, measures like optimizing condition checks, minimizing nested loops, and leveraging list comprehensions where possible can reduce overhead. Avoiding unnecessary operations within the loop, using efficient data structures, and breaking computation by using control statements like 'break' for early exits when conditions are met are other practices . These strategies can effectively reduce complexity and improve execution efficiency in demanding loop operations.

The initialization and update of conditions within loops are critical for controlling iterations and ensuring proper termination in Python. Proper initialization sets the starting point, while conditional updates guide iteration through defined steps, managing execution. In typical loop scenarios, such as using a counter to iterate, initializing the counter sets a base, and incrementing it by a fixed amount within the loop progresses towards termination. For instance, initializing a counter in a while loop as 1 and specifying updates to increment by 1 leads to iterations until a set maximum like 10 is reached . Failing to update conditions correctly results in infinite loops or premature terminations, highlighting the necessity of properly managing these aspects for predictable executions .

Manipulating a list with a for loop involves iterating over each element directly, which is efficient when the structure already supports sequential access. Using a for loop to square elements of a list can be straightforward: iterate directly over the list, squaring each element and storing the results. Conversely, a while loop iterates based on a condition rather than the structure, making it versatile for scenarios where the list size or initial state may change dynamically. For example, squaring elements of a list using a while loop involves continuing iterations until the list is empty, popping elements at each step, as the condition depends on the list's non-emptiness rather than a static range .

Loop control statements 'break' and 'continue' are used to alter the flow of execution in loops. A 'break' statement immediately exits the loop, abandoning remaining iterations. For instance, in a loop iterating through 'Python Loops', a 'break' is used to exit the loop as soon as the character 'n' is encountered, stopping any further iteration . The 'continue' statement, however, skips the current iteration and proceeds to the next one. For example, during an iteration over the string 'While Loops', 'continue' is employed to skip printing specific vowels ('o', 'i', 'e'), effectively omitting them from the output . These statements are critical for handling specific conditions that require bypassing or terminating iterations during runtime.

In Python, for loops are typically used for iterating over a numerical range or a sequence of elements, with a known number of iterations, as it automatically iterates through the given range or collection. For example, to print natural numbers from 1 to 10, a for loop provides a concise and straightforward approach . On the other hand, while loops are more suitable when the number of iterations is not predetermined, relying instead on a condition to continue execution. A while loop is ideal for scenarios where you need to repeatedly execute code as long as a particular condition remains true, such as processing a list until it is empty . Each has specific applications: for loops are preferred for fixed iterations, while while loops excel in indefinite iteration scenarios based on conditions.

Logical operators such as AND and OR allow multiple conditions to be specified within a while loop, controlling loop execution based on the collective evaluation of these conditions. The AND operator ensures that all conditions must be true for the loop to execute, as shown in the example where two numerical values, num1 and num2, are adjusted within the loop while both conditions (num1 > 5 and num2 < -5) remain true . Conversely, the OR operator allows the loop to continue as long as at least one of the conditions is true, providing greater flexibility and potentially more iterations, as demonstrated in the loop that runs as long as either num1 is greater than 5 or num2 is less than -5 .

Logical operators such as AND and OR have distinct roles when employed within complex condition sets in while loops, determining the conditions under which the loop continues to execute. An example of using an AND operator within a loop involves requiring both conditions to be satisfied: a loop might decrement num1 while incrementing num2 until num1 exceeds 5 and num2 is less than -5, forcing termination if either fails . In contrast, an OR operator permits loop continuation if at least one condition holds, as a loop operating until num1 is greater than 5 or num2 is less than -5 would iterate longer and under broader conditions . Thus, AND operators restrict execution to stricter scenarios, while OR operators facilitate extended loops under more relaxed conditions.

In Python, a while loop can be utilized to manipulate and process elements within a list by iterating over its elements until a specified condition is no longer met. A specific example of this is squaring each element in a list. For instance, if we have a list initialized as list_ = [3, 5, 1, 4, 6], a while loop can iterate over this list, appending the square of each element to a new list, squares, until the original list is empty. This can be achieved by using list_.pop() to remove elements from the list and square them before adding to squares .

A pass statement in Python loops is used as a placeholder, indicating a part of the code where a statement is syntactically required but no action is needed. This can be useful in situations where the loop structure must be maintained but actual execution at that point is not necessary. For example, in iterating over a string 'Python Loops', a pass statement can be used to skip execution but still complete the loop's iteration, followed by a print statement that outputs the last character processed outside of the loop .

Python handles multiple conditions within while loops by evaluating them in sequence using logical operators like AND, OR, and NOT to control loop continuation. A while loop evaluating combined conditions will continue execution only if the logical combination of those conditions is true. For example, combining conditions with an AND operator requires all conditions to be true for the loop to proceed, as seen in a loop that decrements num1 while incrementing num2 until both conditions—num1 > 5 and num2 < -5—become false . On the other hand, an OR operator allows continuation as long as at least one of the conditions is true, providing an extended range of operations under varying conditions . This difference in combining logical operators results in varying loop behaviors, affecting both iteration count and the sequence of executions within the loop.

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  
3. # creating the list of numbers  
4.
numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]  
5.   
6.
# initializing a variable that will 
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 pie
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 compil
Now we give code examples of while loops in Python for square every number of a
list. The code is given below -
1. # Python p
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 o
Output:
Now we compile the above code in python, and after successful compilation, we run
it. Then the output is given below
Now we compile the above code in python, and after successful compilation, we run
it. Then the output is given below -
Number
Break Statement
It stops the execution of the loop when the break statement is reached.
Code
1. # Python program to show how 
Content

Example 1: Print the first 10 natural numbers using for loop.
 
  (https://www.shiksha.com/online-courses/articles/

You might also like