If Conditions & Loops in Python#

Python if statement#

In control statements, The if statement is the simplest form. It takes a condition and evaluates to either True or False.

If the condition is True, then the True block of code will be executed, and if the condition is False, then the block of code is skipped, and The controller moves to the next line.

Syntax:#

if(condition):
    statement 1
    statement 2
    statement n
  • An if statement should be preceded by the keyword if and ended with a colon :. The condition of an if statement can be written with or without round brackets ().

  • In Python, the body of the if statement is indicated by the indentation. The body starts with an indentation and the first unindented line marks the end.

  • Python interprets non-zero values as True. None and 0 are interpreted as False.

IF statement#

# Example

# Assume the student's grade
student_score = 64

# Check if the grade is equal to or higher than the passing threshold
if student_score <= 65:
    # If the condition is true, print a message indicating a passing grade
    print("Students has scored passing grades")
Students has scored passing grades
# Assume the student's grade
student_score = 50

# Check if the grade is equal to or higher than the passing threshold
if student_score >= 65:
    # If the condition is true, print a message indicating a passing grade
    print("Students has scored passing grades")
# Checking if a number is positive and printing an appropriate message

# First example with a positive number
positive_num = 3

# Check if the number is greater than 0
if positive_num > 0:
    # If the condition is true, print a message indicating a positive number
    print(positive_num, "is a positive number.")

# Regardless of the condition, this line is always printed
print("This is always printed.")


# Second example with a negative number
negative_num = -1

# Check if the number is greater than 0
if negative_num < 0:
    # Since the condition is false, this block is not executed
    print(negative_num, "is a negative number.")

# Regardless of the condition, this line is always printed
print("This is also always printed.")
3 is a positive number.
This is always printed.
-1 is a negative number.
This is also always printed.
# Calculating the square of a number if it is greater than 6

# Assume the given number
given_number = 11

# Check if the number is greater than 6
if given_number > 6:
    # If the condition is true, calculate the square of the number
    square_result = given_number * given_number
    print("The square of", given_number, "is:", square_result)

# Regardless of the condition, this line is always printed
print('Next lines of code')
The square of 11 is: 121
Next lines of code

Shortcut for if statement (Short-hand if or one-line if)#

num1, num2 = 5, 6
if(num1 < num2): print("num1 is less than num2")
num1 is less than num2
# Example: Checking if the value of first_number is less than second_number

# Assume two numbers, first_number and second_number
first_number, second_number = 5, 6

# Check if the value of first_number is less than second_number
if (first_number < second_number): print(first_number, "is less than" ,second_number)
    # If the condition is true, print a message indicating that first_number is less than second_number
5 is less than 6

Python if-else statement#

# Example: Checking different cases based on the value of 'comparison_value'

# Assume a comparison value 'comparison_value'
comparison_value = 1

# Check if the comparison value is greater than 3
if comparison_value > 3:
    # If the condition is true, print a message indicating Case 1
    print("Case 1: The value is greater than 3")

# Check if the comparison value is less than or equal to 3
if comparison_value <= 3:
    # If the condition is true, print a message indicating Case 2
    print("Case 2: The value is less than or equal to 3")
Case 2: The value is less than or equal to 3

The if-else statement checks the condition and executes the if block of code when the condition is True, and if the condition is False, it will execute the else block of code.

Syntax :

if condition:

  statement 1

else:

  statement 2

if..else statement evaluates condition and will execute the body of if only when the test condition is True.

If the condition is False, the body of else is executed. Indentation is used to separate the blocks.

# Example: Checking if a student passed or failed based on the 'student_grade'

# Assume the student's grade
student_grade = 60

# Check if the student's grade is greater than or equal to the passing threshold
if student_grade >= 65:
    # If the condition is true, print a message indicating a passing grade
    print("Student has scored Passing grade")
else:
    # If the condition is false, print a message indicating a failing grade
    print("Student has scored Failing grade")
Student has scored Failing grade
# Example: Checking if a number is positive, negative, or zero and displaying an appropriate message

#Prompt the user to enter a number
given_number = input("Please enter any number: ")

# Uncomment and try these two variations as well.
# given_number = -5
# given_number = 0

# Check if the given number is greater than or equal to 0
if int(given_number) > 0:
    # If the condition is true, print a message indicating a positive number or zero
    print(given_number, "is Positive")
