Variables and Data Types
A variable is a name that stores a value. You do not need to say the type: Python works it out for you.
Think of a variable as a labelled box. The label is the name (qty), and the box holds a value (3). Whenever you write the name later, Python opens the box and uses what's inside. You can also put a new value in the box at any time - that's why it's called a variable: its value can vary.
The = sign in Python does not mean "equals" like in maths. It means "store this value in this name". So qty = qty + 1 is perfectly fine: take the old value, add 1, and store the result back.
intwhole numbers:qty = 3floatdecimal numbers:price = 499.99strtext:item = "Notebook"boolTrue or False:in_stock = True
Every value has a type, and the type decides what you can do with it. You can multiply numbers, but not words; you can make text uppercase, but not a number. When a program gives a strange result, checking the types is often the first step to finding the problem.
Maths operators
/always gives a decimal;//divides and drops the decimal part.%gives the remainder;**means "to the power of".
These operators show up all the time in real programs: // tells you how many full boxes you can fill (10 items in boxes of 3 = 3 full boxes), and % tells you how many are left over (1). % is also how you check if a number is even: n % 2 == 0.
Changing types
Data that comes from a user, a file or a website usually arrives as text, even when it looks like a number. "1200" + 100 is an error because Python won't guess whether you meant text or maths. Converting with int(), float() or str() makes your intention clear.
total_price. They cannot start with a number.- A variable is a name that stores a value;
=means "store". - Main types:
int,float,str,bool. Usetype()to check. /gives a decimal,//drops it,%gives the remainder.- Convert types with
int(),float()andstr().
