These are the notes for Data Analytics with Python, episode 4. You will learn why variables exist, how assignment works, the rules for naming variables, Python's five basic data types (int, float, str, bool, None) and type(), why input() always gives text and how to convert types with int(), float() and str(), all seven arithmetic operators, why 0.1 + 0.2 is not 0.3, comparison operators, the logical operators and, or and not, and f-strings for clean output. Every term is defined the first time it appears and collected in the Glossary. Every program below was run for real (Python 3.13); outputs are unedited.
The problem: the same number typed in six places
Ramesh sells chai at Rs 12 a cup. His bill for three days, with the numbers typed straight in. A line starting with # is a comment: a note for humans that Python ignores.
# Ramesh's bill: 12 rupees a cup
print(12 * 320) # Monday
print(12 * 280) # Tuesday
print(12 * 410) # Wednesday
print(12 * 320 + 12 * 280 + 12 * 410)
3840
3360
4920
12120
The price goes up to Rs 15. We change 12 to 15 everywhere, but miss Wednesday's line:
# Price is now 15 rupees a cup
print(15 * 320) # Monday
print(15 * 280) # Tuesday
print(12 * 410) # Wednesday (missed!)
print(15 * 320 + 15 * 280 + 15 * 410)
4800
4200
4920
15150
No error, but a wrong number. Wednesday still uses the old price.
Why: the same fact (the price) lived in six places. Changing it meant finding every copy. Fix: write the fact once, give it a name, and use the name.
Variables and assignment
| Kitchen | Python | Meaning |
|---|---|---|
| A jar labelled SUGAR | Variable | A name that points to a value stored in memory |
| Putting sugar in the jar | Assignment (=) |
Store the value on the right under the name on the left |
| Emptying and refilling the jar | Reassignment | Giving an existing name a new value |
Read price = 15 as "price gets 15". In Python, = does not mean "is equal to" (that is ==, below).
price = 15
mon = 320
tue = 280
wed = 410
print(price * mon)
print(price * tue)
print(price * wed)
print(price * (mon + tue + wed))
4800
4200
6150
15150
Every line now uses the new price, because the price lives in one place. Reassigning price = 18 later would update every calculation.
Rules for variable names
- Only letters, digits and
_(underscore). No spaces. - Can't start with a digit:
2cupsis wrong,cups2is fine. - Case-sensitive:
cupsandCupsare different names. - Can't be a keyword (a word Python reserves for itself), such as
if,for,True,None. - Style: snake_case (small letters, words joined by underscores):
cups_sold,avg_price.
Breaking the rules gives real errors. Syntax means the grammar of the language.
cups sold = 5
File "main.py", line 1
cups sold = 5
^^^^
SyntaxError: invalid syntax
2cups = 5
File "main.py", line 1
2cups = 5
^
SyntaxError: invalid decimal literal
cups = 320
print(Cups)
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(Cups)
^^^^
NameError: name 'Cups' is not defined. Did you mean: 'cups'?
A traceback is Python's error report: where the error happened, then the error's type and message on the last line.
Data types
Not every value is the same kind. Cups are whole numbers, the price has a decimal point, the day is text, "rainy?" is yes/no, and Saturday (Ramesh was sick) has no value at all. The kind of a value is its data type.
| Type | Meaning | Examples | Used for |
|---|---|---|---|
int (integer) |
A whole number, no decimal point | 320, -5, 0 |
Counts, quantities, IDs |
float |
A number with a decimal point | 12.5, 0.08, 3.0 |
Prices, averages, rates |
str (string) |
Text: characters inside quotes ('...' or "...") |
"Mon", 'Andheri' |
Names, labels, categories |
bool (Boolean) |
Only True or False (capital letters) |
rainy = True |
Yes/no flags, results of comparisons |
None |
No value at all | sat_cups = None |
"Nothing recorded", like an empty cell |
bool is named after the mathematician George Boole. A function is a named piece of code that does a job when you call it with brackets, like print(...). The built-in function type() tells you a value's type:
cups = 320
price = 12.5
day = "Mon"
rainy = False
sat_cups = None
print(type(cups))
print(type(price))
print(type(day))
print(type(rainy))
print(type(sat_cups))
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'NoneType'>
Here class just means type.
input() always gives text
input("question") shows a question and waits for the user to type an answer. The answer is always a string, even if it's digits.
cups = input("Cups sold today: ") # the user types 320
print(type(cups))
print(cups * 3)
print(cups + 10)
Cups sold today: <class 'str'>
320320320
Traceback (most recent call last):
File "main.py", line 4, in <module>
print(cups + 10)
~~~~~^~~~
TypeError: can only concatenate str (not "int") to str
"320" * 3repeats the text three times:320320320(no error, just a silently wrong number)."320" + 10crashes. Concatenate means join text end to end; Python won't join text and a number.
Type conversion: int(), float(), str()
Type conversion (also called casting) turns a value of one type into another.
| Call | Result |
|---|---|
int("320") |
320 (int) |
float("12.5") |
12.5 (float) |
str(320) |
"320" (str) |
int(12.9) |
12 (drops the decimals, no rounding) |
int(" 42 ") |
42 (spaces around are ignored) |
cups = int(input("Cups sold today: ")) # types 320
price = float(input("Price per cup: ")) # types 12.5
print(cups + 10)
print(cups * price)
Cups sold today: Price per cup: 330
4000.0
An int times a float gives a float (4000.0). (The input questions print on the same line because the typed answers aren't shown in the output.)
Conversion has limits:
print(int("12.5"))
ValueError: invalid literal for int() with base 10: '12.5'
print(int("N/A"))
ValueError: invalid literal for int() with base 10: 'N/A'
int() only accepts text that looks like a whole number. Use float() for decimals, and clean values like "N/A" (not available) first. Data cleaning gets its own chapter later in the course.
Arithmetic operators
An operator is a symbol that does something to values; the values are its operands (in 3 + 4, + is the operator, 3 and 4 the operands).
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
addition | 320 + 30 |
350 |
- |
subtraction | 320 - 20 |
300 |
* |
multiplication | 320 * 12 |
3840 |
/ |
division (always a float) | 320 / 2 |
160.0 |
// |
floor division (divide, drop the decimals) | 320 // 12 |
26 |
% |
remainder (modulo) | 320 % 12 |
8 |
** |
power (exponent) | 2 ** 10 |
1024 |
cups = 320
print(cups + 30)
print(cups - 20)
print(cups * 12)
print(cups / 2)
print(cups // 12) # full trays of 12
print(cups % 12) # cups left over
print(2 ** 10)
print(1000 * 1.1 ** 12)
350
300
3840
160.0
26
8
1024
3138.428376721003
- Ramesh carries chai on trays of 12:
320 // 12= 26 full trays,320 % 12= 8 cups left over. 1000 * 1.1 ** 12: 1,000 cups growing 10% a month for 12 months is about 3,138. Growth that builds on itself is compounding.- For negative numbers,
//rounds down (towards minus infinity):-7 // 2is-4, not-3.
Two surprises: float precision and precedence
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(round(0.1 + 0.2, 2))
print(2 + 3 * 4)
print((2 + 3) * 4)
0.30000000000000004
False
0.3
14
20
- Computers store floats in binary (base 2). As Python's tutorial explains, "the decimal value 0.1 cannot be represented exactly as a base 2 fraction", so a tiny representation error appears. It's not a bug in Python.
round(x, 2)rounds to 2 decimal places for display. For money in accounting, Python'sdecimalmodule does exact decimal arithmetic:Decimal("0.1") + Decimal("0.2") == Decimal("0.3")isTrue.- Never compare floats with
==; compare the rounded values, or check that the difference is tiny. - Operator precedence is the order operations happen:
**first, then*,/,//,%, then+and-. Brackets go first of all.2 + 3 * 4is 14;(2 + 3) * 4is 20.
Comparison operators
A comparison asks a yes/no question and always gives a bool.
| Operator | Meaning | Example (cups = 320) |
Result |
|---|---|---|---|
== |
equal to | cups == 300 |
False |
!= |
not equal to | cups != 300 |
True |
> |
greater than | cups > 300 |
True |
< |
less than | cups < 100 |
False |
>= |
greater than or equal to | cups >= 320 |
True |
<= |
less than or equal to | cups <= 320 |
True |
cups = 320
target = 300
rainy = True
print(cups > target)
print(cups == 300)
print(cups != 300)
print(cups >= 320, cups < 100)
True
False
True
True False
The classic mistake: one = where you meant two.
cups = 320
print(cups = 300)
TypeError: print() got an unexpected keyword argument 'cups'
With one = inside a function call, Python thinks you are passing a setting (a keyword argument) named cups to print. = stores; == compares.
Logical operators: and, or, not
| Ramesh says | Operator | True when |
|---|---|---|
| Bonus if it rained and we sold 300+ | and |
both sides are True |
| Samosa treat if it rained or it's Sunday | or |
at least one side is True |
| "Not a rainy day" | not |
flips True ↔ False |
cups = 320
rainy = True
print(rainy and cups > 300)
print(rainy or cups > 1000)
print(not rainy)
True
True
False
| a | b | a and b | a or b | not a |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
Comparisons run before not, and and or, so rainy and cups > 300 means rainy and (cups > 300). You'll use these operators in every pandas filter (where they become &, | and ~).
f-strings
Joining text and a number with + fails:
revenue = 4000
print("Revenue: " + revenue)
TypeError: can only concatenate str (not "int") to str
An f-string (formatted string literal) is a string with f before the quotes. Each pair of curly braces {} is a placeholder: Python evaluates the expression inside when the line runs and inserts its value as text. f-strings arrived in Python 3.6 (PEP 498). After a colon you can add a format specification:
| Spec | Meaning | Example | Result |
|---|---|---|---|
:.2f |
2 decimal places | f"{12.5:.2f}" |
12.50 |
:, |
thousands separators | f"{1234567:,}" |
1,234,567 |
:,.2f |
both | f"{3500:,.2f}" |
3,500.00 |
:.0% |
as a percentage | f"{0.34:.0%}" |
34% |
day = "Mon"
cups = 320
price = 12.5
revenue = cups * price
print("Revenue: " + str(revenue))
print(f"{day}: {cups} cups, revenue Rs {revenue}")
print(f"Average price: {revenue / cups:.2f}")
print(f"Big number: {1234567:,}")
Revenue: 4000.0
Mon: 320 cups, revenue Rs 4000.0
Average price: 12.50
Big number: 1,234,567
print() can also take several values; it puts a space between them by default, and sep= changes that: print("Mon", 320, "cups", sep=" | ") prints Mon | 320 | cups.
Mini project: Ramesh's day report
day = input("Day: ")
cups = int(input("Cups sold: "))
price = float(input("Price per cup: "))
rainy = input("Rainy? (yes/no): ") == "yes"
revenue = cups * price
good_day = cups >= 300 and not rainy
print(f"--- {day} report ---")
print(f"Revenue: Rs {revenue:,.2f}")
print(f"Trays of 12: {cups // 12}, left over: {cups % 12}")
print(f"Good day? {good_day}")
Input typed: Tue, 280, 12.5, yes.
Day: Cups sold: Price per cup: Rainy? (yes/no): --- Tue report ---
Revenue: Rs 3,500.00
Trays of 12: 23, left over: 4
Good day? False
input(...) == "yes" turns the answer into a bool. Every concept from this episode appears in these ten lines.
Common mistakes
| Code | Real error | Why | Fix |
|---|---|---|---|
print("Revenue: " + revenue) |
TypeError: can only concatenate str (not "int") to str |
Text and a number can't be joined | f"Revenue: {revenue}" or str(revenue) |
cups = input(); cups * 3 |
(no error: 320320320) |
input() returns a string |
int(input()) |
int("12.5") |
ValueError: invalid literal for int() with base 10: '12.5' |
int() needs a whole-number string |
float("12.5") |
int("N/A") |
ValueError: invalid literal for int() with base 10: 'N/A' |
Not a number at all | Clean or skip missing values first |
print(Cups) |
NameError: name 'Cups' is not defined. Did you mean: 'cups'? |
Names are case-sensitive | Use the exact name |
cups sold = 5 |
SyntaxError: invalid syntax |
Spaces aren't allowed in names | cups_sold = 5 |
2cups = 5 |
SyntaxError: invalid decimal literal |
Names can't start with a digit | cups2 = 5 |
print(cups = 300) |
TypeError: print() got an unexpected keyword argument 'cups' |
= stores, == compares |
print(cups == 300) |
0.1 + 0.2 == 0.3 |
(no error: False) |
Binary floats aren't exact | round(...) or decimal |
x = None; x + 5 |
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' |
No value to add | Handle missing values first |
Practice
1. Predict, then run: 7 // 2, 7 % 2, -7 // 2, 2 ** 0.5, 0.1 * 3 == 0.3.
Solution
3, 1, -4 (floor division rounds down, towards minus infinity), 1.4142135623730951 (a square root), False (0.1 * 3 is 0.30000000000000004).
2. Ask for a price with input(), add 18% GST, and print the total with 2 decimals.
Solution
price = float(input("Price: "))
total = price * 1.18
print(f"Total with GST: Rs {total:,.2f}")
For 250 this prints Total with GST: Rs 295.00.
3. What is the type of each: "320", 320, 320.0, 320 > 300, None?
Solution
str, int, float, bool, NoneType.
4. Fix this program so it prints Total: 660: a = input() (user types 320), b = input() (user types 340), print("Total: " + a + b).
Solution
a + b joins the strings into "320340". Convert and use an f-string: a = int(input()), b = int(input()), print(f"Total: {a + b}").
5. A good day for Ramesh is "at least 300 cups, or a Sunday with at least 250 cups". Write it as one bool expression with cups and day.
Solution
good = cups >= 300 or (day == "Sun" and cups >= 250). The brackets make the intent clear (and would run before or anyway).
Quick quiz
cups = input("Cups: ") # user types 50
print(cups * 2)
A. 100 B. 5050 C. TypeError D. 50 * 2
Answer
B. input() returns the string "50", and a string times 2 repeats it: 5050.
Interview questions
- What's the difference between
=and==?=assigns (stores a value under a name);==compares two values and gives abool. - What are Python's basic data types?
int,float,str,boolandNoneType(None); check withtype(). - What does
input()return? Always astr; convert withint()orfloat()for maths. /vs//vs%?/is true division (always a float),//is floor division (rounds down),%is the remainder.- Why is
0.1 + 0.2 != 0.3? Floats are binary fractions; 0.1 can't be stored exactly. Useround,math.isclose, ordecimalfor money. - What is an f-string? A string prefixed with
fwhose{}placeholders are evaluated at run time, with optional format specs like:.2f.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Comment | A note for humans that Python ignores, after # |
# Monday |
| Variable | A name that points to a value in memory | price |
| Assignment | Storing a value under a name with = |
price = 15 |
| Reassignment | Giving an existing variable a new value | price = 18 |
| Keyword | A word Python reserves for itself | if, for, True |
| snake_case | Naming style: small letters joined by _ |
cups_sold |
| Syntax | The grammar rules of a language | — |
| SyntaxError | Python's error for code that breaks the grammar | cups sold = 5 |
| NameError | Error for a name that doesn't exist | print(Cups) |
| Traceback | Python's error report: where, then what went wrong | Last line: NameError: ... |
| Data type | The kind of a value, which decides what you can do with it | int, str |
| int | A whole number | 320 |
| float | A number with a decimal point | 12.5 |
| str (string) | Text inside quotes | "Mon" |
| bool | True or False |
rainy = True |
| None / NoneType | "No value"; its type is NoneType |
sat_cups = None |
| Function | A named piece of code you call with brackets | print(), type() |
| type() | Built-in function that returns a value's type | type(3.0) → float |
| print() | Built-in function that shows values as text | print("hi", 5) |
| input() | Built-in function that asks the user and returns a str |
input("Day: ") |
| Type conversion (casting) | Turning a value into another type | int("320") |
| int(), float(), str() | Conversion functions | str(320) → "320" |
| Concatenate | Join text end to end with + |
"chai" + "wala" |
| TypeError | Error when an operation gets the wrong type | "320" + 10 |
| ValueError | Error when a value has the right type but an impossible content | int("N/A") |
| Operator | A symbol that does something to values | +, ==, and |
| Operand | A value an operator works on | 3 and 4 in 3 + 4 |
| Arithmetic operators | + - * / // % ** |
320 // 12 |
Floor division // |
Divide and round down to a whole number | 320 // 12 → 26 |
Modulo % |
The remainder after division | 320 % 12 → 8 |
Power ** |
Raise to a power | 2 ** 10 → 1024 |
| Compounding | Growth that builds on previous growth | 1000 * 1.1 ** 12 |
| Representation error | The tiny error when a decimal can't be stored exactly in binary | 0.1 + 0.2 |
| round() | Round a number to some decimal places | round(3.14159, 2) → 3.14 |
| decimal module | Exact decimal arithmetic, for money | Decimal("0.1") |
| Operator precedence | The order operations run in | 2 + 3 * 4 → 14 |
| Comparison operators | == != > < >= <=; give a bool |
cups > 300 |
| Keyword argument | A named setting passed to a function | print(..., sep="-") |
| Logical operators | and, or, not; combine or flip bools |
rainy and cups > 300 |
| f-string | A string with f whose {} are filled in at run time |
f"{day}: {cups}" |
| Placeholder | The {} in an f-string |
{revenue} |
| Format specification | Rules after : inside {} |
{x:.2f}, {x:,} |
Summary
- A variable is a name for a value;
=assigns. Write each fact once. - Names: letters, digits,
_; no leading digit; case-sensitive; use snake_case. - Five basic types: int, float, str, bool, None; check with
type(). input()always returns a str; convert withint(),float(),str().- Arithmetic:
+ - * / // % **;/always gives a float; brackets beat precedence; floats are approximate. - Comparisons give bools; combine them with and, or, not.
- f-strings with
{}and format specs make clean reports. - Next episode: Python for data, part 2: lists, tuples, dicts and sets.