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)
Another Method to find Prime Number:-
def another_method(number):
for i in range(2, number):
if number%i==0:
print(“Not prime”)
break
else:
print(“Prime”)
number = int(input(“Enter a number: “))
another_method(number)
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)
Contents
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 thesequence
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 thesequence
.iterable
: This is the iterable object (like a list, string, tuple, etc.) that the loop will iterate over. Thefor
loop will extract each item from the sequence one by one and assign it to theitem
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()
Break, continue and pass in python with examples
In Python, break
, continue
, and pass
are control flow statements used within loops and conditional statements to alter the program’s execution flow. Here’s a breakdown of each statement with examples:
1. break:
- Terminates the loop prematurely when a specific condition is met.
- Control jumps to the statement after the loop (if any).
Python
fruits = ["apple", "banana", "cherry", "orange"]
for fruit in fruits:
if fruit == "cherry":
print(f"Found {fruit}!")
break # Exit the loop after finding cherry
print(fruit)
# Output:
# apple
# banana
# Found cherry!
2. continue:
- Skips the current iteration of the loop and continues with the next iteration.
- The remaining code within the current iteration is not executed.
Python
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0: # Skip even numbers
continue
print(num)
# Output:
# 1
# 3
# 5
3. pass:
- Acts as a placeholder within a code block.
- It does nothing but maintains the structure, allowing for an empty statement where Python expects one syntactically.
Python
# Example 1: Empty loop (does nothing)
for i in range(5):
pass # Placeholder, loop iterates but does nothing
# Example 2: Conditional statement without an action (no indentation needed)
if age < 18:
pass # Placeholder, no action for underage users
else:
print("You are eligible.")
Choosing the Right Statement:
- Use
break
to exit a loop early when you’ve found what you’re looking for or a certain condition is met. - Use
continue
to skip specific iterations within a loop based on a condition. - Use
pass
as a placeholder when you need a syntactically valid statement but don’t want any action to occur at that point in your code.
0 Comments