Decision control statements: To know in detail click here
1. If Statement:
Syntax:
if expression:
#execute your code
Example:1
x = 30
if(x > 20):
print(" x is largest")
2. If else Statement:
Syntax:
if expression:
#execute your code
else:
#execute your code
Example:2
m = 30
n = 20
if(m > n):
print(" m is largest")
else:
print(" n is largest")
3. Nested if:
if statement inside if statement is called as nested if statement.
Syntax:
if expression:
#execute your code
if expression:
#execute your code
else:
#execute your code
Example:3
a = int(input("Enter your number"))
if a > 10:
print("Above ten,")
if a > 20:
print("and also above 20!")
else:
print("but not above 20.")
if a > 10:
print("Above ten,")
if a > 20:
print("and also above 20!")
else:
print("but not above 20.")
4. elif Statement:
elif - is a keyword used in Python replacement of else if to place another condition in the program. This is called a chained conditional.
Syntax:
if expression:
#execute your code
elif expression:
#execute your code
else:
#execute your code
Example:4
x = int(input("Enter your number:"))
y = int(input("Enter your number:"))
if x > y:
print("x is greater")
elif x == y:
print("both x and y are equal")
else:
print("y is greater")
if x > y:
print("x is greater")
elif x == y:
print("both x and y are equal")
else:
print("y is greater")
BASIC LOOP in Python:
Python has two primitive loop commands:
- while loops
- for loops
1. while loop:
Execute the statement as long as the condition is true.
Syntax:
initialization of counter
while condition:
statement or logic
increment/ decrement counter
Example:5
i = 1
while i < 6:
print(i)
i += 1
while i < 6:
print(i)
i += 1
The break Statement:
Example:6
i = 1
while i < 6:
print(i)
if i == 4:
break
i += 1
while i < 6:
print(i)
if i == 4:
break
i += 1
The continue Statement:
Continue to the next iteration if the condition is true
Example:7
n = 0
while n < 6:
n = n + 1
if n == 3:
continue
print(n)
while n < 6:
n = n + 1
if n == 3:
continue
print(n)
The else Statement
When the condition is no longer true at that time we can run the else statement
Example:8
i = 1
while i < 8:
print(i)
i += 1
else:
print("i is no longer less than 8")
while i < 8:
print(i)
i += 1
else:
print("i is no longer less than 8")
What is pass statement in Python?
To avoid the indentation error in Python we simply used pass in Python. now you doubt in mind why we get an indentation error, so let's check this code.
Example:1
output:
IndentationError: expected an indented block after 'if' statement
This is happen when the user does not know what code to write, So the user simply places a pass at that line.
Sometimes, the pass is used when the user doesn’t want any code to execute.
So users can simply place a pass where empty code is not allowed,
like in loops, function definitions, class definitions, or in if statements. So using a pass statement user avoids this error.
Use of pass keyword in Function
Example:2
No comments:
Post a Comment