0% found this document useful (0 votes)
2 views20 pages

python for-loop

The document provides an overview of for loops and while loops in Python, including various examples demonstrating their usage. It covers topics such as printing natural numbers, calculating sums, checking for palindromes, and validating passwords. Additionally, it explains the break statement and its function in controlling loop execution.

Uploaded by

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

python for-loop

The document provides an overview of for loops and while loops in Python, including various examples demonstrating their usage. It covers topics such as printing natural numbers, calculating sums, checking for palindromes, and validating passwords. Additionally, it explains the break statement and its function in controlling loop execution.

Uploaded by

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

Python Raja Sir- 9062813257

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 1: Print the first 10 natural numbers using for loop.


# between 0 to 10 Output
# there are 11 numbers 1
# therefore, we set the value 2
# of n to 11 3
n = 11 4
5
# since for loop starts with 6
# the zero indexes we need to skip it and 7
# start the loop from the first index 8
for i in range(1,n): 9
print(i) 10

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:

# if above condition is true


# print the number
print(i)

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

# 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


Python Raja Sir- 9062813257

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

# 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
# to the sum variable
if i%2!=0:
sum+=i

# print the total sum at the end


print(sum)
Example 5: Python program to print a multiplication table of a given number
# if the given range is 10 Output
given_number = 5 5x0=0
5x1=5
for i in range(11): 5 x 2 = 10
print (given_number," x",i," =",5*i) 5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

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

Example 7: Python program to count the total number of digits in a number.


# if the given number is 129475 Output
given_number = 129475 6

# 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


Python Raja Sir- 9062813257

# 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 Output
given_string = "madam" The string madam is a Palindrome String.

# 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
# 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 9: Python program that accepts a word from the user and reverses it.
# input string from user Input
given_string = input() Naukri

# an empty string variable to store Output


# the given string in reverse irkuaN
reverse_string = ""

# iterate through the given string


# and append each element of the given string
# to the reverse_string variable
for i in given_string:
reverse_string = i + reverse_string

# print the reverse_string variable


print(reverse_string)

Example 10: Python program to check if a given number is an Armstrong number


# the given number Output
given_number = 153
Python Raja Sir- 9062813257

The given number 153 is an Amstrong


# convert given number to string number.
# so that we can iterate through it
given_number = str(given_number)

# store the lenght of the string for future use


string_length = len(given_number)

# initialize a sum variable with


# 0 value to store the sum of the product of
# each digit
sum = 0

# iterate through the given string


for i in given_number:
sum += int(i)**string_length

# if the sum matches the given string


