Python Full Tutorial
1. Introduction and Setup
A. Why Python?
Readability: Syntax is very clean and close to English.
Versatility: Used for web development (Django, Flask), data science (Pandas, NumPy),
machine learning, scripting, and automation.
Large Community: Abundant libraries and excellent documentation.
B. Installation and Running Code
1. Install Python: Download the latest version from [[Link]].
2. Use an IDE/Editor: Visual Studio Code (VS Code) is highly recommended.
3. Run Python: You can run Python in a few ways:
o Interactive Shell (REPL): Type python or python3 in your terminal.
o Script: Write code in a file (e.g., [Link]) and run it using python [Link].
C. Your First Program
Python
# This is a comment in Python
print("Hello, Python World!")
2. Variables and Data Types
Python is dynamically typed, meaning you do not need to declare the variable type. The type is
inferred at runtime.
A. Variables
Python
name = "Alice" # String
age = 30 # Integer (int)
height = 5.9 # Floating-point number (float)
is_student = True # Boolean (True/False, capitalized)
# Check the type
print(type(age)) # Output: <class 'int'>
B. Basic Data Types
Type Description Example
str Textual data, enclosed in quotes. "Python", 'Coding'
int Whole numbers. 10, -500
float Numbers with a decimal point. 3.14, 0.001
bool Logical values: True or False. True
NoneType Represents the absence of a value. None
3. Operators and Control Flow
A. Operators
Arithmetic: +, -, *, /, % (modulo), ** (exponentiation), // (floor division)
Comparison: == (equal), != (not equal), >, <, >=, <=
Logical: and, or, not
B. Conditional Statements (if/elif/else)
Python uses indentation (usually 4 spaces) to define code blocks (no curly braces {}).
Python
score = 85
if score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B") # This code block runs
else:
print("Grade C or lower")
C. Loops
1. for Loop: Used for iterating over a sequence (list, tuple, string, range).
Python
# Looping through a range of numbers
for i in range(5): # range(5) generates numbers 0, 1, 2, 3, 4
print(i)
# Looping through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
2. while Loop: Repeats as long as a condition is true.
Python
count = 0
while count < 3:
print(f"Count is {count}")
count += 1
4. Functions
Functions are blocks of reusable code that perform a specific task. They are defined using the
def keyword.
Python
def greet(name):
"""
This is a docstring (documentation).
It prints a personalized greeting.
"""
return f"Hello, {name}!" # f-string for easy formatting
# Call the function
message = greet("Bob")
print(message) # Output: Hello, Bob!
Arguments:
Positional: Arguments are matched by their position.
Keyword: Arguments are matched by their name.
Default: You can set a default value for an argument.
Python
def describe_pet(animal="dog", name="Rex"):
print(f"I have a {animal} named {name}.")
describe_pet("cat", "Luna") # Positional
describe_pet(name="Max", animal="parrot") # Keyword
describe_pet() # Uses default values
5. Data Structures (Collections)
Python offers powerful built-in collection types.
A. List
Ordered, Changeable (mutable), allows duplicate members.
Defined by square brackets [ ].
Python
my_list = [10, "hello", 3.14, True]
print(my_list[0]) # Access by index: 10
my_list.append(20) # Add item
my_list.pop(1) # Remove item at index 1
print(my_list) # Output: [10, 3.14, True, 20]
B. Tuple
Ordered, Unchangeable (immutable), allows duplicate members.
Defined by parentheses ( ). Useful for data that should not change.
Python
my_tuple = (1, 2, "three")
# my_tuple.append(4) # Error: Tuples cannot be modified
x, y, z = my_tuple # Tuple unpacking
print(x) # Output: 1
C. Dictionary
Unordered (as of Python 3.7+ it is insertion-ordered), Changeable, stores data in key-
value pairs.
Defined by curly braces { }.
Python
person = {
"name": "Charlie",
"age": 45,
"city": "London"
}
# Access and modify
print(person["name"]) # Output: Charlie
person["age"] = 46 # Update value
person["job"] = "Engineer" # Add new key-value pair
print([Link]()) # View all keys
D. Set
Unordered, Unindexed, No duplicate members.
Defined by curly braces { } (or set() for an empty set).
Python
numbers = {1, 2, 3, 3, 4, 1}
print(numbers) # Output: {1, 2, 3, 4} (duplicates removed)
set_a = {1, 2, 3}
set_b = {3, 4, 5}
print(set_a.union(set_b)) # Set operations: {1, 2, 3, 4, 5}
6. Error Handling (try...except)
To prevent your program from crashing when an error (exception) occurs, use try and except.
Python
try:
result = 10 / 0 # This will cause a ZeroDivisionError
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except TypeError:
print("Error: Type mismatch occurred.")
except Exception as e:
# Catch any other error
print(f"An unexpected error occurred: {e}")
else:
# Optional: runs if the try block succeeds
print("Division successful.")
finally:
# Optional: runs no matter what
print("Execution complete.")
7. Working with External Libraries (Modules)
Python's strength comes from its vast collection of modules. You use the import keyword to
access them.
1. Standard Library: Modules built into Python (e.g., math, random).
2. External Libraries: Installed using the pip package manager (e.g., requests, pandas).
Python
# Example 1: Standard Library (Math)
import math
print([Link](16)) # Output: 4.0
# Example 2: External (You must install 'requests' first: pip install
requests)
# import requests
# response = [Link]('[Link]
# print(response.status_code)