🐍 What is Python?
📌 1. Definition
Python is a high-level, interpreted, general-purpose programming language. It was created by Guido van Rossum and released in 1991.
Python is known for its clear syntax and readability, which makes it a popular language for both beginners and experienced developers.
📌 2. History and Background
Python was developed in the late 1980s by Guido van Rossum at the National Research Institute for Mathematics and Computer Science in the Netherlands. The language was named after the British comedy group Monty Python.
📌 3. Key Features of Python
- Simple and Easy to Learn: Python has a simple syntax similar to English
- Interpreted: Python code is executed line by line, making debugging easier
- Cross-platform: Runs on Windows, macOS, Linux, and more
- Large Standard Library: Comes with extensive built-in modules
- Object-Oriented: Supports object-oriented programming concepts
📌 4. What is Python Used For?
- Web Development (Django, Flask)
- Data Science and Analytics
- Machine Learning and AI
- Automation and Scripting
- Desktop Applications
- Scientific Computing
📌 5. Python 2 vs Python 3
✅ Today, always use Python 3.x.
Python 2 reached end-of-life on January 1, 2020, and is no longer supported. Python 3 has many improvements and new features.
📌 6. Advantages of Python
- Simple syntax makes it easy to write and debug
- Rapid development – fewer lines of code compared to other languages
- Large ecosystem of third-party libraries (PyPI)
- Strong support for integration with other languages and tools
- Popular in academia, industry, and research
📌 7. Disadvantages of Python
- Slower than compiled languages like C/C++
- Not ideal for mobile app development
- High memory usage compared to low-level languages
- Limited in multithreading due to the Global Interpreter Lock (GIL)
📌 8. Python Syntax Example
# Simple Python program
name = input("Enter your name: ")
print("Hello, " + name)
This simple program asks for your name and greets you!
Practice Editor
🐍 Getting Started with Python
📌 1. What You Need to Begin
- A computer (Windows, macOS, or Linux)
- Internet connection (for downloading Python or using online editors)
- A text editor or an IDE (like VS Code, PyCharm, or IDLE)
📌 2. Installing Python
✅ Official Website:
Download Python from: 👉 https://www.python.org/downloads/
📦 Steps:
- Choose the version (always go for the latest Python 3.x)
- During installation:
- Check the box "Add Python to PATH"
- Click Install Now
✅ Verify Installation:
Open your terminal (CMD, PowerShell, or Bash):
python --version
or
python3 --version
📌 3. Writing Your First Python Program
You can write Python code in:
- IDLE (comes with Python)
- VS Code, PyCharm, Jupyter Notebook
- Online editors like:
✅ First Program:
print("Hello, World!")
💡 What it does: It tells Python to display the message "Hello, World!" on the screen.
📌 4. Python File Basics
- Python files end with
.py
- To run a script:
python yourfile.py
📌 5. Basic Python Syntax
🔹 Comments
# This is a comment
🔹 Variables
name = "Alice"
age = 25
🔹 Input and Output
name = input("Enter your name: ")
print("Hello,", name)
🐍 Python Syntax: The Basics
📌 1. Python is Indentation-Sensitive
Python uses indentation (spaces or tabs) to define blocks of code. This is different from many other languages that use curly braces {}.
# Correct
if 5 > 3:
print("Yes")
# Incorrect (no indentation)
if 5 > 3:
print("Yes") # ❌ Error
📌 2. Comments
Used to explain code. They are ignored by Python.
# This is a single-line comment
"""
This is a
multi-line comment
"""
📌 3. Print Statement
Used to display output.
print("Hello, World!")
📌 4. Variables and Data Types
No need to declare data types; Python is dynamically typed.
x = 10 # Integer
name = "Ali" # String
pi = 3.14 # Float
flag = True # Boolean
📌 5. Input
Get user input.
name = input("Enter your name: ")
print("Hello", name)
📌 6. Data Types and Casting
int("10") # Converts string to integer
str(123) # Converts integer to string
float("3.14") # Converts string to float
📌 7. Conditional Statements
x = 10
if x > 5:
print("Greater")
elif x == 5:
print("Equal")
else:
print("Smaller")
📌 8. Loops
🔹 for Loop
for i in range(5):
print(i) # Prints 0 to 4
🔹 while Loop
i = 0
while i < 5:
print(i)
i += 1
📌 9. Functions
def greet(name):
print("Hello", name)
greet("Aisha")
📌 10. Operators
# Arithmetic operators
+ - * / % ** //
# Comparison operators
== != > < >= <=
# Logical operators
and or not
📌 11. Lists, Tuples, Dictionaries, Sets
# List
fruits = ["apple", "banana", "cherry"]
# Tuple
coordinates = (10, 20)
# Dictionary
student = {"name": "Ali", "age": 20}
# Set
colors = {"red", "green", "blue"}
📌 12. List Example
fruits = ["apple", "banana"]
fruits.append("mango")
print(fruits[1]) # banana
📝 Python Variables
🧠 What Are Variables in Python?
A variable is like a container that holds data. It stores values you want to use in your program.
🔹 1. Declaring a Variable
Python does not require you to declare the type of variable. Just assign a value using =.
x = 5 # Integer
name = "Alice" # String
price = 19.99 # Float
is_valid = True # Boolean
🔹 2. Variable Naming Rules
✅ Valid names:
- Start with a letter or underscore _
- Followed by letters, digits, or underscores
- Case-sensitive (name and Name are different)
❌ Invalid names:
2name = "Ali" # ❌ Cannot start with a digit
user-name = "Ali" # ❌ Hyphens not allowed
✅ Valid examples:
user_name = "Ali"
_user = "hidden"
Name1 = "John"
🔹 3. Data Types Stored in Variables
integer = 42
float_num = 3.14
string = "Hello"
boolean = True
list_var = [1, 2, 3]
dict_var = {"key": "value"}
🔹 4. Checking the Type of a Variable
x = 10
print(type(x)) # Output: <class 'int'>
🔹 5. Multiple Assignments
You can assign multiple variables at once:
a, b, c = 1, 2, 3
print(a, b, c) # Output: 1 2 3
# Assigning the same value to multiple variables:
x = y = z = 0
🔹 6. Constants (By Convention)
Python doesn't have true constants, but you can use uppercase names to indicate a value shouldn't change.
PI = 3.14159
MAX_USERS = 100
🔒 These can still be changed in code, but shouldn't be.
🔹 7. Type Casting (Changing Variable Types)
x = str(10) # '10'
y = int("5") # 5
z = float("3.14") # 3.14
🔹 8. Deleting a Variable
x = 10
del x
Trying to use x after this will give an error.
🧠 What Are Data Types in Python?
A data type tells Python what kind of value a variable holds. For example:
- "Ali" is a string
- 10 is an integer
- 3.14 is a float
- True is a boolean
Python automatically assigns the correct type when you assign a value to a variable.
🔹 1. Basic (Built-in) Data Types
🔸 int – Integer
a = 100
print(type(a)) # <class 'int'>
🔸 float – Decimal / Floating Point
pi = 3.14159
print(type(pi)) # <class 'float'>
🔸 str – String
name = "Alice"
print(type(name)) # <class 'str'>
🔸 bool – Boolean
is_online = True
print(type(is_online)) # <class 'bool'>
🔹 2. Collection Data Types
🔸 list – Mutable Sequence
fruits = ["apple", "banana", "cherry"]
print(type(fruits)) # <class 'list'>
🔸 tuple – Immutable Sequence
point = (10, 20)
print(type(point)) # <class 'tuple'>
🔸 set – Unique, Unordered Collection
colors = {"red", "green", "blue"}
print(type(colors)) # <class 'set'>
🔸 dict – Dictionary (Key:Value Pairs)
student = {"name": "Ali", "age": 21}
print(type(student)) # <class 'dict'>
🔹 3. None Type
Represents the absence of a value.
x = None
print(type(x)) # <class 'NoneType'>
🔹 4. Type Conversion (Casting)
Convert one type into another:
int("10") # 10
str(99) # "99"
float("3.14") # 3.14
bool(1) # True
🔹 5. Checking the Type
a = 10
print(type(a)) # <class 'int'>
🔢 Python Numbers
In Python, numbers are a built-in data type used to store numeric values. There are three main numeric types:
🔹 1. Integer (int)
Whole numbers without decimals. Can be positive or negative.
a = 100
b = -25
print(type(a)) # <class 'int'>
🔹 2. Float (float)
Numbers with decimal points. Used for measurements, prices, etc.
pi = 3.14159
temperature = -5.5
print(type(pi)) # <class 'float'>
🔹 3. Complex (complex)
Numbers with a real and imaginary part (a + bj). j is the imaginary unit in Python (like i in math).
z = 2 + 3j
print(type(z)) # <class 'complex'>
🔸 4. Type Conversion (Casting)
You can convert between number types using:
int(3.9) # 3
float(5) # 5.0
complex(4) # (4+0j)
📝 Python Comments
✅ What is a Comment?
A comment is a line in your code that Python ignores during execution. It is used to:
🔹 1. Single-Line Comments
Use the # symbol. Everything after # on that line is ignored by Python.
🔹 2. Multi-Line Comments (Docstrings or Block Comments)
Python doesn't have official multi-line comments, but you can:
Method 1: Use multiple #
Method 2: Use triple quotes (''' or """)
(These are technically multi-line strings, often used for documentation.)
💡 Triple quotes are mainly used for docstrings in functions, classes, and modules.
🔹 3. Docstrings (Documentation Strings)
A docstring is a special kind of comment used to describe a function, class, or module. It goes right after the def, class, or top of a file.
🧠 Why Use Comments?
🚫 What Not to Do with Comments
Don't over-comment obvious code:
Don't use comments to justify bad code. Instead, refactor the code.