Master Python programming with our comprehensive tutorial. Learn through examples and hands-on practice with Python's elegant syntax.
Python is a high-level, interpreted programming language known for its simplicity and readability.
# Simple Hello World program
print("Hello World!")A simple Hello World program in Python
Learn fundamental Python concepts including variables, data types, and basic operations.
# Data types and variables
number = 42
pi = 3.14159
grade = 'A'
is_valid = True
name = "John"
# Print all variables
print(f"Number: {number}")
print(f"Pi: {pi}")
print(f"Grade: {grade}")
print(f"Is Valid: {is_valid}")
print(f"Name: {name}")
# Dynamic typing
x = 100
print(f"\nX as integer: {x}")
x = "Python"
print(f"X as string: {x}")Common data types and variable declarations in Python
# Lists in Python
numbers = [1, 2, 3, 4, 5]
print(f"Original list: {numbers}")
# List operations
numbers.append(6)
print(f"After append(6): {numbers}")
numbers.extend([7, 8])
print(f"After extend([7, 8]): {numbers}")
first_item = numbers[0]
last_item = numbers[-1]
print(f"First item: {first_item}")
print(f"Last item: {last_item}")Lists and basic list operations
Functions in Python are defined using the def keyword and are essential for code organization.
def greet(name, greeting="Hello"):
"""
A simple greeting function
with optional parameter
"""
return f"{greeting}, {name}!"
# Function calls
print(greet("Alice")) # Hello, Alice!
print(greet("Bob", "Hi")) # Hi, Bob!
# Lambda function
square = lambda x: x * x
print(square(5)) # 25Functions and lambda expressions in Python
Learn how to control program flow using conditional statements and loops in Python.
# If-elif-else statement
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
else:
grade = 'C'
print(f"Score: {score}, Grade: {grade}")
# For loop with range
print("\nFor loop output:")
for i in range(5):
print(i)
# While loop
print("\nWhile loop output:")
count = 0
while count < 3:
print(f"Count: {count}")
count += 1
# List comprehension
squares = [x**2 for x in range(5)]
print(f"\nSquares: {squares}")Examples of control flow statements and loops in Python