Python Control Flow Statements:- IF-Elif-Else, For & While Loop, Break, Continue, Pass

by | Apr 13, 2024 | Python | 0 comments


Python control flow statements are constructs used to control the flow of execution within a Python program. Python control flow statements are powerful tools that dictate how your program executes. They allow your code to make decisions, repeat tasks conditionally, and organize instructions efficiently.

Q:- How to get Prime Number greater than 5 and Less than 58?

Answer:-

def is_prime(num):
if num <= 1:
return False
elif num <= 3:
return True
elif num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
return True

Iterate through numbers from 6 to 57 and check if they’re prime

prime_numbers = [num for num in range(6, 58) if is_prime(num)]

print(“Prime numbers greater than 5 and less than 58:”, prime_numbers)

Q:How to generate a Fibonacci series within the range of 5 to 57?

Answer:-

def fibonacci_series(start, end):
fibonacci = [0, 1]
while True:
next_fib = fibonacci[-1] + fibonacci[-2]
if next_fib <= end: fibonacci.append(next_fib) else: break return [x for x in fibonacci if x >= start]

start = 5
end = 57
fib_series = fibonacci_series(start, end)
print(“Fibonacci series between”, start, “and”, end, “:”, fib_series)

IF-Elif-Else

Syntax:

if Boolean_condition:
    True statement
elif Boolean_condition:
    True statement
elif Boolean_condition:
    True statement
else:
    False statement

1.

score = 85

if score >= 90:
grade = ‘A’
elif score >= 80:
grade = ‘B’
elif score >= 70:
grade = ‘C’
elif score >= 60:
grade = ‘D’
else:
grade = ‘F’

print(“Grade:”, grade)

2.

username = “user”
password = “password”

entered_username = input(“Enter username: “)
entered_password = input(“Enter password: “)

if entered_username == username and entered_password == password:
print(“Login successful”)
else:
print(“Invalid username or password”)

3.

num = 10

if num % 2 == 0 and num % 3 == 0:
print(“Divisible by both 2 and 3”)
elif num % 2 == 0:
print(“Divisible by 2 but not by 3”)
elif num % 3 == 0:
print(“Divisible by 3 but not by 2”)
else:
print(“Not divisible by 2 or 3”)

num = 15

if num > 0:
print(“Positive number”)
elif num < 0:
print(“Negative number”)
else:
print(“Zero”)

hour = 14

if hour < 12:
greeting = ‘Good morning!’
elif hour < 18:
greeting = ‘Good afternoon!’
else:
greeting = ‘Good evening!’

print(greeting)

grade = 85

if grade >= 90:

print(“Excellent work! You got an A.”)

elif grade >= 80:

print(“Great job! You got a B.”)

else:

print(“Keep practicing! You got a C or below.”)


Ternary operator in Python

The ternary operator in Python provides a concise way to write if-else statements in a single line. Its syntax is:

<expression_if_true> if <condition> else <expression_if_false>
examples:-


x = 10
result = “even” if x % 2 == 0 else “odd”
print(result) # Output: even

a = 5
b = 10
max_num = a if a > b else b
print(max_num) # Output: 10

x = 10
result = “positive” if x > 0 else (“zero” if x == 0 else “negative”)
print(result) # Output: positive

Looping in Python

For Loops

The syntax for a for loop in Python is concise and easy to understand. Here’s a breakdown of its components:

Basic Structure:

Python

for item in iterable:
  # code to be executed for each item

Explanation:

  • for: This keyword initiates the loop.
  • item(Variable): This is a placeholder variable that takes on the value of each item in the sequence during each iteration of the loop. You can choose any meaningful name for this variable.
  • in: This keyword specifies that you’re looping through the elements in the sequence.
  • iterable: This is the iterable object (like a list, string, tuple, etc.) that the loop will iterate over. The for loop will extract each item from the sequence one by one and assign it to the item variable.
  • # code to be executed for each item: This is the indented code block that will be executed for each item in the sequence. The indentation level is crucial! It defines which lines of code are part of the loop body.

Example 1: Looping through a List

Python

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
  print("I like", fruit)

In this example, the loop iterates over the fruits list. In each iteration, the current fruit (e.g., “apple” in the first iteration) is assigned to the fruit variable, and the indented print statement is executed.

Example 2: Looping through a String

Python

name = "Alice"
for letter in name:
  print(letter.upper())  # Print each letter in uppercase

Here, the loop iterates over each letter in the name string. The current letter is assigned to the letter variable in each iteration, and the print statement converts it to uppercase before printing.

Key Points:

  • The for loop automatically handles the iteration and stops when it reaches the end of the sequence.
  • You can use any iterable object (like a dictionary or a custom class with an iterator) in the sequence part.
  • The loop variable (item in our examples) is temporary within the loop and cannot be accessed outside of the loop’s indented block.

By mastering the for loop in Python, you can efficiently iterate over sequences and perform operations on each item, making your code more concise and readable.

Range Function

The range() function is versatile and widely used in Python for generating sequences of numbers. It’s helpful for iterating over sequences, generating lists of numbers, and various other tasks where you need a series of numbers.

range(start, stop[, step])
  • start: The starting value of the sequence (inclusive). If omitted, it defaults to 0.
  • stop: The end value of the sequence (exclusive). This is the number up to which the sequence generates values.
  • step: The step or increment between each number in the sequence. If omitted, it defaults to 1.

Syntax 1: range(start=0,end=len(sequence),step=1)

list(range(1,5))
[0,1,2,3,4]

list(range(1,10,2))
[1,3,5,7,9]

range(stop)

range(3)

range(3+1)

range(start, stop)

range(2, 6)

range(5,10+1)

range(start, stop, step)

range(4, 15+1, 2)

range(2*2, 25, 3+2)

range(10, 0, -2)

Nested for loops

for i in range(1, 4):
for j in range(1, 4):
print(i * j, end=” “)
print() # Print newline after each row

for i in range(5): for j in range(i + 1): print(“*”, end=” “) print() # Print newline after each row

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

transpose = []
for i in range(len(matrix[0])):
transpose_row = []
for row in matrix:
transpose_row.append(row[i])
transpose.append(transpose_row)

print(transpose)

for left in range(7):

  for right in range(left, 7):

    print(“[” + str(left) + “|” + str(right) + “]”, end=” “)

  print()

Written by HintsToday Team

Related Posts

Python- String Data Type & For Loop Combined

It is a case sensitive, non-mutable sequence of characters marked under quotation. It can contain alphabets, digits, white spaces and special characters. In Python, a string is a sequence of characters enclosed within either single quotes (' '), double quotes (" "),...

read more

functions in Python in an interactive way

Functions in Python are blocks of code that perform a specific task, and they can be defined using the def keyword. Definition: A function in Python is a block of reusable code that performs a specific task. It allows you to break down your program into smaller, more...

read more

Python Data Types, Type Casting, Input(), Print()

In Python, data types define the type of data that can be stored in variables. Here are the main data types in Python: 1. Numeric Types: int: Integer values (e.g., 5, -3, 1000) float: Floating-point values (e.g., 3.14, -0.001, 2.0) 2. Sequence Types: str: Strings,...

read more

Get the latest news

Subscribe to our Newsletter

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *