Saturday, 14 January 2023

Python if statement

 

The if-else conditional statement in Python is used to control the flow of execution based on a certain condition. The basic syntax of an if-else statement is as follows:

if condition:
    # code to be executed if the condition is true
else:
    # code to be executed if the condition is false

Here's an example of how to use an if-else statement to check if a number is even or odd:

number = 5
 
if number % 2 == 0:
    print(f'{number} is even.')
else:
    print(f'{number} is odd.')

This will output: 5 is odd.

You can also use the elif keyword (short for "else if") to chain multiple conditions together:

number = 5
if number > 0:
    print(f"{number} is positive.")
elif number < 0:
    print(f"{number} is negative.")
else:
    print(f"{number} is zero.")

This will output: 5 is positive.

You can also use the and, or and not logical operators to combine multiple conditions in a single if statement:

x = 5
y = 10
 
if x > 0 and y > 0:
    print("Both x and y are positive.")
 
if x > 0 or y > 0:
    print("At least one of x and y is positive.")
 
if not (x > 0 and y > 0):
    print("Either x or y or both are not positive.")

You can also use the in keyword to check if an element is present in a sequence:

fruits = ['apple', 'banana', 'orange']
 
if 'apple' in fruits:
    print("There is an apple in the list.")
else:
    print("There is no apple in the list.")

This will output: There is an apple in the list.

You can also use the is keyword to check if two variables refer to the same object:

x = [1, 2, 3]
y = [1, 2, 3]
z = x
 
if x is y:
    print("x and y refer to the same object.")
else:
    print("x and y do not refer to the same object.")
 
if x is z:
    print("x and z refer to the same object.")
else:
    print("x and z do not refer to the same object.")

This will output:

x and y do not refer to the same object.
x and z refer to the same object.

Python's if-else conditional statement is a very powerful feature that allows you to control the flow of execution based on certain conditions. By using the various logical operators and keywords, you can create complex conditions to suit your needs.

It's also important to keep in mind that the if-else statement can be used inside other control flow structures such as for and while loops to create more complex and powerful programs.

 


Amelioration

This article was researched and written with the help of ChatGPT, a language model developed by OpenAI.

Special thanks to ChatGPT for providing valuable information and examples used in this article.

 

No comments:

Post a Comment