Python Program

Few Examples of Python that use conditional statements

Few Examples of Python that use conditional statements

Here are a few examples of Python programs that use conditional statements to demonstrate different concepts:

Example 1: Check if a number is positive, negative, or zero.

# Program to check if a number is positive, negative, or zero

 

num = float(input(“Enter a number: “))

 

if num > 0:

    print(“The number is positive.”)

elif num == 0:

    print(“The number is zero.”)

else:

    print(“The number is negative.”)

 

Example 2: Check if a number is even or odd

# Program to check if a number is even or odd

num = int(input(“Enter an integer: “))

if num % 2 == 0:

    print(f”{num} is even.”)

else:

    print(f”{num} is odd.”)

 

Example 3: Find the largest of three numbers

# Program to find the largest of three numbers

 

num1 = float(input(“Enter first number: “))

num2 = float(input(“Enter second number: “))

num3 = float(input(“Enter third number: “))

 

if (num1 >= num2) and (num1 >= num3):

    largest = num1

elif (num2 >= num1) and (num2 >= num3):

    largest = num2

else:

    largest = num3

 

print(f”The largest number is {largest}.”)

 

Example 4: Check if a year is a leap year

# Program to check if a year is a leap year

 

year = int(input(“Enter a year: “))

 

if (year % 4 == 0):

if (year % 100 != 0 or year % 400 == 0):

print(f”{year} is a leap year.”)

else:

print(f”{year} is not a leap year.”)

else:

print(f”{year} is not a leap year.”)

 

Example 5: Simple calculator using conditional statements

# Simple calculator using conditional statements

 

num1 = float(input(“Enter first number: “))

num2 = float(input(“Enter second number: “))

 

print(“Select operation:”)

print(“1. Add”)

print(“2. Subtract”)

print(“3. Multiply”)

print(“4. Divide”)

 

choice = input(“Enter choice (1/2/3/4): “)

 

if choice == ‘1’:

print(f”The result is {num1 + num2}”)

elif choice == ‘2’:

print(f”The result is {num1 – num2}”)

elif choice == ‘3’:

print(f”The result is {num1 * num2}”)

elif choice == ‘4’:

if num2 != 0:

print(f”The result is {num1 / num2}”)

else:

print(“Error! Division by zero.”)

else:

print(“Invalid input”)

 

These examples cover a range of basic conditional operations and should give you a good starting point for understanding how to use conditional statements in Python.

 

Social Media Links of Tech DCode

👉🏻 YouTube

https://www.youtube.com/channel/UCjJnEdeugftBwQ3yMuD4B_A

👉🏻Instagram

https://www.instagram.com/thetechdcode/

👉🏻Facebook Page

https://www.facebook.com/thetechdcode

👉🏻 Twitter 

👉🏻Telegram Channel

https://t.me/thetechdcode

👉🏻Tech DCode Linktree

https://linktr.ee/thetechdcode

👉🏻My Personal Handles

https://linktr.ee/virtualshivamin

Leave a Reply

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