Skip to content

Python

demo.py
print("=== Python Demo: 11 Examples ===\n")
# 1. Hello World
print("1) Hello World:")
print("Hello, world!\n")
# 2. Variables and arithmetic
print("2) Variables & Arithmetic:")
a = 5
b = 3
print(f"a = {a}, b = {b}, sum = {a + b}\n")
# 3. Lists (arrays)
print("3) Lists:")
fruits = ["apple", "banana", "cherry"]
print(f"First fruit: {fruits[0]}")
print(f"All fruits: {', '.join(fruits)}\n")
# 4. Dictionaries (hashes)
print("4) Dictionaries:")
ages = {"Alice": 25, "Bob": 30}
print(f"Alice is {ages['Alice']} years old\n")
# 5. Conditionals
print("5) Conditionals:")
if a > b:
print(f"{a} is greater than {b}\n")
else:
print(f"{b} is greater or equal to {a}\n")
# 6. Loops
print("6) Loops:")
for i in range(1, 4):
print(f"Loop iteration {i}")
print()
# 7. Functions
print("7) Functions:")
def greet(name):
return f"Hello, {name}!"
print(greet("Python User"))
print()
# 8. File handling
print("8) File Handling (write & read):")
filename = "demo.txt"
# Write
with open(filename, "w") as f:
f.write("This is a test file.\n")
# Read
with open(filename, "r") as f:
for line in f:
print(f"Read: {line.strip()}")
print()
# 9. Regular expressions
print("9) Regular Expressions:")
import re
text = "Python is powerful"
if re.search("powerful", text):
print("Match found in text!\n")
# 10. Command-line arguments
print("10) Command-line Arguments:")
import sys
if len(sys.argv) > 1:
print("Arguments passed:", " ".join(sys.argv[1:]), "\n")
else:
print("No arguments provided\n")
# 11. Function using shift-like behavior
print("11) Function with shift-like behavior:")
def add_numbers(*args):
args = list(args) # convert tuple to list
x = args.pop(0) # similar to shift (remove first)
y = args.pop(0) # next argument
return x + y
result = add_numbers(10, 20)
print(f"10 + 20 = {result}")
print("\n=== End of Demo ===")