Friday 14 April 2023

If Else in Python

 In Python, the if-else statement is used for conditional branching. It allows you to execute a block of code if a certain condition is true, and another block of code if the condition is false. The basic syntax of an if-else statement in Python is as follows:

python
if condition: # code to execute if condition is true else: # code to execute if condition is false

Here's an example that demonstrates how to use if-else statement in Python:

python
# a simple program that prints whether a number is positive, negative, or zero num = int(input("Enter a number: ")) if num > 0: print("The number is positive") elif num < 0: print("The number is negative") else: print("The number is zero")

In this example, we first prompt the user to enter a number using the input() function and convert it to an integer using the int() function. Then, we use the if-elif-else statement to check whether the number is positive, negative, or zero. If the number is greater than 0, the code inside the first if block is executed, which prints "The number is positive". If the number is less than 0, the code inside the elif block is executed, which prints "The number is negative". If the number is 0, the code inside the else block is executed, which prints "The number is zero".

Note that the elif keyword is used to add additional conditions to check. You can have as many elif blocks as you need to check different conditions. Also note that the if-else statement can be nested inside other if statements to create more complex conditions.

No comments:

Post a Comment

Program For String

 # This program demonstrates various string operations # Define a string variable my_string = "Hello, World!" # Print the string p...