# its an amstrong number
if sum == int(given_number):
print("The given number",given_number,"is an
Amstrong number.")

# if the sum do not match with the given string


# its an amstrong number
else:
print("The given number",given_number,"is Not an
Amstrong number.")

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

# if remainder is not zero


# then it's an odd number
else:
print(i,"is an odd 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

# lower bound of the range


range_starts = 10

# upper bound of the range


range_ends = 30
print("Non-prime numbers
between",range_starts,"and", range_ends,"are:")

for number in filter(is_not_prime, range(range_starts,


range_ends)):
print(number)

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

# if number is within range


# execute the below code block
if nextnum:
break
# print each element that
# satisfies all the above conditions
print(next)
Python Raja Sir- 9062813257

Example 14: Python program to find the factorial of a given number.


# given number Output
given_number= 5 The factorial of 5 is 120

# 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 Input
user_input = input() Naukri1234

# declare 2 variable to store Output


# letters and digits The input string Naukri12345 has 6 letters and
digits = 0 5 digits.
letters = 0

# iterate through the input string


for i in user_input:

# check if the character


# is a digit using
# 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.")

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

# iterate using a for loop till the 2


# given range 3
for i in range(given_range+1): fizz
buzz
# if no. is multiple of 4 and 5 6
# print fizzbuzz 7
if i % 4 == 0 and i % 5 == 0: fizz
print("fizzbuzz") 9
buzz
# continue with the loop 11
continue fizz
13
# if no. is divisible by 4 14
# print fizz and no by 5
buzz
if i % 4 == 0 and i%5!=0:
fizz
print("fizz")
17
18
# continue with the loop
19
continue
# if no. is divisible by 5
fizzbuzz
# print buzz and not by 4 21
if i % 5 == 0 and i % 4!= 0: 22
print("buzz") 23
fizz
else: buzz

# else just print the no.


print(i)

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

# 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
for i in password:

# check if there are lowercase alphabets


if (i.islower()):
has_lower_case = True
Python Raja Sir- 9062813257

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

The Break Statement


The break statement causes immediate exit of the loop. The code that follows the break is never
executed and therefore you can also sometimes use it to avoid nesting in loops. Remember that
break and continue only operate on a single level of the loop. In the case of nested loops, the
break keyword-only terminates the loop where it is located. If a break is present in the innermost
loop, it will only terminate the innermost for loop; any outer loop will continue to run.
Example: Here’s a simple program that will prompt the user to input a string and then convert it to
upper case. The program should continue asking the user for the input until the value provided by
the user is either ‘q’ or ‘Q’. If the user types ‘q’ or ‘Q’, the program stops executing.
#Cancel the execution of while loop with break String to convert [type q or Q to quit]: q
statement Q
while True:
stuff = input("String to convert [type q or Q to quit]: ")
if stuff == "q" or stuff == "Q":
break
print(stuff.upper())
As you can see, the program prompts the user to provide the input string from the keyboard via
Python’s input() function and then prints the uppercase version of the string. The control breaks
out of the while loop when the user enters either ‘q’ or ‘Q’.
The continue statement
Sometimes you might not want to break out of the loop but just want to skip ahead to the next
iteration. In such a case, the continued statement comes to your rescue. It causes an immediate
jump to the top of a loop. Just like break statements, you can use it to avoid statement nesting.
Here’s a simple example:
Python Raja Sir- 9062813257

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.

#Example1: Compute the average of numbers given by


user
sum = 0
counter = 0
while (True):
input_value = input('Enter a number: ')
if input_value == 'done' or input_value == "Done":
break
value = float(input_value)
sum = sum + value #keeps track of the total sum
counter = counter + 1 #keeps the count of number of
inputs entered
average = sum / counter
print('Average:', average)

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)

Calculate binary representation of a given number


Example 3: Write a program that will calculate the binary representation of a given number.
#Example3: Calculate binary representation of given Please enter an integer: 2
number The wrong order [0, 1]
z = int(input("Please enter an integer: ")) The binary representation of 0 is [1, 0]
binary = [ ] #this will store the binary representation of
the number
while z > 0:
remainder = z % 2 #reminder after division by 2
binary.append(remainder) #keeps track of the
reminders
z //= 2 #dividing by two
print("The wrong order", binary)
binary = binary[::-1] #reversing the order of remainders
print("The binary representation of", z ,"is", binary)

Check if the Given String is an Abecedarian Series


Abecedarian series refers to a sequence or list in which the elements appear in alphabetical order.
Example: “ABCDEFGH” is an abecedarian series, while “BOB” is not.
#Example4: Check if a Given String is an Abecedarian True
Series False
def is_abecedarian(string):
i=0
while i< len(string) - 1:
if string[i + 1] < string[i]:
return False
i=i+1
return True

print(is_abecedarian('BCDEFGH'))
print(is_abecedarian('BOB'))
Python Raja Sir- 9062813257

Conditional Statements in Python


As the name suggests, a conditional statement is used to handle conditions in your program. These
statements guide the program while making decisions based on the conditions encountered by the
program. In this article, we will explore three conditional statements in Python: if statement, if-else
statements, if-elif-else ladder.

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.

Python has 3 key Conditional Statements that you should know:


• if statement
• if-else statement
• if-elif-else ladder
Let’s discuss each of them in detail.
if Statement
The if statement is a conditional statement in Python used to determine whether a block of code
will be executed. If the program finds the condition defined in the if statement true, it will execute
the code block inside the if statement.
Syntax:
if condition:
# execute code block
To better understand this, take a look at the below 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
elements of the list 5 is an odd number
for i in list_of_numbers:
# check if no. is odd
if i % 2 != 0:
# if condition is True print "odd"
print (i, "is an odd number")
# check if no. is even
if i % 2 == 0:
# if condition is false print "even"
print (i, "is an even number")
Python Raja Sir- 9062813257

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:

# check if no. is odd


if i%2 != 0:

# if condition is True print "odd"


print(i, "is an odd number")

# if the no. is not odd then the no. is even therfore


print "even"
else:

# if condition is True print "even"


print(i, "is an even number")

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"

# check if value in the string variable


# matches "Shik"
if string == "Shik":
print ("The first condition is true")

# check if value in the string variable


Python Raja Sir- 9062813257

# matches "Shiksha"
elif string == "Shiksha":
print("The second condition is true")

# check if value in the string variable


# matches "Online"
elif string == "Online":
print("The third condition is true")

# check if value in the string variable


# matches "ShikshaOnline"
elif string=="ShikshaOnline":
print("The fourth condition is true")

# if none of the above


# conditions evaluate to true
# execute the code inside the else block
else:
print ("All the above conditions are false")

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:

# condition1: check if no. is odd


# if yes execute the code block inside the first if
statement
if i%2!=0:

# condition2: check if no. is also divisible by 3.


if i%3==0:

# 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

print (i, "is an odd number but not divisible by


3")

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

Example: Check if student passed the exam

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!

Otherwise (number smaller than 50):


Output

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!")

if score < 50:


print("Sorry, you have failed your exam.")

Example: Python if...elif...else statement


score = 105
Output
if score > 100 or score < 0:
print("Score is invalid.")
Python Raja Sir- 9062813257

elif score >= 50:


print("You have passed your exam.") Score is invalid.
print("Congratulations!")
else:
print("Sorry, you have failed your exam.")

Example: Python Nested if Statement

Let's check when the number is positive, either it is odd or even.


num = 5
Output
if num > 0:
if num % 2 == 0: Number is odd
print('Number is even')
else:
print('Number is odd')
else:
print('Number is a non-positive integer')

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:

code to be executed if condition is true

grade = 34

if grade >= 60:


print('You passed the exam.')
print('Congratulations!')

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:

code to be executed if condition is true

else:
Python Raja Sir- 9062813257

code to be executed if condition is false

grade = 34

if grade >= 60:


print("You passed the exam.")
print("Congratulations!")
else:
print("You failed the exam.")
print("Better luck next time.")

You failed the exam.


Better luck next time.

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:

code to be executed if condition is true

elif condition2:

code to be executed if condition1 is false, but condition2 is true

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:

code to be executed if all above conditions are false.

We can include as many conditions as we would like in an if-elif-else statement. However, It is


important to note that only one portion of the code will be allowed to execute. It is possible that
multiple conditions might potentially evaluate to True, but as soon as the if-elif-else statement
encounters its first True condition, it will execute the code for that condition, and will then skip the rest
of the statment.

The example below provides an example with a single elif clause.


Python Raja Sir- 9062813257

grade = 85 You got a 'B' on the exam.

if grade >= 90:

print("You got an 'A' on the exam.")

elif grade >= 80:

print("You got a 'B' on the exam.")

elif grade >= 70:

print("You got a 'C' on the exam.")

elif grade >= 60:

print("You got a 'D' on the exam.")

else:

print("You got an 'F' on the exam.")

Examples of Conditional Statements¶


Conditional Statements and Loops¶
We will often use if statements in conjunctions with loops. In the example below, we are provided with
two lists, one that contains the names of several students, and one that contains the grades that these
students got on an exam. We will loop over these lists, printing a different message for each student.

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.

for i in range(0, len(names) ): Chad got a grade of 'B' on the exam.

if grades[i] >= 90: Drew got a grade of 'F' on the exam.


print(names[i] + " got a grade of 'A' on the
exam.") Elsa got a grade of 'C' on the exam.
elif grades[i] >= 80:
print(names[i] + " got a grade of 'B' on the Fred got a grade of 'D' on the exam.
exam.")
elif grades[i] >= 70:
print(names[i] + " got a grade of 'C' on the
exam.")
elif grades[i] >= 60:
print(names[i] + " got a grade of 'D' on the
exam.")
else:
print(names[i] + " got a grade of 'F' on the
exam.")
Python Raja Sir- 9062813257

Example: Determining if Elements of a


List are Odd or Even
my_list = [74, -55, -77, 58, 0, 91, 62, 0, -91, 61] 74 is even.
-55 is odd.
for i in range(0, len(my_list)): -77 is odd.
if my_list[i] % 2 == 0: 58 is even.
print(str(my_list[i]) + " is even.") 0 is even.
else: 91 is odd.
print(str(my_list[i]) + " is odd.") 62 is even.
0 is even.
-91 is odd.
61 is odd.

Example: Determining if Elements of a


List are Positive, Negative, or Neither¶
The cell below contains a look that will print out one of the following messages for each item in my_list.

for i in range(0, len(my_list)): 74 is positive.


-55 is negative.
if my_list[i] < 0: -77 is negative.
print(str(my_list[i]) + " is negative.") 58 is positive.
elif my_list[i] > 0: 0 is neither positive nor negative.
print(str(my_list[i]) + " is positive.") 91 is positive.
else: 62 is positive.
print(str(my_list[i]) + " is neither positive nor 0 is neither positive nor negative.
negative.") -91 is negative.
61 is positive.

Example: Classifying Credit Scores¶


Two lists are given below. One provides a list of names. The other provides a list of credit scores
associated with each of the people in the first list. Assume that credit scores are classified as follows:

• 0 - 599 is considered “bad”.


• 600 - 649 is considered “poor”.
• 650 - 699 is considered “fair”.
• 700 - 749 is considered “good”.
• 750 and up is considered “excellent”.
• names = ['Anna', 'Beth', 'Chad', 'Drew', 'Elsa', Anna has a fair credit score.
'Fred'] Beth has a bad credit score.
• credit = [683, 580, 752, 607, 615, 703] Chad has a excellent credit score.
• for i in range(0, len(names)): Drew has a poor credit score.
• Elsa has a poor credit score.
• if(credit[i] <= 599): Fred has a good credit score.
• print(names[i] + " has a bad credit score.")
• elif(credit[i] <= 649):
• print(names[i] + " has a poor credit score.")
Python Raja Sir- 9062813257

• elif(credit[i] <= 699):


• print(names[i] + " has a fair credit score.")
• elif(credit[i] <= 749):
• print(names[i] + " has a good credit
score.")
• else:
• print(names[i] + " has a excellent credit
score.")

You might also like