Skip to main content

Conditional Statements in Python & Control Flow Statements

Conditional statements

Conditional statements allow you to execute a block of code only if a specific condition is true.

Syntax


if condition: # code to execute if condition is true elif another_condition: # code to execute if another_condition is true else: # code to execute if all conditions are false

Examples

  1. Simple if statement

age = 18 if age >= 18: print("You are eligible to vote.") # Output: You are eligible to vote.
  1. if-else statement

num = 10 if num % 2 == 0: print("Even number") else: print("Odd number") # Output: Even number
  1. if-elif-else ladder

marks = 85 if marks >= 90: print("Grade: A") elif marks >= 75: print("Grade: B") else: print("Grade: C") # Output: Grade: B
  1. Nested if statements

num = 10 if num > 0: if num % 2 == 0: print("Positive even number") else: print("Positive odd number") else: print("Negative number or zero") # Output: Positive even number

Control Flow Statements

Control flow statements are used to alter the natural sequence of execution in a program.

Types of Control Flow Statements

a. for Loop

Iterates over a sequence (list, tuple, string, etc.).

Example:


for i in range(1, 6): print(i) # Output: # 1 # 2 # 3 # 4 # 5

b. while Loop

Executes a block of code as long as a condition is true.

Example:


count = 1 while count <= 5: print(count) count += 1 # Output: # 1 # 2 # 3 # 4 # 5

c. break

Exits a loop prematurely.

Example:


for i in range(1, 6): if i == 3: break print(i) # Output: # 1 # 2

d. continue

Skips the current iteration and moves to the next.

Example:


for i in range(1, 6): if i == 3: continue print(i) # Output: # 1 # 2 # 4 # 5

e. pass

Does nothing; a placeholder for future code.

Example:


if True: pass # Code to be added later

f. else with Loops

You can attach an else block to a loop, which executes if the loop completes without a break.

Example:


for i in range(1, 6): if i == 3: break else: print("Loop completed without a break.") # Output: (No output because the loop breaks)

3. Example: Combining Conditional and Control Flow Statements


for i in range(1, 10): if i % 2 == 0: print(f"{i} is even") else: print(f"{i} is odd") # Output: # 1 is odd # 2 is even # 3 is odd # 4 is even # 5 is odd # 6 is even # 7 is odd # 8 is even # 9 is odd

Comments

Popular posts from this blog

Python Calculator Program with GUI Intercface

   Python Calculator Program with GUI Intercface Here is a Python program using the tkinter library to create a simple GUI-based calculator. This calculator can perform basic arithmetic operations like addition, subtraction, multiplication, and division.   import tkinter as tk # Function to update the input field when a button is clicked def button_click(item):     global expression     expression = expression + str(item)     input_text.set(expression) # Function to clear the input field def button_clear():     global expression     expression = ""     input_text.set("") # Function to evaluate the expression and display the result def button_equal():     global expression     try:         result = str(eval(expression))  # Evaluate the expression         input_text.set(result) ...

Python GUI Program to Calculate Age

Python GUI Program to Calculate Age     Certainly! Below is a Python program using the tkinter library to create a simple GUI that accepts a date of birth and calculates the age.   import tkinter as tk from tkinter import messagebox from datetime import datetime def calculate_age():     dob_str = entry_dob.get()     try:         dob = datetime.strptime(dob_str, "%Y-%m-%d")         today = datetime.today()         age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))         messagebox.showinfo("Age Calculator", f"Your age is: {age} years")     except ValueError:         messagebox.showerror("Error", "Please enter the date in YYYY-MM-DD format") # Create the main window root = tk.Tk() root.title("Age Calculator") # Create a labe...

Python Basic Programs to Practice

  Python Programming Introduction Python is a high-level, interpreted programming language known for its simplicity, readability, and ease of learning. It's versatile, suitable for various applications, including web development, data science, automation, artificial intelligence, and more. Python's popularity stems from its vast standard library, extensive community support, and compatibility with other programming languages. Key Features of Python Simple and Easy to Learn : Python's syntax is straightforward, making it a great choice for beginners. Interpreted Language : Code is executed line-by-line, making debugging easier. Object-Oriented : Supports classes and objects, promoting organized, reusable code. Extensive Libraries : Python has a large standard library for handling various tasks and third-party libraries for specialized needs. Cross-Platform : Python can run on various operating systems, including Windows, macOS, and Linux. Python Basic Syntax Variables :...