Your cart is currently empty!
Learn Python (Full Tutorial)

Python Introduction
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
It is used for:
- web development (server-side),
- software development,
- mathematics,
- system scripting.
What can Python do?
- Python can be used on a server to create web applications.
- Python can be used alongside software to create workflows.
- Python can connect to database systems. It can also read and modify files.
- Python can be used to handle big data and perform complex mathematics.
- Python can be used for rapid prototyping, or for production-ready software development.
Why Python?
- Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
- Python has a simple syntax similar to the English language.
- Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
- Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
- Python can be treated in a procedural way, an object-oriented way or a functional way.
Good to know
- The most recent major version of Python is Python 3, which we shall be using in this tutorial. However, Python 2, although not being updated with anything other than security updates, is still quite popular.
- In this tutorial Python will be written in a text editor. It is possible to write Python in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are particularly useful when managing larger collections of Python files.
Python Syntax compared to other programming languages
- Python was designed for readability, and has some similarities to the English language with influence from mathematics.
- Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.
- Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose.
Example
print(“Hello, World!”)
Python: Getting Started Guide
1. Installing Python
Most modern Windows, Mac, and Linux systems already come with Python pre-installed.
Let’s check if it’s available on your computer.
🔹 Check if Python is Installed
On Windows:
-
Open the Start Menu and search for Python, or
-
Open Command Prompt (
cmd.exe) and type:
or, if that doesn’t work:
On macOS or Linux:
-
Open the Terminal, then type:
or, depending on your setup:
If Python is installed, you’ll see an output like:
If you don’t have Python installed, you can download it for free from the official website:
👉 https://www.python.org/downloads/
2. Your First Python Program
Python is an interpreted programming language, meaning you can write and run code directly without compiling.
🔹 Step 1: Create a Python File
Create a new file called helloworld.py using any text editor (e.g., Notepad, VS Code, Sublime, etc.).
Inside the file, write this simple line:
🔹 Step 2: Run Your Program
Open the Command Prompt (Windows) or Terminal (Mac/Linux), navigate to the folder where you saved the file, and type:
✅ Output:
Congratulations — you just wrote and executed your first Python program! 🎉
3. Using the Python Command Line (Interactive Mode)
Sometimes, you may want to test a few lines of code quickly without creating a file.
Python allows you to do this through its interactive command line (also called the REPL).
🔹 Open the Python REPL
On Windows:
or if that doesn’t work:
On macOS/Linux:
You’ll see something like this:
Now, you can type Python commands directly:
🔹 Exit the Python REPL
When you’re done, type:
or press Ctrl + Z (Windows) or Ctrl + D (Mac/Linux) and hit Enter.
✅ Summary
| Task | Command |
|---|---|
| Check Python version | python --version or python3 --version |
| Run a Python file | python filename.py |
| Open Python interactive mode | python or python3 |
| Exit interactive mode | exit() |
Now you’re ready to start learning Python and writing your own programs. 🚀
Next steps: explore variables, data types, and control structures to build on this foundation.
Python Syntax Guide
1. Executing Python Syntax
As you learned earlier, Python code (called syntax) can be executed in two main ways:
🔹 Option 1: Run Directly in the Command Line
You can type and execute Python commands interactively:
This is useful for testing small pieces of code quickly.
🔹 Option 2: Run a Python File
You can also write your code in a file with the .py extension and run it using the command line.
Example:
2. Python Indentation
In Python, indentation (the spaces at the beginning of a line) is not optional — it defines the structure of your code.
Unlike many other languages where indentation is just for readability, Python uses indentation to mark code blocks.
✅ Correct Example:
❌ Incorrect Example (Missing Indentation):
Output:
🔹 How Many Spaces?
-
You can use any number of spaces, but you must be consistent.
-
The common convention (and the Python standard) is 4 spaces per indentation level.
Example:
❌ Inconsistent Indentation Example:
Output:
3. Python Variables
In Python, you don’t need to declare variables before using them.
A variable is created automatically the moment you assign a value to it.
✅ Example:
Output:
-
You can store numbers, text, lists, booleans, and more.
-
Variable names are case-sensitive (
myVar,MyVar, andMYVARare all different).
4. Comments in Python
Comments are used to explain code and improve readability.
Python ignores comments during execution.
🔹 Single-Line Comments
Start a comment with a # symbol.
Everything after # on that line will be ignored.
Example:
🔹 Multi-Line Comments (Tip)
Python doesn’t have a specific multi-line comment syntax,
but you can use multiple # lines or a triple-quoted string for documentation-style comments.
Example:
✅ Summary
| Concept | Description | Example |
|---|---|---|
| Execute Code | Run directly or from a .py file |
python myfile.py |
| Indentation | Defines code blocks; use 4 spaces | if 5 > 2: → indented code |
| Variables | Created when assigned | x = 5, y = "Hello" |
| Comments | Explain code; ignored by Python | # This is a comment |
Tip:
Always keep your indentation consistent and add meaningful comments — it makes your code more readable, maintainable, and professional. 🧠💡
Python Comments
1. What Are Comments?
Comments are lines in your Python code that are ignored by the interpreter.
They are used to:
-
🧩 Explain what your code does
-
👀 Make your code more readable
-
🧪 Temporarily disable (skip) code during testing
Comments do not affect the program’s execution — they’re just there for humans to read.
2. Creating a Comment
A single-line comment starts with the # (hash) symbol.
Everything after # on that line will be ignored by Python.
✅ Example:
Output:
The line starting with # is ignored.
3. Inline Comments
You can also place a comment at the end of a line of code.
Python will ignore everything after the #.
✅ Example:
Output:
This is useful for quick explanations beside code statements.
4. Disabling Code with Comments
You can use comments to temporarily prevent a line of code from running,
which is helpful when debugging or testing.
✅ Example:
Output:
Here, the first print() statement is skipped because it’s commented out.
5. Multi-Line Comments
Python doesn’t have a dedicated syntax for multi-line comments like some other languages.
However, there are two common ways to write multi-line comments:
🔹 Option 1: Multiple # Lines (Preferred)
Simply start each line with a #.
This method is clear and standard practice.
🔹 Option 2: Triple-Quoted Strings (Alternative)
You can also use a multi-line string (triple quotes ''' or """) that isn’t assigned to a variable.
Python will ignore it since it’s not being used.
Note:
While this works, triple-quoted strings are technically string literals, not real comments.
They’re often used for docstrings — special documentation strings that describe functions or modules.
✅ Summary
| Type | Syntax | Example |
|---|---|---|
| Single-line | # followed by text |
# This is a comment |
| Inline | After code on the same line | print("Hi") # Comment |
| Disabled code | Prefix with # |
# print("Off") |
| Multi-line | # each line or triple quotes |
""" multi-line """ |
💡 Tip:
Use comments wisely — write why the code does something, not just what it does.
Good comments make your code easier for others (and your future self!) to understand. 🧠
📦 Python Variables
1. What Are Variables?
In Python, variables are containers used to store data values.
Think of a variable as a label you attach to a piece of data — you can use that label later in your code.
2. Creating Variables
Python does not require explicit variable declarations.
A variable is created automatically as soon as you assign a value to it.
✅ Example:
Output:
3. Dynamic Typing
Unlike many other programming languages, Python variables don’t need a fixed type.
You can assign a value of one type, then later assign a value of another type — and Python handles it dynamically.
✅ Example:
Output:
Python automatically updates the variable’s data type when the value changes.
4. Casting (Specifying the Type)
Sometimes, you may want to explicitly define the data type of a variable.
You can do this by casting with built-in type functions like str(), int(), or float().
✅ Example:
5. Getting the Type of a Variable
To check the data type of a variable, use the built-in type() function.
✅ Example:
Output:
6. Single or Double Quotes for Strings
Python allows you to create string variables using either single (') or double (") quotes.
Both are valid and equivalent.
✅ Example:
Output:
✅ Tip: Use one style consistently throughout your code for readability.
Double quotes are often preferred when your string contains an apostrophe (e.g.,"I'm happy").
7. Case Sensitivity
Python variable names are case-sensitive — this means a, A, and myVar are all different variables.
✅ Example:
Output:
✅ Summary
| Concept | Description | Example |
|---|---|---|
| Variable Creation | Automatically created when assigned | x = 5 |
| Dynamic Typing | Variables can change type | x = 5 → x = "Hi" |
| Casting | Explicitly set type | x = float(3) |
| Check Type | Use type() function |
type(x) |
| String Quotes | Use ' ' or " " |
'John' = "John" |
| Case Sensitivity | A ≠ a |
A = 1, a = 2 |
💡 Pro Tip:
Use descriptive variable names like age, price, or user_name instead of single letters.
It makes your code easier to understand and maintain. 🧠
🏷️ Python Variable Names
1. What Are Variable Names?
A variable name is the identifier you assign to store a value in Python.
You can use short names like x or y, or descriptive names like age, car_name, or total_volume.
Good variable names make your code easier to read and understand.
Let’s look at the rules and best practices for naming them.
2. Rules for Python Variable Names
When creating variable names in Python, follow these essential rules:
-
✅ Must start with a letter or underscore (
_)-
Examples:
name,_score
-
-
❌ Cannot start with a number
-
Example:
2score❌ (invalid)
-
-
✅ Can contain only letters, numbers, and underscores
-
Allowed characters:
A–Z,a–z,0–9, and_
-
-
⚠️ Case-sensitive
-
age,Age, andAGEare three different variables
-
-
❌ Cannot be a Python keyword (like
if,for,class,True, etc.)
3. Examples of Valid Variable Names
These examples follow all the rules:
All of these are valid and will work correctly.
4. Examples of Invalid Variable Names
These examples will cause syntax errors because they break naming rules:
Python will raise an error like:
5. 💡 Best Practices for Naming Variables
Follow these simple tips to write clean, readable Python code:
| Rule | Example | Notes |
|---|---|---|
| Use descriptive names | user_name, total_price |
Makes your code self-explanatory |
| Use lowercase_with_underscores | car_speed |
Follows the PEP 8 naming convention |
| Avoid confusing letters | Don’t use l, O, or I |
They can look like numbers |
| Be consistent | Stick to one style | Increases readability |
| Avoid keywords | Don’t use for, if, True, etc. |
These are reserved by Python |
6. 🔍 Checking Python Keywords
You can view all reserved Python keywords using the keyword module:
Output (example):
✅ Summary
| Rule | Valid Example | Invalid Example |
|---|---|---|
| Starts with letter/underscore | _name, user1 |
1user |
| No special characters or spaces | total_sum |
total-sum, total sum |
| Case-sensitive | Name ≠ name |
— |
| Not a Python keyword | value |
for, if |
💬 Tip:
Choose clear, descriptive variable names that reflect their purpose.
Good naming habits make your code easier to debug, share, and maintain. 🧠✨
🍊 Python Variables – Assign Multiple Values
In Python, you can assign values to multiple variables in a single line.
This makes your code cleaner and more efficient — especially when working with multiple related values.
1. Assign Multiple Values to Multiple Variables
Python allows you to assign different values to multiple variables at once.
✅ Example:
Output:
Each variable on the left (x, y, z) is assigned the corresponding value from the right.
⚠️ Important:
The number of variables must match the number of values.
Otherwise, Python will raise aValueError.
❌ Example (Mismatch):
Error:
2. Assign One Value to Multiple Variables
You can also assign the same value to multiple variables in one line.
✅ Example:
Output:
All three variables now refer to the same value ("Orange").
3. Unpack a Collection
If you have a collection (like a list, tuple, or set) containing multiple values,
you can unpack them directly into separate variables.
This is called unpacking in Python.
✅ Example — Unpack a List:
Output:
Each element in the list is assigned to a variable in the same order.
4. 🧩 Advanced Example — Partial Unpacking (Optional)
You can use * to unpack “the rest” of the collection into a list.
✅ Example:
Output:
The *z variable collects all remaining items as a list.
✅ Summary
| Operation | Description | Example |
|---|---|---|
| Multiple values | Assign different values | x, y, z = 1, 2, 3 |
| One value to all | Assign same value | x = y = z = "Hi" |
| Unpack collection | Extract list/tuple values | x, y, z = fruits |
| Partial unpacking | Capture remaining items | x, *y = fruits |
💡 Tip:
Unpacking is especially useful when working with tuples, lists, or function returns.
It keeps your code clean, concise, and Pythonic 🐍✨
🖨️ Python – Output Variables
The print() function in Python is used to display output — including variables, text, and expressions.
Let’s explore how to use it effectively.
1. Printing a Single Variable
The simplest way to show a variable’s value is by passing it to the print() function.
✅ Example:
Output:
2. Printing Multiple Variables
You can print multiple variables at once by separating them with commas.
✅ Example:
Output:
Python automatically adds spaces between each item when using commas.
3. Using the + Operator
You can also concatenate (join) string variables using the + operator.
✅ Example:
Output:
💡 Note: Notice the spaces in
"Python "and"is ".
Without them, the result would bePythonisawesome.
4. The + Operator with Numbers
When used with numbers, the + operator performs addition.
✅ Example:
Output:
5. Mixing Strings and Numbers
If you try to combine a string and a number with +, Python will raise an error because they’re different data types.
❌ Example:
Error:
6. Best Practice — Use Commas
To print different data types together, separate them with commas.
Python will handle the conversion automatically.
✅ Example:
Output:
This is the recommended way to print multiple variables safely.
🌍 Python – Global Variables
1. What Are Global Variables?
Variables created outside of any function are called global variables.
They can be accessed from anywhere in your code — both inside and outside functions.
✅ Example:
Output:
2. Local vs Global Variables
If you create a variable inside a function, it becomes local to that function.
A local variable is separate from a global variable, even if they share the same name.
✅ Example:
Output:
Here:
-
Inside the function →
x = "fantastic"(local variable) -
Outside the function →
x = "awesome"(global variable)
3. The global Keyword
By default, variables declared inside a function are local.
If you want to create or modify a global variable from inside a function, use the global keyword.
✅ Example 1: Creating a Global Variable Inside a Function
Output:
✅ Example 2: Modifying a Global Variable Inside a Function
Output:
Here, the global keyword allows the function to update the global x variable.
🧩 Python – Variable Exercises
You’ve now learned how to create, use, and manage variables in Python.
Let’s test your understanding with a simple exercise!
🧠 Exercise:
👉 Create a variable named carname and assign the value Volvo to it.
✅ Expected Output:
🎯 You’ve completed the Python Variables chapter!
You now understand how to:
-
Create and name variables
-
Assign multiple values
-
Output variables correctly
-
Work with global and local variables
Python Data Types
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
| Text Type: | str |
| Numeric Types: | int, float, complex |
| Sequence Types: | list, tuple, range |
| Mapping Type: | dict |
| Set Types: | set, frozenset |
| Boolean Type: | bool |
| Binary Types: | bytes, bytearray, memoryview |
| None Type: | NoneType |
Getting the Data Type
You can get the data type of any object by using the type() function:
Example
Print the data type of the variable x:
x = 5
print(type(x))
Setting the Data Type
In Python, the data type is set when you assign a value to a variable:
| Example | Data Type | Num |
|---|---|---|
| x = “Hello World” | str | 1 |
| x = 20 | int | 2 |
| x = 20.5 | float | 3 |
| x = 1j | complex | 4 |
| x = [“apple”, “banana”, “cherry”] | list | 5 |
| x = (“apple”, “banana”, “cherry”) | tuple | 6 |
| x = range(6) | range | 7 |
| x = {“name” : “John”, “age” : 36} | dict | 8 |
| x = {“apple”, “banana”, “cherry”} | set | 9 |
| x = frozenset({“apple”, “banana”, “cherry”}) | frozenset | 10 |
| x = True | bool | 11 |
| x = b”Hello” | bytes | 12 |
| x = bytearray(5) | bytearray | 13 |
| x = memoryview(bytes(5)) | memoryview | 14 |
| x = None | NoneType | 15 |
Setting the Specific Data Type
If you want to specify the data type, you can use the following constructor functions:
| Example | Data Type | Num |
|---|---|---|
| x = str(“Hello World”) | str | 1 |
| x = int(20) | int | 2 |
| x = float(20.5) | float | 3 |
| x = complex(1j) | complex | 4 |
| x = list((“apple”, “banana”, “cherry”)) | list | 5 |
| x = tuple((“apple”, “banana”, “cherry”)) | tuple | 6 |
| x = range(6) | range | 7 |
| x = dict(name=”John”, age=36) | dict | 8 |
| x = set((“apple”, “banana”, “cherry”)) | set | 9 |
| x = frozenset((“apple”, “banana”, “cherry”)) | frozenset | 10 |
| x = bool(5) | bool | 11 |
| x = bytes(5) | bytes | 12 |
| x = bytearray(5) | bytearray | 13 |
| x = memoryview(bytes(5)) | memoryview | 14 |
🔢 Python Numbers
In Python, there are three main numeric types:
| Type | Description | Example |
|---|---|---|
int |
Whole numbers (no decimals) | 5, -23, 1000000 |
float |
Numbers with decimals or in scientific notation | 3.14, -0.5, 2e3 |
complex |
Numbers with an imaginary part (j) |
3+5j, 2j, -7j |
🧮 Creating Numeric Variables
Python automatically assigns the correct numeric type when you give a value.
✅ Example:
Output:
🧱 Integers (int)
An integer is a whole number, positive or negative, without decimals.
Python integers have unlimited length.
✅ Example:
🌊 Floats (float)
A float (floating-point number) is a number that contains a decimal point.
✅ Example:
Floats can also be written in scientific notation, using "e" or "E" to indicate powers of 10.
✅ Example:
🌀 Complex Numbers (complex)
Complex numbers have a real part and an imaginary part, written with j.
✅ Example:
🔄 Type Conversion
You can convert numbers between types using:
-
int()→ to integer -
float()→ to float -
complex()→ to complex
✅ Example:
Note: You cannot convert a complex number into another numeric type.
🎲 Random Numbers
Python does not have a built-in random() function,
but the random module can generate random numbers.
✅ Example:
This prints a random number between 1 and 9 (inclusive of 1, exclusive of 10).
🧠 Exercise:
Fill in the missing code to convert x into a floating point number.
🧱 Python Casting
Sometimes you may want to manually specify the type of a variable.
Python supports casting using constructor functions:
| Function | Description |
|---|---|
int() |
Converts a number or string to an integer |
float() |
Converts a number or string to a float |
str() |
Converts a number or other data to a string |
✅ Integers
✅ Floats
✅ Strings
🧵 Python Strings
Strings in Python are sequences of characters, enclosed in single or double quotes.
✅ Example:
✍️ Assigning a String to a Variable
📜 Multiline Strings
You can create multiline strings using triple quotes (""" or ''').
✅ Example 1 (Double Quotes):
✅ Example 2 (Single Quotes):
💡 The line breaks in the code are preserved in the output.
🔠 Strings Are Arrays
Strings act like arrays of characters —
you can access individual characters using square brackets [].
✅ Example:
Output:
🔁 Looping Through a String
You can loop through the characters of a string using a for loop.
✅ Example:
📏 String Length
Use the len() function to get the number of characters in a string.
✅ Example:
Output:
🔍 Check if a Substring Exists
Use the keyword in to check if a substring exists in a string.
✅ Example:
Output:
You can also use it in an if statement:
🚫 Check if a Substring Does NOT Exist
Use not in to check if a substring is not present.
✅ Example:
Output:
Or with an if statement:
🧵 Python Strings — Deep Dive
✂️ Slicing Strings
You can extract parts of a string using slice syntax.
Specify the start and end indexes separated by a colon : — the slice includes the start index but excludes the end index.
✅ Example:
Output:
💡 Indexing starts at
0, sob[2]is the third character.
🏁 Slice From the Start
Omit the start index to slice from the beginning:
Output: Hello
🎯 Slice To the End
Omit the end index to slice to the end:
Output: llo, World!
🔢 Negative Indexing
Use negative indexes to slice from the end of the string:
Output: orl
This selects characters from
"o"(position-5) up to but not including"d"(position-2).
✨ Modify Strings
Python provides many built-in string methods for cleaning, formatting, and transforming text.
🔠 Upper Case
Output: HELLO, WORLD!
🔡 Lower Case
Output: hello, world!
🚿 Remove Whitespace
Whitespace is the space before or after the text.
Use .strip() to remove it.
🔁 Replace Text
Output: Jello, World!
✂️ Split Text
The .split() method divides a string into a list using a separator (default is space).
Output: ['Hello', ' World!']
🔗 String Concatenation
To combine two strings, use the + operator.
✅ Example 1:
Output: HelloWorld
✅ Example 2 (With Space):
Output: Hello World
🧩 String Formatting
You can insert variables into strings using the .format() method.
This is the proper way to mix strings and numbers.
⚠️ Incorrect:
✅ Correct:
🧮 Multiple Placeholders:
🔢 Indexed Placeholders:
You can specify the index of each placeholder:
🧍♂️ Escape Characters
Some characters can’t appear directly in a string.
Use a backslash (\) to insert special characters.
⚠️ Example (Error):
✅ Correct with Escape Character:
Common Escape Sequences
| Code | Description |
|---|---|
\' |
Single quote |
\\ |
Backslash |
\n |
New line |
\r |
Carriage return |
\t |
Tab |
\b |
Backspace |
\f |
Form feed |
\ooo |
Octal value |
\xhh |
Hexadecimal value |
🧰 String Methods Overview
💡 All string methods return a new value — they do not change the original string.
| Method | Description |
|---|---|
capitalize() |
Capitalizes the first letter |
casefold() |
Converts string to lowercase |
center() |
Returns a centered string |
count() |
Counts occurrences of a substring |
encode() |
Returns an encoded version |
endswith() |
Checks if string ends with a value |
expandtabs() |
Sets tab size |
find() |
Finds position of substring |
format() |
Formats values into string |
index() |
Finds substring, raises error if not found |
isalnum() |
Checks if all chars are alphanumeric |
isalpha() |
Checks if all chars are letters |
isdigit() |
Checks if all chars are digits |
islower() |
Checks if all chars are lowercase |
isspace() |
Checks if string is whitespace |
istitle() |
Checks if string is titlecased |
isupper() |
Checks if all chars are uppercase |
join() |
Joins iterable into a string |
ljust() |
Left-justifies text |
lower() |
Converts to lowercase |
replace() |
Replaces substring |
rfind() |
Finds substring from right |
rjust() |
Right-justifies text |
split() |
Splits string into list |
startswith() |
Checks prefix |
strip() |
Removes whitespace |
swapcase() |
Swaps case |
title() |
Title-cases string |
upper() |
Converts to uppercase |
zfill() |
Pads with zeros |
🧠 Exercise
Use the len() function to print the length of a string.
⚖️ Python Booleans
Booleans represent True or False values.
✅ Boolean Values
You can evaluate any expression — Python will return either True or False.
Example:
Output:
🧠 Using Booleans in if Statements:
🧩 Evaluate Values with bool()
You can test any value using the bool() function.
✅ Examples:
✅ Variables:
✅ Most Values Are True
Non-empty values evaluate to True:
🚫 Some Values Are False
The following evaluate to False:
⚙️ Custom Class Example
If a class defines __len__() and returns 0, its objects evaluate to False.
🔁 Functions Returning Booleans
You can make functions that return True or False.
Use the return value to control logic:
🧩 Built-in Boolean Function: isinstance()
Use it to check the type of an object:
🧮 Python Operators
Operators perform actions on variables/values.
Arithmetic
Assignment
Comparison
Logical
Identity
Membership
Bitwise
Precedence (high → low)
🧺 Python Lists
-
Ordered, changeable, allows duplicates
-
Create:
mylist = ["apple", "banana", "cherry"]orlist(("apple","banana")) -
Length:
len(mylist) -
Access:
mylist[0],mylist[-1], rangesmylist[1:3] -
Check:
"apple" in mylist
Modify
Remove
Loop
Copy & Join
🍎 Python Tuples
-
Ordered, unchangeable, allows duplicates
-
Create:
mytuple = ("apple","banana","cherry")ortuple(("apple","banana")) -
One item:
("apple",) -
Access:
mytuple[0],mytuple[-1], rangesmytuple[1:3] -
Length:
len(mytuple) -
Mixed types allowed:
("abc", 34, True)
🍏 Python Tuples
-
Ordered, immutable, allows duplicates
-
Create:
t = ("apple","banana")ortuple(("apple","banana")) -
Single item:
("apple",) -
Access:
t[0],t[-1], slices:t[1:3],t[:3],t[2:],t[-4:-1] -
Check:
"apple" in t
Modify / Add
Remove
Join / Multiply
🍀 Python Sets
-
Unordered, mutable, no duplicates
-
Create:
s = {"apple","banana"}orset(("apple","banana")) -
Length:
len(s) -
Check:
"apple" in s
Add / Update
Remove
Set Operations
📖 Python Dictionaries
-
Ordered, mutable, key:value pairs, no duplicate keys
-
Create:
-
Access:
d["brand"] -
Modify / Add:
d["year"]=2020 -
Length:
len(d) -
Values can be any type: string, int, list, boolean
⚡ Python If … Else
-
Comparison:
== != < <= > >= -
Structure:
-
Single-line if / else:
-
Logical operators:
-
Nested if:
-
Empty if:
pass
Python Loops
While Loop
Executes while a condition is True.
Break: exits loop immediately.
Continue: skips current iteration.
Else: runs when loop ends normally.
For Loop
Iterates over a sequence (list, tuple, string, etc.).
Range: loop specific number of times.
Break / Continue / Else work same as while.
Nested Loops:
Functions
-
Arguments / Parameters: input values.
-
Default values:
def f(x=5): ... -
Arbitrary args:
*args(tuple),**kwargs(dict). -
Return values:
return x*2 -
Pass: placeholder in empty function.
-
Lambda: one-line anonymous function.
Recursion: function calls itself.
Arrays (Lists)
Loop:
Classes & Objects
-
Modify / Delete properties:
p1.age = 40,del p1.age -
Delete object:
del p1 -
Pass: placeholder for empty class
Inheritance
Iterators
Custom iterator:
Scope
-
Local: inside function
-
Global: outside function
Python Modules
-
Module: A file (
.py) with functions, variables, or classes you can reuse. -
Create: Save code in
mymodule.py:
-
Use Module:
-
Alias Module:
-
Import Specific:
-
Built-in Module:
Datetime
Math
JSON
-
Formatting:
RegEx (re)
PIP (Package Manager)
Try / Except
-
Raise Exception:
