Python Code Examples
Python Code Examples
print("Hello, World!")
Explanation: This is the most basic Python program that prints text to the screen.
a = 5
b = 3
sum = a + b
print("Sum:", sum)
Explanation: This code adds two numbers and prints the result.
num = 4
if num % 2 == 0:
print("Even")
else:
print("Odd")
Explanation: This checks if a number is even or odd using the modulus operator.
n = 5
factorial = 1
factorial *= i
print("Factorial:", factorial)
5. Fibonacci Sequence
a, b = 0, 1
for _ in range(10):
num = 7
is_prime = True
if num % i == 0:
is_prime = False
break
7. List Comprehension
print(squares)
def greet(name):
print(greet("Alice"))
9. Dictionary Operations
print(student["name"])
student["grade"] = "A"
print(student)
Explanation: This demonstrates basic dictionary operations like access and update.
try:
num = int("abc")
except ValueError:
print("Invalid input")