A comprehensive guide to Python syntax and common operations.
# Print to console
print("Hello, World!")
# Variables
x = 10
y = 20.5
name = "Python"
# Data Types
integer = 42
floating_point = 3.14
string = "Hello"
boolean = True
none_type = None
# List creation and operations
my_list = [1, 2, 3, 4, 5]
my_list.append(6) # Add an item
my_list.pop() # Remove last item
my_list[1:3] # Slicing
# Dictionary creation
my_dict = {"name": "Alice", "age": 25}
my_dict["city"] = "New York" # Add key-value pair
value = my_dict.get("name") # Get value
# If-else
if x > 0:
print("Positive")
else:
print("Non-positive")
# For loop
for i in range(5):
print(i)
# While loop
count = 0
while count < 5:
print(count)
count += 1
# Define a function
def greet(name):
return f"Hello, {name}!"
# Call a function
message = greet("Python")
print(message)
# Define a class
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return "Woof!"
# Create an object
my_dog = Dog("Buddy", 3)
print(my_dog.bark())
# Write to a file
with open("example.txt", "w") as file:
file.write("Hello, File!")
# Read from a file
with open("example.txt", "r") as file:
content = file.read()
print(content)
# Try-except block
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Execution completed.")
import math
print(math.sqrt(16)) # Square root
import random
print(random.randint(1, 10)) # Random number between 1 and 10
import datetime
print(datetime.datetime.now()) # Current date and time