Python is a high-level, interpreted, object-oriented programming language with dynamic typing and interactive capabilities. It's renowned for its simplicity and readability, making it an excellent choice for beginners.
Key Features of Python
- Easy to Learn: Minimal keywords and simple syntax structure.
- Readability: Clean code structure enhances maintainability.
- Standard Libray: Comprehensive libraires for cross-platform compatibility.
- Interactive Mode: Supports direct code execution and debugging.
- Extensibility: Can integrate C/C++ to performance-critical sections.
Core Syntax Elements
Variables and Naming Conventions
user_name = "Alice"
user_age = 30
print(f"User: {user_name}, Age: {user_age}")
Data Types
# Type checking examples
num = 42
text = "Hello"
boolean = True
float_num = 3.14
Control Structures
Conditional Statements
# Age validation example
user_age = int(input("Enter your age: "))
if user_age >= 18:
print("Access granted.")
else:
print("Access denied.")
Loops
# Summing even numbers
total = 0
for i in range(1, 101):
if i % 2 == 0:
total += i
print(f"Sum of even numbers: {total}")
Data Structures
Lists
# List operations
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
print(fruits[1:]) # Output: ['banana', 'cherry', 'date']
Dictionaries
# Dictionary operations
person = {"name": "Bob", "age": 25}
person["occupation"] = "Developer"
print(person.get("age", "Not found")) # Output: 25
String Manipulation
# String formatting
name = "Charlie"
greeting = f"Welcome, {name}!"
print(greeting) # Output: Welcome, Charlie!
Functions and Modules
# Custom function example
def calculate_sum(a, b):
return a + b
result = calculate_sum(5, 7)
print(f"Sum: {result}") # Output: Sum: 12
File Handling
# File reading example
with open("data.txt", "r") as file:
content = file.read()
print(content)
Advanced Concepts
List Comprehensions
# Square numbers
squares = [x**2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
Error Handling
# Exception handling
try:
num = int(input("Enter a number: "))
print(10 / num)
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Cannot divide by zero")