Comprehensive Python Programming Guide
Introduction to Python
Python is a high-level, interpreted programming language known for its simplicity and versatility.
1. Installation
- Download and install Python from: https://www.python.org/downloads/
- Verify installation by running 'python --version' in your command line.
2. Basic Syntax
- Print statements: Use 'print()' to output data to the console.
Example:
print('Hello, World!')
- Comments: Use '#' for single-line comments and ''' for multi-line comments.
Example:
# This is a single-line comment
'''
This is a
multi-line comment
'''
3. Variables
- Variables are created by assigning a value with '='.
Example:
age = 25 # integer
name = 'Alice' # string
height = 5.5 # float
4. Data Types
- Common data types include:
- int: Integer
- float: Floating-point number
- str: String
- bool: Boolean (True/False)
Example:
x = 10 # int
y = 3.14 # float
z = 'Python' # str
a = True # bool
5. Control Structures
- Conditionals: Use 'if', 'elif', and 'else' to execute code based on conditions.
Example:
if age >= 18:
print('You are an adult.')
elif age < 13:
print('You are a child.')
else:
print('You are a teenager.')
- Loops: Use 'for' and 'while' to repeat actions.
Example of 'for' loop:
for i in range(5):
print(i)
Example of 'while' loop:
count = 0
while count < 5:
print(count)
count += 1
6. Functions
- Define functions using 'def'.
Example:
def greet(name):
return f'Hello, {name}!'
print(greet('Alice'))
7. Data Structures
- Lists: Ordered collections of items.
Example:
fruits = ['apple', 'banana', 'cherry']
print(fruits[0]) # Output: apple
- Tuples: Immutable ordered collections.
Example:
coordinates = (10.0, 20.0)
print(coordinates[1]) # Output: 20.0
- Dictionaries: Key-value pairs.
Example:
person = {'name': 'Alice', 'age': 25}
print(person['name']) # Output: Alice
- Sets: Unordered collections of unique items.
Example:
unique_numbers = {1, 2, 3, 3}
print(unique_numbers) # Output: {1, 2, 3}
8. Object-Oriented Programming
- Classes and Objects: Define classes to create objects.
Example:
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return 'Woof!'
my_dog = Dog('Buddy')
print(my_dog.bark())
9. Modules and Libraries
- Importing modules using 'import'.
Example:
import math
print(math.sqrt(16)) # Output: 4.0
10. Exception Handling
- Handle errors gracefully using try and except.
Example:
try:
result = 10 / 0
except ZeroDivisionError as e:
print('Error:', e)
11. File Handling
- Reading from and writing to files.
Example:
with open('example.txt', 'w') as file:
file.write('Hello, World!')
with open('example.txt', 'r') as file:
content = file.read()
print(content)
12. Advanced Topics
- Decorators: Modify function behavior.
Example:
def decorator_function(original_function):
def wrapper_function():
print('Wrapper executed before {}'.format(original_function.__name__))
return original_function()
return wrapper_function
@decorator_function
def display():
return 'Display function executed.'
print(display())
- Generators: Create iterators with 'yield'.
Example:
def generate_numbers():
for i in range(5):
yield i
for number in generate_numbers():
print(number)
- Context Managers: Manage resources with 'with'.
Example:
with open('example.txt', 'w') as file:
file.write('Using context manager.')
13. Conclusion
- Continue exploring Python and work on projects to enhance your skills.