Check if number is positive
num = 5
if num > 0:
print("Positive number")
Check if number is zero
num = 0
if num == 0:
print("Zero")
Check if number is negative
num = -3
if num < 0:
print("Negative number")
Check if number is even
num = 10
if num % 2 == 0:
print("Even number")
Check if number is odd
num = 7
if num % 2 != 0:
print("Odd number")
Grade checker using if-elif-else
marks = 85
if marks >= 90:
print("Grade A")
elif marks >= 80:
print("Grade B")
else:
print("Grade C")
Check largest of two numbers
a, b = 10, 20
if a > b:
print("a is greater")
else:
print("b is greater")
Check if character is vowel
char = 'e'
if char in 'aeiou':
print("Vowel")
else:
print("Consonant")
Print numbers 1 to 5 using while
i = 1
while i <= 5:
print(i)
i += 1
Sum of first 10 natural numbers
i, total = 1, 0
while i <= 10:
total += i
i += 1
print("Sum:", total)
Factorial using while
n = 5
fact = 1
while n > 0:
fact *= n
n -= 1
print("Factorial:", fact)
Even numbers between 1 and 10
i = 2
while i <= 10:
print(i)
i += 2
Print each character in string
for char in "Python":
print(char)
Print squares of 1 to 5
for i in range(1, 6):
print(i**2)
Sum of a list
numbers = [1, 2, 3, 4]
total = 0
for num in numbers:
total += num
print("Sum:", total)
Multiplication table of 5
for i in range(1, 11):
print("5 x", i, "=", 5*i)
Count vowels in a string
string = "education"
count = 0
for char in string:
if char in "aeiou":
count += 1
print("Vowel count:", count)
Skip even numbers using continue
for i in range(1, 10):
if i % 2 == 0:
continue
print(i)
Stop loop at number 5 using break
for i in range(1, 10):
if i == 5:
break
print(i)
Print odd numbers till 10
for i in range(1, 11):
if i % 2 == 0:
continue
print(i)
Print numbers until divisible by 7
i = 1
while True:
if i % 7 == 0:
break
print(i)
i += 1
Handle invalid int conversion
try:
num = int("abc")
except ValueError:
print("Invalid number")
Catch ZeroDivisionError
try:
a = 5 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Multiple exceptions
try:
x = int("abc")
y = 10 / 0
except ValueError:
print("ValueError occurred")
except ZeroDivisionError:
print("ZeroDivisionError occurred")
Try-Except-Else
try:
x = int(input("Enter number: "))
except ValueError:
print("Invalid input")
else:
print("You entered:", x)
Try-Except-Finally
try:
x = int(input("Enter number: "))
except ValueError:
print("Invalid input")
finally:
print("This block always runs")
Nested try-except
try:
try:
a = int("xyz")
except ValueError:
print("Inner block")
b = 5 / 0
except ZeroDivisionError:
print("Outer block")
Try with list index error
try:
a = [1, 2]
print(a[5])
except IndexError:
print("Index out of range")
File not found handling
try:
f = open("[Link]")
except FileNotFoundError:
print("File not found")
KeyError handling
try:
d = {"a": 1}
print(d["b"])
except KeyError:
print("Key not found")