elif int(given_number) == 0:
        print(given_number, "is zero")
else:
    # If the condition is false, print a message indicating a negative number
    print(given_number, "is a Negative number")
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Cell In[9], line 4
      1 # Example: Checking if a number is positive, negative, or zero and displaying an appropriate message
      2 
      3 #Prompt the user to enter a number
----> 4 given_number = input("Please enter any number: ")
      6 # Uncomment and try these two variations as well.
      7 # given_number = -5
      8 # given_number = 0
      9 
     10 # Check if the given number is greater than or equal to 0
     11 if int(given_number) > 0:
     12     # If the condition is true, print a message indicating a positive number or zero

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.13_qbz5n2kfra8p0\LocalCache\local-packages\Python313\site-packages\ipykernel\kernelbase.py:1281, in Kernel.raw_input(self, prompt)
   1279 if not self._allow_stdin:
   1280     msg = "raw_input was called, but this frontend does not support input requests."
-> 1281     raise StdinNotImplementedError(msg)
   1282 return self._input_request(
   1283     str(prompt),
   1284     self._parent_ident["shell"],
   1285     self.get_parent("shell"),
   1286     password=False,
   1287 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
num = 3
if num >0:
    
 print("Positive number")    
Positive number
# login program and indentation

email = input('enter email')
password = input('enter password')

if email == 'fahad1078397@gmail.com' and password == '1234':
  print('Welcome')
elif email == 'fahad1078397@gmail.com' and password != '1234':
  # tell the user
  print('Incorrect password')
  password = input('enter password again')
  if password == '1234':
    print('Welcome,finally!')
  else:
    print('beta tu rehny de!')
else:
  print('Not correct')
Incorrect password
beta tu rehny de!
Not correct

if-else examples#

1. Find the min of 3 given numbers#

What is Loop ?#

A loop is a programming concept that allows for the repetition of a set of instructions multiple times.

Python - For Loops#

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

you’ll learn to iterate over a sequence of elements using the different variations of for loop. We use a for loop when we want to repeat a code block for a fixed number of times.

Why use for loop?#

Definite Iteration: When we know how many times we wanted to run a loop, then we use count-controlled loops such as for loops. It is also known as definite iteration. For example, Calculate the percentage of 50 students. here we know we need to iterate a loop 50 times (1 iteration for each student).

Reduces the code’s complexity: Loop repeats a specific block of code a fixed number of times. It reduces the repetition of lines of code, thus reducing the complexity of the code. Using for loops and while loops we can automate and repeat tasks in an efficient manner.

Loop through sequences: used for iterating over lists, strings, tuples, dictionaries, etc., and perform various operations on it, based on the conditions specified by the user.

# print the Hello World using the print statement
print(" Hello World")
print(" Hello World")
print(" Hello World")
print(" Hello World")
print(" Hello World")
print(" Hello World")
print(" Hello World")
print(" Hello World")
print(" Hello World")
print(" Hello World")
 Hello World
 Hello World
 Hello World
 Hello World
 Hello World
 Hello World
 Hello World
 Hello World
 Hello World
 Hello World
# print the string specific number of times
for i in range(10):
  print("Hello World")
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

Syntax :

for element in sequence:

body of for loop

First, element is the variable that takes the value of the item inside the sequence on each iteration.

Second, all the statements in the body of the for loop are executed with the same value. The body of for loop is separated from the rest of the code using indentation.

Finally, loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.

# For loop 
for i in range(10):
  print(i)
0
1
2
3
4
5
6
7
8
9
for i in range(1,10):
  print(i)
1
2
3
4
5
6
7
8
9
for i in range(1,15,3):
  print(i)
1
4
7
10
13
for i in range(10,0,-2):
  print(i)
10
8
6
4
2
for i in 'Lahore':
  print(i)
L
a
h
o
r
e
for i in [1,2,3,4,5]:
  print(i)
1
2
3
4
5
# Example : Iterating through a list of words using a for loop

# Assume a list of words
number_list = ['one', 'two', 'three', 'four', 'five']

# Iterate through each word in the list
for number in number_list:
    # Print each word
    print(number)
one
two
three
four
five
# Example : Calculating the average of a list of numbers

# Assume a list of numbers
number_list = [10, 20, 30, 40, 50]

# Initialize variables for sum and list size
total_sum = 0
list_size = len(number_list)

# Iterate through each number in the list
for num in number_list:
    # Accumulate the sum of numbers
    total_sum = total_sum + num
    print(total_sum)
    # total_sum += num

# Calculate the average by dividing the sum by the number of items in the list
average = total_sum / list_size

# Print the calculated average
print("The average of the numbers is:", average)
10
30
60
100
150
The average of the numbers is: 30.0

The range() function#

In most cases, we will want to loop through a predetermined list. However, we can also generate a list to loop over “on the fly” with the range() function

for i in range(8):
    print(i)
0
1
2
3
4
5
6
7
# Printing Numbers
for num in range(1, 6):
    print(num)
1
2
3
4
5
# Using the For  loop to print the Items of list and their index
my_list = [10, 20, 30, 40, 50, 60]
for i in range(len(my_list)):
    print(i, my_list[i])
0 10
1 20
2 30
3 40
4 50
5 60

Program - The current population of a town is 10000. The population of the town is increasing at the rate of 10% per year. You have to write a program to find out the population at the end of each of the last 10 years.#

curr_pop = 10000

for i in range(0,10,1):
  print(i,curr_pop)
  curr_pop = curr_pop + 0.1*curr_pop
0 10000
1 11000.0
2 12100.0
3 13310.0
4 14641.0
5 16105.1
6 17715.61
7 19487.171000000002
8 21435.888100000004
9 23579.476910000005

Python while Loop#

Loops are used in programming to repeat a specific block of code. In this article, you will learn to create a while loop in Python. We use a while loop when we want to repeat a code block.

What is while loop in Python?#

The while loop in Python is used to iterate over a block of code as long as the expression/condition is True. When the condition becomes False, execution comes out of the loop immediately, and the first statement after the while loop is executed.

We generally use this loop when we don’t know the number of times to iterate beforehand.

Python interprets any non-zero value as True. None and 0 are interpreted as False.

Why and When to use while loop in Python#

Now, the question might arise: when do we use a while loop, and why do we use it.

  • Automate and repeat tasks: As we know, while loops execute blocks of code over and over again until the condition is met it allows us to automate and repeat tasks in an efficient manner.

  • **Indefinite Iteration:**The while loop will run as often as necessary to complete a particular task. When the user doesn’t know the number of iterations before execution, while loop is used instead of a loop

  • Reduce complexity: while loop is easy to write. using the loop, we don’t need to write the statements again and again. Instead, we can write statements we wanted to execute again and again inside the body of the loop thus, reducing the complexity of the code

  • Infinite loop: If the code inside the while loop doesn’t modify the variables being tested in the loop condition, the loop will run forever.

Syntax:#

while condition:
    body of while loop
  1. In the while loop, expression/condition is checked first.

  2. The body of the loop is entered only if the expression/condition evaluates to True.

  3. After one iteration, the expression/condition is checked again. This process continues until the test_expression evaluates to False.

Note: An infinite loop occurs when a program keeps executing within one loop, never leaving it. To exit out of infinite loops on the command line, press CTRL + C.

# Example: Printing numbers as long as they are less than 60 using a while loop

# Initialize a counter variable
current_number = 1

# Continue looping as long as the current number is less than or equal to 60
while current_number <= 60:
    # Print the current number
    print(current_number)

    # Increment the current number by 1 in each iteration
    current_number = current_number + 1
    # current_number +=1   # this can also be used
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Example : Using a while loop to print "Hello" multiple times

# Initialize a counter variable
loop_counter = 0

# Continue the loop as long as the counter is less than 3
while loop_counter < 3:
    # Print the message along with the current count
    print("Print hello", loop_counter)

    # Increment the counter by 1 in each iteration
    loop_counter = loop_counter + 1
Print hello 0
Print hello 1
Print hello 2
# Example: Calculate how many times a given number can be divided by 3 before it is less than or equal to 10.

# Initialize the counter for the number of iterations
iteration_count = 0

# Set the initial value of the number to be divided
given_number = 180

# Continue the loop while the number is greater than 10
while given_number > 10:
    # Divide the number by 3
    given_number = given_number / 3

    # Increase the count of iterations
    iteration_count = iteration_count + 1

# Print the total number of iterations required
print('Total iterations required:', iteration_count)
Total iterations required: 3
# Example: Program to add natural numbers up to sum = 1+2+3+...+n

# To take input from the user,
n = int(input("Enter n: "))

# n = 100

# initialize sum and counter
sum = 0
i = 1

while i <= n:
    sum = sum + i
    i = i+1    # update counter, i.e., the value of i will change from 1 to 2 in next iteration...

# print the sum
print("The sum is", sum)
The sum is 10

while loop with if-else#

A while loop can have an optional block. We use if-else statement in the loop when conditional iteration is needed. i.e., If the condition is True, then the statements inside the if block will execute othwerwise, the else block will execute.

# Example: Print even and odd numbers between 1 and the entered number.

# Get user input for the upper limit
user_number = int(input('Please Enter a Number: '))

# Start the loop while the entered number is greater than 0
while user_number > 0:
    # Check if the current number is even or odd
    if user_number % 2 == 0:
        print(user_number, 'is an even number')
    else:
        print(user_number, 'is an odd number')

    # Decrease the number by 1 in each iteration
    user_number = user_number - 1
2 is an even number
1 is an odd number
# Example: User Input Validation for a Password

# Initialize an empty string for the user's password
user_password = ""

# Continue prompting for the password until it matches the expected password "secret"
while user_password != "secret":
    # Take user input for the password
    user_password = input("Enter the password: ")

    # Check if the entered password is correct
    if user_password == "secret":
        # If the password is correct, grant access
        print("Access granted!")
    else:
        # If the password is incorrect, deny access
        print("Access denied!")
Access denied!
Access denied!
Access granted!
# Example : Summing Numbers from 1 to 10 using a while loop

# Initialize a variable to store the running total
sum_of_numbers = 0

# Start with the first number
current_number = 1

# Continue adding numbers to the total as long as the current number is less than or equal to 10
while current_number <= 10:
    # Add the current number to the running total
    sum_of_numbers = sum_of_numbers + current_number

    # Increment the current number by 1 in each iteration
    current_number = current_number + 1

# Print the final sum
print("The sum is:", sum_of_numbers)
The sum is: 55
# While loop example -> program to print the table
# Program -> Sum of all digits of a given number
# Program -> keep accepting numbers from users till he/she enters a 0 and then find the avg
number = int(input('enter the number'))
i = 1
while i<11:
  print(number * i)
  i += 1
23
46
69
92
115
138
161
184
207
230
number = int(input('enter the number'))
i = 1
while i<11:
  print(number,'*',i,'=',number * i)
  i += 1
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
# while loop with else

x = 1
while x < 3:
  print(x)
  x += 1
else:
  print('limit crossed')
1
2
limit crossed
# Guessing game

# generate a random integer between 1 and 100
import random
jackpot = random.randint(1,100)

guess = int(input('guess karo'))
counter = 1
while guess != jackpot:
  if guess < jackpot:
    print('galat!guess higher')
  else:
    print('galat!guess lower')

  guess = int(input('guess karo'))
  counter += 1

else:
  print('correct guess')
  print('attempts',counter)
galat!guess lower
galat!guess lower
correct guess
attempts 3

Nested Loops#

# Examples
for i in range(1,5):
  for j in range(1,5):
    print(i,j)
1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4
3 1
3 2
3 3
3 4
4 1
4 2
4 3
4 4
# Program - Unique combination of 1,2,3,4
# Program - Pattern 1 and 2

Pattern 1#

***
****
***

rows = int(input('enter number of rows'))

for i in range(1,rows+1):
  for j in range(1,i+1):
    print('*',end='')
  print()
*
**
***
****
*****

Pattern 2#

1
121
12321
1234321

rows = int(input('enter number of rows'))

for i in range(1,rows+1):
  for j in range(1,i+1):
    print(j,end='')
  for k in range(i-1,0,-1):
    print(k,end='')

  print()
1
121
12321
1234321

Loop Control Statement#

  • Break

  • Continue

  • Pass

# Break demo
for i in range(1,10):
  if i == 6:
    break
  print(i)
1
2
3
4
5
# Break example (Linear Search) -> Prime number in a given range
lower = int(input('enter lower range'))
upper = int(input('enter upper range'))

for i in range(lower,upper+1):
  for j in range(2,i):
    if i%j == 0:
      break
  else:
    print(i)
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
# Continue demo
for i in range(1,10):
  if i == 5:
    continue
  print(i)
1
2
3
4
6
7
8
9
# Pass demo
for i in range(1,10):
  pass