Python Learning Notes for Beginners
1. Introduction to Python
What is Python?
Python is a high-level, interpreted, general-purpose programming language. Created by
Guido van Rossum and first released in 1991, Python's design philosophy emphasizes
code readability with its notable use of significant indentation. It is dynamically typed
and garbage-collected. It supports multiple programming paradigms, including
structured (particularly procedural), object-oriented, and functional programming.
Python is often described as a
batteries-included" language due to its comprehensive standard library.
Why learn Python?
Python's popularity stems from several key advantages:
• Simplicity and Readability: Python's syntax is designed to be intuitive and easy to
read, making it an excellent choice for beginners.
• Versatility: It's used in various domains, including web development (Django,
Flask), data analysis (Pandas, NumPy), artificial intelligence and machine learning
(TensorFlow, PyTorch), scientific computing, automation, and more.
• Large Community and Ecosystem: Python has a vast and active community,
which means abundant resources, libraries, and frameworks are available.
• High Demand in the Job Market: Python skills are highly sought after in many
industries.
• Cross-Platform Compatibility: Python code can run on various operating systems
like Windows, macOS, and Linux without modification.
Setting up Python (installation, IDEs)
Installation
1. Download Python: Visit the official Python website ([Link]) and download
the latest stable version for your operating system.
2. Run the Installer:
◦ Windows: 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.
◦ macOS/Linux: Python often comes pre-installed. You can check your version
by opening a terminal and typing python3 --version . If you need a newer
version, you can download it from the official website or use a package
manager like Homebrew (macOS) or apt (Linux).
Integrated Development Environments (IDEs) and Text Editors
While you can write Python code in any text editor, IDEs offer features that enhance
productivity, such as syntax highlighting, code completion, debugging tools, and
integrated terminals.
• IDEs:
◦ PyCharm: A powerful and popular IDE specifically designed for Python
development. It comes in a free Community Edition and a paid Professional
Edition.
◦ VS Code (Visual Studio Code): A lightweight yet powerful code editor with
excellent Python support through extensions.
◦ Jupyter Notebook/JupyterLab: Ideal for data science and interactive
computing, allowing you to create and share documents that contain live
code, equations, visualizations, and narrative text.
• Text Editors:
◦ Sublime Text: A sophisticated text editor for code, markup, and prose.
◦ Atom: A hackable text editor for the 21st Century.
To verify your installation, open your terminal or command prompt and type:
python3 --version
You should see the installed Python version. If you added Python to PATH on Windows,
you might just use python --version .
2. Python Basics: Syntax and Data Types
Variables
Variables are used to store data values. In Python, you don't need to declare the type of a
variable; it's dynamically inferred.
x = 10 # Integer
name = "Alice" # String
is_python_fun = True # Boolean
Basic Data Types
Python has several built-in data types:
• Integers ( int ): Whole numbers (e.g., 5 , -100 ).
• Floating-point numbers ( float ): Numbers with a decimal point (e.g., 3.14 ,
-0.5 ).
• Strings ( str ): Sequences of characters enclosed in single or double quotes (e.g.,
'hello' , "Python" ).
• Booleans ( bool ): Represent truth values, either True or False .
# Examples of data types
my_integer = 42
my_float = 3.14159
my_string = "Hello, Python!"
my_boolean = False
print(type(my_integer))
print(type(my_float))
print(type(my_string))
print(type(my_boolean))
Operators
Operators are special symbols that perform operations on variables and values.
• Arithmetic Operators: Perform mathematical operations.
◦ + (addition)
◦ - (subtraction)
◦ * (multiplication)
◦ / (division)
◦ % (modulo - remainder of division)
◦ ** (exponentiation)
◦ // (floor division - division that results in a whole number)
a = 10
b = 3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.333...
print(a % b) # 1
print(a ** b) # 1000
print(a // b) # 3
• Comparison Operators: Compare two values and return True or False .
◦ == (equal to)
◦ != (not equal to)
◦ > (greater than)
◦ < (less than)
◦ >= (greater than or equal to)
◦ <= (less than or equal to)
x = 5
y = 8
print(x == y) # False
print(x != y) # True
print(x < y) # True
print(x >= y) # False
• Logical Operators: Combine conditional statements.
◦ and (returns True if both statements are true)
◦ or (returns True if one of the statements is true)
◦ not (reverses the result, returns False if the result is true)
p = True
q = False
print(p and q) # False
print(p or q) # True
print(not p) # False
Comments
Comments are used to explain code and are ignored by the Python interpreter. They
start with a # .
# This is a single-line comment
print("Hello, World!") # This comment explains the line
"""
This is a multi-line comment
or docstring.
"""
3. Control Flow
Control flow statements determine the order in which the code is executed.
Conditional Statements (if, elif, else)
Used to execute different blocks of code based on conditions.
age = 20
if age < 18:
print("You are a minor.")
elif age >= 18 and age < 65:
print("You are an adult.")
else:
print("You are a senior citizen.")
Loops (for, while)
Used to repeatedly execute a block of code.
• for loop: Iterates over a sequence (like a list, tuple, string, or range).
# Iterating through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Using range()
for i in range(5): # 0, 1, 2, 3, 4
print(i)
• while loop: Executes a block of code as long as a condition is true.
count = 0
while count < 5:
print(count)
count += 1
Break and Continue Statements
• break : Terminates the loop entirely.
for i in range(10):
if i == 5:
break
print(i)
# Output: 0, 1, 2, 3, 4
• continue : Skips the rest of the current iteration and moves to the next.
for i in range(5):
if i == 2:
continue
print(i)
# Output: 0, 1, 3, 4
4. Data Structures
Python offers several built-in data structures to organize and store data.
Lists
Ordered, mutable (changeable) sequences of items. Defined by square brackets [] .
my_list = [1, 2, 3, "hello", True]
print(my_list[0]) # Accessing elements: 1
my_list.append(4) # Adding elements
my_list[1] = 20 # Modifying elements
print(my_list) # [1, 20, 3, 'hello', True, 4]
Tuples
Ordered, immutable (unchangeable) sequences of items. Defined by parentheses () .
my_tuple = (1, 2, "python")
print(my_tuple[0]) # Accessing elements: 1
# my_tuple[1] = 20 # This would raise an error (immutable)
Dictionaries
Unordered collections of key-value pairs. Mutable. Defined by curly braces {} .
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
print(my_dict["name"]) # Accessing values: Alice
my_dict["age"] = 31 # Modifying values
my_dict["country"] = "USA" # Adding new key-value pairs
print(my_dict) # {'name': 'Alice', 'age': 31,
'city': 'New York', 'country': 'USA'}
Sets
Unordered collections of unique items. Mutable. Defined by curly braces {} or set() .
my_set = {1, 2, 3, 2, 1} # Duplicate values are automatically
removed
print(my_set) # {1, 2, 3}
my_set.add(4) # Adding elements
my_set.remove(1) # Removing elements
print(my_set) # {2, 3, 4}
5. Functions
Functions are blocks of reusable code that perform a specific task.
Defining and Calling Functions
Use the def keyword to define a function.
def greet(name):
print(f"Hello, {name}!")
greet("Bob") # Calling the function
Parameters and Arguments
• Parameters: Variables listed inside the parentheses in the function definition.
• Arguments: The actual values passed to the function when it's called.
def add_numbers(a, b): # a and b are parameters
return a + b
result = add_numbers(5, 3) # 5 and 3 are arguments
print(result) # 8
Return Values
The return statement is used to send a value back from a function.
def multiply(x, y):
return x * y
product = multiply(4, 6)
print(product) # 24
Scope of Variables
• Local Scope: Variables defined inside a function are local to that function.
• Global Scope: Variables defined outside any function are global and can be
accessed from anywhere.
global_var = "I am global"
def my_function():
local_var = "I am local"
print(global_var)
print(local_var)
my_function()
print(global_var)
# print(local_var) # This would cause an error
6. Modules and Packages
Importing Modules
A module is a file containing Python definitions and statements. You can use modules to
organize your code.
import math
print([Link](16)) # 4.0
print([Link])
from datetime import date
print([Link]())
Creating and Using Packages
A package is a collection of modules in directories. It must contain an __init__.py file
(even if empty) to be recognized as a package.
Let's imagine a directory structure:
my_project/
├── [Link]
└── my_package/
├── __init__.py
└── my_module.py
In my_package/my_module.py :
def hello_world():
return "Hello from my_module!"
In [Link] :
from my_package.my_module import hello_world
message = hello_world()
print(message)
7. File I/O
Python allows you to read from and write to files.
Reading from Files
# Create a dummy file for reading
with open("[Link]", "w") as f:
[Link]("Line 1: Hello Python\n")
[Link]("Line 2: File I/O is fun!")
# Reading the file
with open("[Link]", "r") as f:
content = [Link]()
print(content)
# Reading line by line
with open("[Link]", "r") as f:
for line in f:
print([Link]()) # .strip() removes newline
characters
Writing to Files
• "w" mode: Write mode (creates a new file or overwrites an existing one).
• "a" mode: Append mode (adds content to the end of an existing file).
# Writing to a new file (or overwriting existing)
with open("[Link]", "w") as f:
[Link]("This is the first line.\n")
[Link]("This is the second line.")
# Appending to a file
with open("[Link]", "a") as f:
[Link]("\nThis line was appended.")
8. Error Handling
Handling errors gracefully is crucial for robust programs.
Try, Except, Finally Blocks
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except TypeError:
print("Error: Type mismatch!")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
print("Execution completed (this always runs).")
Common Exceptions
• NameError : When a variable is not defined.
• TypeError : When an operation is applied to an inappropriate type.
• ValueError : When a function receives an argument of the correct type but an
inappropriate value.
• IndexError : When an index is out of range for a sequence.
• KeyError : When a dictionary key is not found.
• FileNotFoundError : When a file is not found.
9. Object-Oriented Programming (OOP) Concepts
(Basic)
Python is an object-oriented language. OOP allows you to structure your programs using
"objects" that combine data and behavior.
Classes and Objects
• Class: A blueprint for creating objects (a template).
• Object: An instance of a class.
class Dog:
# Class attribute
species = "Canis familiaris"
# Initializer / Constructor
def __init__(self, name, age):
[Link] = name # Instance attribute
[Link] = age # Instance attribute
# Instance method
def bark(self):
return f"{[Link]} says Woof!"
# Creating objects (instances of the Dog class)
my_dog = Dog("Buddy", 3)
your_dog = Dog("Lucy", 5)
print(my_dog.name) # Accessing instance attribute: Buddy
print(your_dog.age) # Accessing instance attribute: 5
print(my_dog.species) # Accessing class attribute: Canis
familiaris
print(my_dog.bark()) # Calling instance method: Buddy says
Woof!
Attributes and Methods
• Attributes: Variables associated with an object (data).
◦ name and age in the Dog class are instance attributes.
◦ species is a class attribute.
• Methods: Functions associated with an object (behavior).
◦ bark() in the Dog class is an instance method.
10. Practical Examples and Exercises
Example 1: Simple Calculator
def calculator(operation, num1, num2):
if operation == "add":
return num1 + num2
elif operation == "subtract":
return num1 - num2
elif operation == "multiply":
return num1 * num2
elif operation == "divide":
if num2 == 0:
return "Error: Cannot divide by zero!"
return num1 / num2
else:
return "Invalid operation"
print(calculator("add", 10, 5)) # 15
print(calculator("divide", 10, 0)) # Error: Cannot divide by
zero!
Example 2: Factorial Calculation
def factorial(n):
if n == 0:
return 1
else:
res = 1
for i in range(1, n + 1):
res *= i
return res
print(factorial(5)) # 120 (5*4*3*2*1)
print(factorial(0)) # 1
Exercise Ideas:
1. Temperature Converter: Write a function that converts Celsius to Fahrenheit and
vice versa.
2. Palindrome Checker: Write a function that checks if a given string is a palindrome
(reads the same forwards and backward).
3. Guessing Game: Create a simple number guessing game where the computer
picks a random number, and the user tries to guess it.
4. To-Do List Application: Build a command-line to-do list application that allows
users to add, view, and mark tasks as complete.
These notes cover the fundamental concepts of Python programming. Practice these
concepts by writing your own code and experimenting with different scenarios. Happy
coding!