What is a Variable?
Think of a variable like a box with a label on it.
You put something inside the box, and you use the label to find it later.
name = "Gagan"
Here:
nameis the label (variable name)"Gagan"is the value stored inside it=means "store this value in this variable"
Now whenever you use name in your code, Python knows it means "Gagan".
Your First Variable Program
name = "Gagan" age = 22 print(name) print(age)
Output:
Gagan
22
Simple! You stored two values and printed them.
Variable Naming Rules
Not everything is allowed as a variable name. Here are the rules:
Allowed:
my_name = "Gagan" # underscore is allowed
age2 = 25 # numbers allowed (not at start)
firstName = "Gagan" # camelCase is allowed
NOT Allowed:
2age = 25 # cannot start with a number
my-name = "Gagan" # hyphen not allowed
my name = "Gagan" # spaces not allowed
Best Practice: Use lowercase with underscores for variable names. This is called snake_case and it's the Python standard:
first_name = "Gagan" phone_number = 9876543210 is_student = True
Data Types
Every value in Python has a type. Python has several built-in data types. As a beginner, these 4 are the most important:
1. String (str) — Text
Any text inside quotes is a string:
name = "Gagan" city = "Delhi" message = "I love Python"
print(type(name)) # <class 'str'>
type() tells you what type a variable is. Very useful for debugging.
2. Integer (int) — Whole Numbers
Numbers without decimal points:
age = 22 year = 2025 students = 100
print(type(age)) # <class 'int'>
3. Float (float) — Decimal Numbers
Numbers with decimal points:
price = 99.99 height = 5.11 temperature = 36.6
print(type(price)) # <class 'float'>
4. Boolean (bool) — True or False
Only two possible values — True or False:
is_student = True has_job = False is_raining = True
print(type(is_student)) # <class 'bool'>
Important: True and False must start with capital letters. true or false will give an error.
Using Variables with print()
You can combine variables and text in print using f-strings (the modern way):
name = "Gagan" age = 22 city = "Delhi"
print(f"My name is {name}") print(f"I am {age} years old") print(f"I live in {city}") print(f"My name is {name} and I am {age} years old")
Output:
My name is Gagan
I am 22 years old
I live in Delhi
My name is Gagan and I am 22 years old
The f before the quote makes it an f-string. Inside {} curly brackets you write your variable name and Python automatically puts its value there.
This is the most used and cleanest way to print variables in modern Python.
Updating Variables
You can change the value of a variable anytime:
score = 0 print(f"Score: {score}")
score = 10 print(f"Score: {score}")
score = 50 print(f"Score: {score}")
Output:
Score: 0
Score: 10
Score: 50
The variable just gets updated with the new value.
Multiple Variables in One Line
Python allows this shortcut:
x, y, z = 10, 20, 30 print(x) # 10 print(y) # 20 print(z) # 30
Or assign the same value to multiple variables:
a = b = c = 0 print(a, b, c) # 0 0 0
A Complete Example
Let's put it all together:
# Personal Information name = "Gagan" age = 22 city = "Delhi" height = 5.11 is_student = True
print(f"Name: {name}") print(f"Age: {age}") print(f"City: {city}") print(f"Height: {height}") print(f"Student: {is_student}") print(f"Data type of name: {type(name)}") print(f"Data type of age: {type(age)}")
Output:
Name: Gagan
Age: 22
City: Delhi
Height: 5.11
Student: True
Data type of name: <class 'str'>
Data type of age: <class 'int'>
Exercise 🏋️
Create a program that stores this information in variables and prints it using f-strings:
- Your name
- Your age
- Your favorite subject
- Your city
- Whether you are a student (True/False)
Expected output format:
Hello! My name is [name]
I am [age] years old
My favorite subject is [subject]
I live in [city]
Am I a student? [True/False]
Try it yourself!
Basic Math Operations
Python as a Calculator
Python can do all kinds of math. Think of it as a very powerful calculator.
Let's start simple:
print(2 + 3) # 5 print(10 - 4) # 6 print(3 * 4) # 12 print(10 / 2) # 5.0
All Math Operators in Python
|
Operator |
Name |
Example |
Result |
|
+ |
Addition |
5 + 3 |
8 |
|
- |
Subtraction |
5 - 3 |
2 |
|
* |
Multiplication |
5 * 3 |
15 |
|
/ |
Division |
10 / 3 |
3.333... |
|
// |
Floor Division |
10 // 3 |
3 |
|
% |
Modulus |
10 % 3 |
1 |
|
** |
Power / Exponent |
2 ** 3 |
8 |
Let's understand each one properly.
Addition, Subtraction, Multiplication — Simple
a = 10 b = 3
print(a + b) # 13 print(a - b) # 7 print(a * b) # 30
Nothing surprising here. Works exactly like normal math.
Division / — Always Returns Float
print(10 / 2) # 5.0 (not 5, notice the .0) print(7 / 2) # 3.5 print(10 / 3) # 3.3333333333333335
Regular division always returns a float even if the answer is a whole number. That's why 10 / 2 gives 5.0 not 5.
Floor Division // — Removes the Decimal
print(10 // 3) # 3 (3.33... becomes 3, decimal removed) print(7 // 2) # 3 (3.5 becomes 3) print(15 // 4) # 3 (3.75 becomes 3)
Floor division divides and then rounds down to the nearest whole number. Decimal part is just thrown away.
Modulus % — Gives the Remainder
This one confuses beginners at first but it's very useful:
print(10 % 3) # 1 (10 divided by 3 = 3, remainder is 1) print(15 % 4) # 3 (15 divided by 4 = 3, remainder is 3) print(10 % 2) # 0 (10 divided by 2 = 5, remainder is 0)
Think of it like this — when you divide 10 by 3:
- 3 goes into 10 exactly 3 times (that's 9)
- What's left over is 1
- So
10 % 3 = 1
Most common use case: Checking if a number is even or odd:
number = 7 print(number % 2) # 1 — odd (remainder is 1)
number = 8 print(number % 2) # 0 — even (remainder is 0)
If number % 2 is 0 → even. If it's 1 → odd. You'll use this a LOT in future.
Power ** — Exponents
print(2 ** 3) # 8 (2 * 2 * 2) print(5 ** 2) # 25 (5 * 5) print(3 ** 4) # 81 (3 * 3 * 3 * 3) print(9 ** 0.5) # 3.0 (square root of 9)
Math with Variables
You'll almost never do math with raw numbers. You'll use variables:
price = 500 quantity = 3 discount = 50
total = price * quantity final_price = total - discount
print(f"Price per item: {price}") print(f"Quantity: {quantity}") print(f"Total before discount: {total}") print(f"Discount: {discount}") print(f"Final price: {final_price}")
Output:
Price per item: 500
Quantity: 3
Total before discount: 1500
Discount: 50
Final price: 1450
Shorthand Operators
These are shortcuts to update a variable's value:
score = 10
score = score + 5 # normal way score += 5 # shorthand — same thing
score = score - 3 score -= 3 # shorthand
score = score * 2 score *= 2 # shorthand
score = score / 2 score /= 2 # shorthand
Full example:
score = 0 print(f"Start: {score}")
score += 10 print(f"After +10: {score}")
score += 5 print(f"After +5: {score}")
score -= 3 print(f"After -3: {score}")
score *= 2 print(f"After *2: {score}")
Output:
Start: 0
After +10: 10
After +5: 15
After -3: 12
After *2: 24
Order of Operations (BODMAS)
Python follows the same math rules you learned in school — BODMAS/PEMDAS:
- Brackets
() - Exponents
** - Multiplication
*, Division/, Floor Division//, Modulus% - Addition
+, Subtraction-
print(2 + 3 * 4) # 14 (multiplication first, then addition) print((2 + 3) * 4) # 20 (brackets first) print(10 - 2 + 3) # 11 (left to right) print(2 ** 3 + 1) # 9 (exponent first, then addition)
When in doubt — use brackets to make your intention clear:
result = (price * quantity) - discount # clear and readable
Type Conversion in Math
Sometimes you'll have a number stored as a string and need to do math with it. Direct math won't work:
a = "10" # this is a string, not a number b = 5
print(a + b) # ERROR! can't add string and number
You need to convert it first:
a = "10" b = 5
a = int(a) # convert string to integer print(a + b) # 15 — works now!
Conversion functions:
int()— converts to integerfloat()— converts to floatstr()— converts to string
print(int("25")) # 25 print(float("3.14")) # 3.14 print(str(100)) # "100" print(int(9.99)) # 9 (decimal part is cut off, not rounded)
Real World Example — Simple Bill Calculator
item1 = 150 item2 = 250 item3 = 100
subtotal = item1 + item2 + item3 tax = subtotal * 0.18 # 18% GST total = subtotal + tax
print(f"Item 1: Rs.{item1}") print(f"Item 2: Rs.{item2}") print(f"Item 3: Rs.{item3}") print(f"Subtotal: Rs.{subtotal}") print(f"GST (18%): Rs.{tax}") print(f"Total Bill: Rs.{total}")
Output:
Item 1: Rs.150
Item 2: Rs.250
Item 3: Rs.100
Subtotal: Rs.500
GST (18%): Rs.90.0
Total Bill: Rs.590.0
Exercise 🏋️
Write a program that:
- Stores two numbers in variables
a = 17andb = 5 - Prints the result of all 7 operations on them (addition, subtraction, multiplication, division, floor division, modulus, power)
- Also prints whether
ais even or odd using modulus operator
Expected output format:
a = 17, b = 5
Addition: 22
Subtraction: 12
Multiplication: 85
Division: 3.4
Floor Division: 3
Modulus (Remainder): 2
Power: 1419857
Is a even? False (hint: use a % 2 == 0)
Don't worry about the last line for now — we'll properly learn == in the next step. Just try your best!
No comments:
Post a Comment