Python Tutorial
Learn Python programming from scratch to advanced concepts. This comprehensive tutorial covers everything from basic syntax to web development, data science, and automation.
Why Learn Python?
Python is one of the most popular and versatile programming languages in the world. Created by Guido van Rossum and first released in 1991, Python emphasizes code readability with its notable use of significant whitespace.
Python’s simple, easy-to-learn syntax emphasizes readability and reduces the cost of program maintenance. Python supports multiple programming paradigms, including structured, object-oriented, and functional programming.
With its extensive standard library and vibrant ecosystem of third-party packages, Python is used for web development, data analysis, artificial intelligence, scientific computing, automation, and more.
The Zen of Python (PEP 20) summarizes the language philosophy: “Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated…”
Easy to Learn
Clean syntax and readability make Python perfect for beginners.
Extensive Libraries
Rich standard library and 300,000+ packages on PyPI.
Cross-platform
Runs on Windows, Linux, macOS, and many other platforms.
Large Community
Vast community support with extensive documentation and resources.
High Demand
One of the most in-demand skills in tech and data science.
Get Started with Python
Follow these simple steps to install Python and write your first program.
# Download from https://www.python.org/downloads/
python –version
# Should display: Python 3.x.x
print(“Hello, World!”)
print(“Welcome to Python programming!”)
python hello.py
# Output:
Hello, World!
Welcome to Python programming!
Python Basics
Variables, operators, and basic syntax
Variables in Python
In Python, variables are created when you assign a value to them. Python is dynamically typed, meaning you don’t need to declare the variable type explicitly.
Basic Operators
Python supports various operators for arithmetic, comparison, logical operations, and more.
- Arithmetic Operators: +, -, *, /, // (floor division), % (modulus), ** (exponentiation)
- Comparison Operators: ==, !=, >, <, >=, <=
- Logical Operators: and, or, not
- Assignment Operators: =, +=, -=, *=, /=, etc.
Use snake_case for variables and functions (e.g., my_variable). Use PascalCase for classes (e.g., MyClass). Use UPPER_CASE for constants (e.g., MAX_VALUE).
name = “Alice” # String
age = 25 # Integer
height = 5.8 # Float
is_student = True # Boolean
# Arithmetic operations
x = 10
y = 3
sum = x + y # 13
difference = x – y # 7
product = x * y # 30
quotient = x / y # 3.333…
floor_div = x // y # 3
remainder = x % y # 1
power = x ** y # 1000
# String operations
greeting = “Hello” + ” “ + “World”
repeated = “Python “ * 3 # “Python Python Python “
>> sum = 13
> quotient = 3.3333333333333335
> greeting = “Hello World”
Data Types in Python
Understanding Python’s built-in data types
Python Built-in Data Types
Python has several built-in data types that are used to store different kinds of data. The type() function can be used to check the data type of any variable.
Numeric Types
- int: Integer numbers (e.g., 5, -10, 1000)
- float: Floating-point numbers (e.g., 3.14, -0.001, 2.0)
- complex: Complex numbers (e.g., 3+4j)
Sequence Types
- str: Strings of characters (e.g., “hello”, ‘Python’)
- list: Ordered, mutable collection (e.g., [1, 2, 3])
- tuple: Ordered, immutable collection (e.g., (1, 2, 3))
- range: Sequence of numbers (e.g., range(5))
Mapping Type
- dict: Key-value pairs (e.g., {“name”: “Alice”, “age”: 25})
Set Types
- set: Unordered collection of unique items
- frozenset: Immutable version of set
Boolean Type
- bool: True or False values
print(type(42)) #
print(type(3.14)) #
print(type(“Python”)) #
print(type(True)) #
# List examples
fruits = [“apple”, “banana”, “cherry”]
numbers = [1, 2, 3, 4, 5]
mixed = [“text”, 42, 3.14, True]
# Dictionary examples
person = {
“name”: “Alice”,
“age”: 25,
“city”: “New York”
}
# Set examples
unique_numbers = {1, 2, 3, 3, 4} # {1, 2, 3, 4}
vowels = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’}
>>
>>
>>
>>
Control Flow
Conditional statements and loops
Conditional Statements
Python uses if, elif, and else statements for decision making. The code block under each condition is defined by indentation (typically 4 spaces).
Loops in Python
Python provides two types of loops: for loops and while loops.
- for loop: Iterates over a sequence (list, tuple, string, etc.)
- while loop: Repeats as long as a condition is true
Loop Control Statements
- break: Exits the loop immediately
- continue: Skips the rest of the current iteration
- pass: Does nothing (placeholder)
score = 85
if score >= 90:
grade = “A”
elif score >= 80:
grade = “B”
elif score >= 70:
grade = “C”
else:
grade = “F”
print(f”Score: {score}, Grade: {grade}”)
# For loop example
fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)
# While loop example
count = 1
while count <= 5:
print(f”Count: {count}”)
count += 1
>> Score: 85, Grade: B
>> apple
>> banana
>> cherry
>> Count: 1
>> Count: 2
>> Count: 3
>> Count: 4
>> Count: 5
Functions
Reusable blocks of code
Defining Functions
Functions are defined using the def keyword followed by the function name and parentheses. Parameters can be placed inside the parentheses.
Function Arguments
Python supports different types of function arguments:
- Positional arguments: Arguments passed in correct positional order
- Keyword arguments: Arguments passed with parameter names
- Default arguments: Parameters with default values
- Variable-length arguments: *args and **kwargs
Return Statement
The return statement is used to exit a function and return a value. A function can return multiple values as a tuple.
Lambda Functions
Anonymous functions created with the lambda keyword. They can have any number of arguments but only one expression.
def greet(name):
return f”Hello, {name}!”
print(greet(“Alice”)) # Hello, Alice!
# Function with default argument
def power(base, exponent=2):
return base ** exponent
print(power(3)) # 9 (3^2)
print(power(3, 3)) # 27 (3^3)
# Function returning multiple values
def min_max(numbers):
return min(numbers), max(numbers)
nums = [5, 2, 8, 1, 9]
minimum, maximum = min_max(nums)
print(f”Min: {minimum}, Max: {maximum}”)
# Lambda function
square = lambda x: x * x
print(square(5)) # 25
>> Hello, Alice!
>> 9
>> 27
>> Min: 1, Max: 9
>> 25
Python Applications
Python’s versatility makes it suitable for a wide range of applications across different domains.
Python Learning Path
Beginner Level
Master Python fundamentals and basic programming concepts.
Intermediate Level
Learn advanced Python concepts and start building projects.
Advanced Level
Specialize in specific domains and work on complex projects.
Learning Resources
Pro Tip: The best way to learn Python is by building projects. Start with simple scripts, then move to web applications, data analysis projects, or automation tools. Consistent practice is key to mastering Python.
