Introduction to Python
Programming Cycle of Python
Varibles and Datatypes in Python
Input and Output in Python
Operators in Python
Precedence of Operators in Python
Typecasting in Python
If Else in Python
Loops in Python
Break, Continue and Pass in Python
Functions in Python
Default Arguments and Keyword Arguments in Python
Strings in python
Lists in Python
Tuple in Python
Dictionary in Python
Sets in Python
List Comprehension in Python
Unpacking Sequences in Python
Higher Order Functions in Python
Lambda Functions in Python
Sieve of Eratosthenes Algorithm in Python
Linear Search in Python
Binary Search in Python
Selection Sort in Python
Bubble Sort in Python
Insertion Sort in Python
Merge Sort in Python
If Else in Python
In every language we need some keywords for decision-making. In Python, we have mainly three keywords for decision-making. These are:
- if
- elif
- else
If in Python
In Python when we need to execute a block of code based on some condition then we use 'if' keyword. Code defined inside 'if' block will execute only if the condition given in parenthesis of 'if' is true.
Syntax:
if(condition_1): this block will execute only if condition_1 is trueExample:
age = 20
if age>18:
# in python spaces are very important
# Python uses these spaces to identify blocks of codes
# way of giving spaces at beginning of lines is called indentation
print("You can Vote")
Output:
You can Vote
Elif in Python
It is used when we have multiple conditions and we need to run different codes on different conditions. It is same as 'else if' of C++ or Java.
Syntax:
if (condition_1): this block will execute only if condition_1 is true elif (condition_2): this block will execute only if condition_2 is true elif (condition_3): this block will execute only if condition_3 is trueExample:
num1 = 12
num2 = 10
op = "+"
if (op == "+"):
print(num1 + num2)
elif (op == "-"):
print(num1 - num2)
elif (op == "*"):
print(num1 * num2)
Output:
22
Else in Python
It is used to run a piece of code when all conditions specified in 'if' or 'elif' are false.
Syntax:
if (condition_1): this block will execute only if condition_1 is true elif (condition_2): this block will execute only if condition_2 is true elif (condition_3): this block will execute only if condition_3 is true else: this block will execute when condition_1, condition_2 and condition_3 are falseExample:
num1 = 12
num2 = 10
op = "/"
if (op == "+"):
print(num1 + num2)
elif (op == "-"):
print(num1 - num2)
elif (op == "*"):
print(num1 * num2)
else:
print("Your operator is not valid")
Output:
Your operator is not valid