python for-loop
python for-loop
For loops in Python is designed to repeatedly execute the code block while iterating over a sequence or an
iterable object such as list, tuple, dictionary, sets. In this article, we will briefly discuss for loop
in Python with different examples.
Example 2: Python program to print all the even numbers within the given range.
# if the given range is 10 Output
given_range = 10 0
2
for i in range(given_range): 4
6
# if number is divisble by 2 8
# then it's even
if i%2==0:
Example 3: Python program to calculate the sum of all numbers from 1 to a given
number
# if the given number is 10 Output
given_number = 10 55
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 Output
given_range = 10 25
for i in range(given_range):
# if i is odd, add it
# to the sum variable
if i%2!=0:
sum+=i
Example 6: Python program to display numbers from a list using a for loop.
# if the below list is given Output
list = [1,2,4,6,88,125] 1
for i in list: 2
print(i) 4
6
88
125
for i in given_number:
count += 1
Example 9: Python program that accepts a word from the user and reverses it.
# input string from user Input
given_string = input() Naukri
Example 11: Python program to count the number of even and odd numbers from
a series of numbers.
# given list of numbers Output
num_list = [1,3,5,6,99,134,55] 1 is an odd number.
3 is an odd number.
5 is an odd number.
# iterate through the list elemets 6 is an even number.
# using for loop 99 is an odd number.
for i in num_list: 134 is an even number.
55 is an odd number.
# if divided by 2, all even
# number leave a remainder of 0
if i%2==0:
print(i,"is an even number.")
Example 12: Python program to display all numbers within a range except the
prime numbers.
# import the math library Output
import math Non-prime numbers between 10 and 30 are:
10
# function to print all 12
Python Raja Sir- 9062813257
# non-primes in a range 14
def is_not_prime(n): 15
16
# flag to track 18
# if no. is prime or not 20
# initially assume all numbers are 21
# non prime 22
flag = False 24
25
# iterate in the given range 26
# using for loop starting from 2 27
# as 0 & 1 are neither prime 28
# 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
Example 13: Python program to get the Fibonacci series between 0 to 50.
# given upper bound Output
num = 50 1
2
# initial values in the series 3
first_value,second_value = 0, 1 5
8
# iterate in the given range 13
# of numbers 21
for n in range(0, num): 34
# if no. is less than 1
# move to next number
if(n <= 1):
next = n
# since 1 is a factor
# of all number
# set the factorial to 1
factorial = 1
Example 15: Python program that accepts a string and calculates the number of
digits and letters.
# take string input from user Input
user_input = input() Naukri1234
Example 16: Write a Python program that iterates the integers from 1 to 25.
# given range Output
given_range = 25 fizzbuzz
1
Python Raja Sir- 9062813257
Example 17: Python program to check the validity of password input by users
# input password from user Input
password = input() Naukri12345@
Output
# set up flags for each criteria Naukri12345@
# 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
Example 18: Python program to convert the month name to a number of days.
# given list of month name Output
month = ["January", "April", The month of January has 31 days.
"August","June","Dovember"] The month of April has 30 days.
The month of August has 31 days.
# iterate through each mont in the list The month of June has 30 days.
for i in month: November is not a valid month name
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.")
While loop
The while loop repeatedly executes a block of statements as long as the condition evaluates to True. Flow
control is a very important feature in any programming language. The real strength of programming isn’t
just for the programs to start from the first line of code and simply execute every line, straight till the end. A
program should be able to skip over a few instructions, return to them at some other point in time, repeat
them, or simply choose one of several instructions to run. To achieve these tasks, Python provides various
flow control statements, one of which is the while loop.
Python Raja Sir- 9062813257
Python Loops
Loops are important and one of the most basic concepts in any programming language. Looping
basically means being able to repeat the execution of a certain portion of code more than once
(known as iterations), based on loop parameters. Python offers two main looping constructs that
serve different purposes: for and while statements. In this article, let’s focus on the while loop.
The while loop
The python while statement is the simplest and the most basic iteration mechanism. It repeatedly
executes a block of statements (usually indented) as long as the condition evaluates to True.
When the test condition becomes False, the control moves to the statement that follows the while
block. In case the test condition evaluates to False, to begin with, the body of the loop never runs
and the while statement will be entirely skipped. Here’s a simple example that prints the numbers
1 to 10:
#Print numbers 1 to 10 using while loop 1
counter = 1 2
while counter <= 10: 3
print(counter) 4
counter += 1 5
6
7
8
9
10
Example: Write a program that will accept an integer input from the user, and prints the square of
the number if the number is even, and if the number is odd, prints the message “num is odd. Enter
an even number”. Also, the program should stop prompting for input if the user inputs the letter ‘q’
or ‘Q’.
#Skip the current iteration and go to next one with
continue statement
while True:
input_value = input("Integer, please [q (or Q) to quit]:
")
if input_value == 'q' or input_value == 'Q': # quit
break
number = int(input_value)
if number % 2 == 0: # an even number
print(number, "squared is", number*number)
continue
print(number, "is odd. Enter even number")
Example: Write a Python program that validates if given all the items of a given list are odd. If one of the
items is even, the control should break out of the while loop and a relevant message has to be displayed.
#while loop with optional else clause Found even number 2 at the position 3
test_list = [1, 3, 5, 2, 7, 9, 13, 11]
index = 0
while index < len(test_list):
num = test_list[index]
if num % 2 == 0:
print('Found even number', num, "at the position",
index)
break
index += 1
else: # executes when break not called
print('No even number found! The list is odd')
Example 1: Write a program that computes an average. The program should keep asking the user to enter
a number until the user types “done”. When the input is “done”, the program should then display the
average of all the given numbers. Make use of control flow statements and break.
The above program clearly illustrates the functionality of the break statement that we discussed
earlier. When the input provided by the user is either ‘Done’ or ‘done’, the control breaks out of the
while loop and the statement after that is executed.
Python Raja Sir- 9062813257
Use while loop to demonstrate the countdown and print a message when the count is 0
Example 2: Write a program that will demonstrate the countdown. So, the moment the count is 0,
the program should print a message “Happy New Year ”.
#Example2: Demonstrating countdown using while 5
def countdown(m): 4
while m > 0: 3
print(m) 2
m=m-1 1
print("Happy New Year!!") Happy New Year!!
countdown(5)
print(is_abecedarian('BCDEFGH'))
print(is_abecedarian('BOB'))
Python Raja Sir- 9062813257
Like every other programming language, Python also has some predefined conditional statements. A
conditional statement as the name suggests itself, is used to handle conditions in your program. These
statements guide the program while making decisions based on the conditions encountered by the
program.
if-else Statement
As discussed above, the if statement executes the code block when the condition is true. Similarly,
the else statement works in conjuncture with the if statement to execute a code block when the
defined if condition is false.
Syntax:
if condition:
# execute code if condition is true
else:
# execute code if condition if False
Now, let’s expand on this concept in the previous example.
Python Example: Python program to check if a number is odd or even.
# list of numbers 2 is an even number
list_of_numbers = [2,4,6,9,5] 4 is an even number
6 is an even number
# for loop to iterate through the list and check each 9 is an odd number
element of the list 5 is an odd number
for i in list_of_numbers:
if-elif-else ladder
The elif statement is used to check for multiple conditions and execute the code block within if any
of the conditions are evaluated to be true.
The elif statement is similar to the else statement in that it is optional. Still, unlike the else
statement, multiple elif statements can be in a block of code following an if statement.
if condition1:
# execute this statement
elif condition2:
# execute this statement
..
..
else:
# if non of the above conditions evaluate to True execute this statement
Take a look at the below example for context.
Python Example: Python program to check if a string matches the condition.
# take a sample string The fourth condition is true
string ="ShikshaOnline"
# matches "Shiksha"
elif string == "Shiksha":
print("The second condition is true")
Output:
The fourth condition is true
Nested if Statements:
A nested if statement is considered as if within another if statement(s). These are generally used
to check for multiple conditions.
Syntax:
if condition1:
if condition2:
# execute code if both condition1and condition2 are True
Look at the example below for a better understanding of nested if statements.
Python Example: Python program to check if a number is odd and divisible by 3.
# list of numbers 4 is an even number
list_of_numbers = [4,5,9,17,21] 5 is an odd number but not divisible by 3
9 is an odd number & divisible by 3
# for loop to iterate through the list and check each 17 is an odd number but not divisible by 3
element of the list 21 is an odd number & divisible by 3
for i in list_of_numbers:
# if condition2 is true
# execute the below code block
print (i,"is an odd number & divisible by 3")
# if codition2 if False
# execute the below code block
else:
Python Raja Sir- 9062813257
# if condition1 is False
# execute the below code block
else:
print(i,"is an even number")
Conclusion:
In this article, we explored the following concepts:
• What is the if statement?
• How does it work?
• What is the if-else statement?
• What is the if-elif-else ladder?
• How do nested if statements work?
Suppose you are a university student and to pass the examination you need to
score 50 or more. Let's look at a program to check if you passed the exam.
score = int(input("Enter a number: "))
For a number greater than or equal to 50:
if score >= 50: Output
print("You have passed your exams.")
print("Congratulations!")
Enter a number: 75
You have passed your exams.
Congratulations!
Enter a number: 35
We can see nothing is printed as the if block is skipped. We can add one more if statement to
handle this as:
score = 35
Output
if score >= 50:
print("You have passed your exam.") Sorry, you have failed your exam.
print("Congratulations!")
Conditional Statements¶
We can use conditional statements to control how or if portions of our code will execute, based on
logical criteria that we provide. The most basic type of conditional statement is an if statement. The
syntax for an if statement is as follows:
if condition:
grade = 34
If-Else Statements
We can use an if statemnt to determine whether or not a particular set of actions will be satisfied. But
we will occasionally want to use a condition to determine which of two sets of actions will be
completed. This functionality is provided to us by an if-else statement. The syntax for an if-else
statement is as follows:
if condition:
else:
Python Raja Sir- 9062813257
grade = 34
If-Elif-Else Statements¶
If statements allow us to determine whether or not a single set of actions will be taken, and if-else
statments allow us to determine which of two sets of actions will be taken. If we require our program to
select from more than two options when making a decision, we can use an if-elif-else statment. The
syntax for this sort of statement is as follows:
if condition1:
elif condition2:
elif condition3:
code to be executed if all above conditions are false, but condition3 is true
elif condition4:
code to be executed if all above conditions are false, but condition4 is true
...
else:
else:
names = ['Anna', 'Beth', 'Chad', 'Drew', 'Elsa', Anna got a grade of 'F' on the exam.
'Fred']
grades = [56, 92, 87, 43, 75, 62] Beth got a grade of 'A' on the exam.