Python Notes
A versatile and beginner-friendly programming language
Table of Contents
-
Python Basics
-
Control Flow
-
Functions and Modules
Introduction to Python
Python is a high-level, interpreted programming language known for its simplicity and readability. It's often recommended as a first programming language for beginners due to its clean syntax and powerful libraries.
Python Basics
What is Python?
Python is a high-level, interpreted programming language created by Guido van Rossum and first released in 1991. It's known for its readability, simplicity, and versatility, making it an excellent choice for beginners and experienced developers alike.
Key features of Python include:
- Easy to Learn and Read: Python uses clean, readable syntax with natural language elements
- Interpreted: Code is executed line by line, making debugging easier
- Dynamically Typed: No need to declare variable types
- Versatile: Used for web development, data analysis, AI, scientific computing, and more
- Large Standard Library: Comes with libraries for many common programming tasks
- Strong Community: Active development and extensive third-party packages
# Your first Python program
print("Hello, World!")
# Simple calculation
result = 5 + 10
print(f"5 + 10 = {result}")
# Working with strings
name = "Python"
print(f"I'm learning {name} programming!")
Setting Up Python
To start programming with Python, you need to set it up on your computer. Here's how to do it:
Step 1: Download Python
Visit the official Python website and download the latest version for your operating system.
Step 2: Install Python
Run the installer and make sure to check the box that says "Add Python to PATH" during installation. This makes it easier to run Python from the command line.
Step 3: Verify Installation
Open a terminal or command prompt and type the following commands to verify your installation:
# Check Python version
python --version
# Enter Python interactive mode
python
# In interactive mode, try a simple command
>>> print("Python is installed correctly!")
>>> exit() # To exit interactive mode
Basic Syntax
Python has a clean, readable syntax that uses indentation (whitespace) to define code blocks instead of braces or keywords.
Indentation
Indentation (usually 4 spaces) is used to define code blocks in Python. Proper indentation is critical for the code to work correctly.
Comments
Comments in Python start with the # character and extend to the end of the line.
Variables
Variables in Python don't need explicit declaration or type definition. They're created when you first assign a value to them.
Print Statement
The print()
function outputs values to the console.
Input
The input()
function reads user input from the console.
# This is a comment
# Variables don't need type declarations
name = "John" # String
age = 30 # Integer
height = 1.75 # Float
is_student = True # Boolean
# Indentation defines code blocks
if age >= 18:
print("You are an adult.") # Indented with 4 spaces
if height > 1.7:
print("You are tall.") # Indented with 8 spaces
else:
print("You are a minor.") # Same indentation level as the if block
# Multiple line statements can be written using \ or parentheses
total = 1 + 2 + 3 + \
4 + 5
sum_of_numbers = (1 + 2 + 3 +
4 + 5)
# Getting user input
user_name = input("Enter your name: ")
print(f"Hello, {user_name}!")
You are an adult. You are tall. Hello, John!
Variables and Data Types
Python has several built-in data types for storing different kinds of values. Variables can hold any type of data, and their type can change during program execution.
Basic Data Types
- Numeric Types:
int
: Integer numbers (e.g., 5, -17, 1000)float
: Floating-point numbers (e.g., 3.14, -0.001, 2.0)complex
: Complex numbers (e.g., 3+4j)
- Boolean Type:
bool
: EitherTrue
orFalse
- Sequence Types:
str
: String of characters (e.g., "Hello", 'Python')list
: Ordered, mutable collection (e.g., [1, 2, 3])tuple
: Ordered, immutable collection (e.g., (1, 2, 3))
- Mapping Type:
dict
: Key-value pairs (e.g., {'name': 'John', 'age': 30})
- Set Types:
set
: Unordered collection of unique items (e.g., {1, 2, 3})frozenset
: Immutable version of set
- None Type:
None
: Represents absence of value
Type Conversion
You can convert between types using functions like int()
, float()
, str()
, etc.
Checking Types
Use the type()
function to check the type of a variable.
# Numeric types
int_num = 42
float_num = 3.14
complex_num = 2 + 3j
# Boolean type
is_python_fun = True
# String type
name = "Python"
single_quotes = 'Also works'
multi_line = """This is a
multi-line string"""
# List type (mutable)
fruits = ["apple", "banana", "cherry"]
fruits[0] = "orange" # Lists can be modified
# Tuple type (immutable)
coordinates = (10.0, 20.0)
# coordinates[0] = 15.0 # This would cause an error
# Dictionary type
person = {
"name": "Alice",
"age": 25,
"is_student": True
}
# Set type
unique_numbers = {1, 2, 3, 2, 1} # Duplicates are automatically removed
# None type
result = None
# Checking types
print(f"Type of int_num: {type(int_num)}")
print(f"Type of name: {type(name)}")
print(f"Type of fruits: {type(fruits)}")
# Type conversion
string_num = "42"
converted_num = int(string_num)
print(f"converted_num: {converted_num}, type: {type(converted_num)}")
float_to_int = int(3.99) # Truncates decimal part
print(f"float_to_int: {float_to_int}")
Type of int_num: <class 'int'> Type of name: <class 'str'> Type of fruits: <class 'list'> converted_num: 42, type: <class 'int'> float_to_int: 3
Control Flow
Conditional Statements
Conditional statements allow your program to make decisions based on specified conditions. Python provides several ways to implement conditional logic:
if Statement
The if
statement executes a block of code if a specified condition is true.
if-else Statement
The if-else
statement executes one block of code if a condition is true and another block if the condition is false.
if-elif-else Statement
The if-elif-else
chain allows you to check multiple conditions in sequence.
Ternary Operator
Python's ternary operator provides a shorthand way to write simple if-else statements in a single line.
Logical Operators
Python uses the following logical operators:
and
: True if both operands are trueor
: True if at least one operand is truenot
: True if the operand is false
# if statement
age = 20
if age >= 18:
print("You are an adult.")
# if-else statement
temperature = 15
if temperature > 25:
print("It's a warm day.")
else:
print("It's not very warm today.")
# if-elif-else statement
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Grade: {grade}")
# Nested if statements
num = 15
if num > 0:
if num % 2 == 0:
print(f"{num} is a positive even number.")
else:
print(f"{num} is a positive odd number.")
else:
print(f"{num} is not a positive number.")
# Ternary operator
age = 20
status = "adult" if age >= 18 else "minor"
print(f"Status: {status}")
# Logical operators
has_passport = True
has_ticket = True
can_travel = has_passport and has_ticket
print(f"Can travel: {can_travel}")
# Checking membership with 'in'
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Yes, banana is in the fruits list.")
You are an adult. It's not very warm today. Grade: B 15 is a positive odd number. Status: adult Can travel: True Yes, banana is in the fruits list.
Loops
Loops allow you to execute a block of code repeatedly. Python provides several ways to create loops:
for Loop
The for
loop iterates over a sequence (list, tuple, string, etc.) or other iterable objects.
while Loop
The while
loop repeats a block of code as long as a specified condition is true.
Loop Control Statements
break
: Exits the loop prematurelycontinue
: Skips the current iteration and moves to the next onepass
: Does nothing; used as a placeholder
Else Clause in Loops
Python allows an else
clause with loops, which executes after the loop completes normally (not when terminated by a break
statement).
Comprehensions
Python provides concise ways to create lists, dictionaries, and sets using comprehensions.
# for loop with a list
print("For loop with a list:")
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"Fruit: {fruit}")
# for loop with range
print("\nFor loop with range:")
for i in range(5): # 0 to 4
print(f"Number: {i}")
# for loop with range start, stop, step
print("\nFor loop with range parameters:")
for i in range(2, 10, 2): # 2, 4, 6, 8
print(f"Even number: {i}")
# while loop
print("\nWhile loop:")
count = 0
while count < 5:
print(f"Count: {count}")
count += 1
# break statement
print("\nUsing break:")
for i in range(10):
if i == 5:
break
print(f"Number before break: {i}")
# continue statement
print("\nUsing continue:")
for i in range(10):
if i % 2 == 0: # Skip even numbers
continue
print(f"Odd number: {i}")
# else clause with for loop
print("\nFor loop with else:")
for i in range(3):
print(f"Number: {i}")
else:
print("For loop completed successfully!")
# List comprehension
print("\nList comprehension:")
squares = [x**2 for x in range(1, 6)]
print(f"Squares: {squares}")
# Dictionary comprehension
print("\nDictionary comprehension:")
square_dict = {x: x**2 for x in range(1, 6)}
print(f"Square dictionary: {square_dict}")
For loop with a list: Fruit: apple Fruit: banana Fruit: cherry For loop with range: Number: 0 Number: 1 Number: 2 Number: 3 Number: 4 For loop with range parameters: Even number: 2 Even number: 4 Even number: 6 Even number: 8 While loop: Count: 0 Count: 1 Count: 2 Count: 3 Count: 4 Using break: Number before break: 0 Number before break: 1 Number before break: 2 Number before break: 3 Number before break: 4 Using continue: Odd number: 1 Odd number: 3 Odd number: 5 Odd number: 7 Odd number: 9 For loop with else: Number: 0 Number: 1 Number: 2 For loop completed successfully! List comprehension: Squares: [1, 4, 9, 16, 25] Dictionary comprehension: Square dictionary: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Functions and Modules
Functions
Functions are blocks of reusable code designed to perform a specific task. They help organize code, make it more readable, and avoid repetition.
Defining Functions
You define functions in Python using the def
keyword, followed by the function name and parentheses.
Parameters and Arguments
Functions can accept inputs (parameters) and return outputs:
- Parameters: Variables listed in the function definition
- Arguments: Values passed to the function when it's called
Return Values
Functions can return values using the return
statement. A function can return multiple values as a tuple.
Default Parameters
You can provide default values for parameters, which are used if no argument is provided.
Keyword Arguments
You can specify arguments by the parameter name, allowing you to skip some arguments or change their order.
Variable-Length Arguments
Python supports functions with a variable number of arguments:
*args
: For variable positional arguments (as a tuple)**kwargs
: For variable keyword arguments (as a dictionary)
Lambda Functions
Lambda functions are small, anonymous functions defined with the lambda
keyword.
# Defining a simple function
def greet():
print("Hello, World!")
# Function with parameters
def greet_person(name):
print(f"Hello, {name}!")
# Function with return value
def add(a, b):
return a + b
# Function with default parameter
def greet_with_message(name, message="How are you?"):
print(f"Hello, {name}! {message}")
# Function returning multiple values
def get_dimensions():
return 1920, 1080 # Returns a tuple
# Using *args for variable positional arguments
def sum_all(*numbers):
total = 0
for num in numbers:
total += num
return total
# Using **kwargs for variable keyword arguments
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
# Lambda function
square = lambda x: x ** 2
# Calling the functions
greet()
greet_person("Alice")
result = add(5, 3)
print(f"5 + 3 = {result}")
greet_with_message("Bob")
greet_with_message("Charlie", "Nice to meet you!")
width, height = get_dimensions()
print(f"Resolution: {width}x{height}")
print(f"Sum of numbers: {sum_all(1, 2, 3, 4, 5)}")
print_info(name="David", age=30, city="New York")
print(f"Square of 5: {square(5)}")
Hello, World! Hello, Alice! 5 + 3 = 8 Hello, Bob! How are you? Hello, Charlie! Nice to meet you! Resolution: 1920x1080 Sum of numbers: 15 name: David age: 30 city: New York Square of 5: 25
Modules and Packages
Modules and packages help organize and reuse code across different Python programs.
Modules
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py
.
Importing Modules
You can import modules using the import
statement:
import module_name
: Imports the entire modulefrom module_name import function_name
: Imports a specific functionfrom module_name import *
: Imports all functions (not recommended)import module_name as alias
: Imports with an alias
Standard Library
Python comes with a rich standard library of modules for common tasks:
math
: Mathematical functionsrandom
: Random number generationdatetime
: Date and time handlingos
: Operating system interfacessys
: System-specific parameters and functions- And many more...
Packages
A package is a way of organizing related modules in a directory. A directory becomes a package when it contains a special file called __init__.py
.
Creating Your Own Modules
You can create your own modules by writing functions in a .py
file, which can then be imported in other scripts.
# Importing the entire module
import math
print(f"Pi: {math.pi}")
print(f"Square root of 16: {math.sqrt(16)}")
# Importing specific functions
from random import randint, choice
print(f"Random number between 1 and 10: {randint(1, 10)}")
print(f"Random choice from list: {choice(['apple', 'banana', 'cherry'])}")
# Importing with an alias
import datetime as dt
now = dt.datetime.now()
print(f"Current date and time: {now}")
# Using the os module
import os
print(f"Current working directory: {os.getcwd()}")
# Using the sys module
import sys
print(f"Python version: {sys.version}")
# Example of creating and using your own module
'''
File: mymodule.py
def say_hello(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
'''
# Then in another file:
'''
import mymodule
print(mymodule.say_hello("Alice"))
print(f"2 + 3 = {mymodule.add(2, 3)}")
'''
Pi: 3.141592653589793 Square root of 16: 4.0 Random number between 1 and 10: 7 Random choice from list: banana Current date and time: 2025-05-23 10:18:44.651983 Current working directory: /home/runner/workspace Python version: 3.11.5 (main, Feb 3 2024, 23:30:50) [GCC 12.3.0]