A variable is a name stuck onto a value
price = 250
currency = "rupees"
print(price)
print(currency)The = here is not the = from school maths. It is not a claim that two things are equal. It is an instruction: work out what is on the right, then attach the name on the left to it. Read it as "price gets 250".
Because it is an instruction, it happens at the moment that line runs, and it can happen again:
price = 250
price = price + 50
print(price) # 300Line two would be nonsense as an equation. As an instruction it is ordinary: take the current value of price, add 50, and re-attach the name to the result.
Names can be almost anything made of letters, digits and underscores, as long as they do not start with a digit. Use names that say what the thing is. total_marks beats tm every time you come back to the file a week later.
Everything has a type
Every value in Python is of some kind, and the kind decides what you are allowed to do with it. You can ask:
price = 250
currency = "rupees"
rate = 0.5
passed = True
print(type(price)) # <class 'int'>
print(type(currency)) # <class 'str'>
print(type(rate)) # <class 'float'>
print(type(passed)) # <class 'bool'>Four types cover most of what a beginner needs:
int— a whole number:250,-3,0float— a number with a decimal point:0.5,19.99str— text, in quotes:"rupees",'Kano'bool—TrueorFalse, with capital letters
The type changes what an operator means
This is the part worth slowing down for:
print(250 * 2) # 500
print("rupees" * 2) # rupeesrupeesThe same * did two different jobs. With numbers it multiplied. With text it repeated. Python looked at the types and chose. The same happens with +: numbers add, text joins end to end.
print(3 + 4) # 7
print("3" + "4") # 34"3" is not the number three. It is a character that happens to look like three, the way the word "three" does.
And when the types do not agree, Python refuses rather than guessing:
print("3" + 4)TypeError: can only concatenate str (not "int") to strSome languages would quietly decide you meant "34", or 7. Python decides that a wrong answer is worse than a stop. You will meet this error constantly, and it almost always means "one of these is text and you thought it was a number".
Converting on purpose
When you do want to cross the line, say so:
print(int("3") + 4) # 7
print("3" + str(4)) # 34
print(float("19.99") * 2) # 39.98int("hello") fails, and it should. int("3.7") also fails, because "3.7" is not a whole number written down; use float first.
Try this now
subtotal = 1200
tax = subtotal * 0.18
total = subtotal + tax
label = "Total: "
print(label + str(total))
print(type(total))Then remove the str(...) and read the error carefully. That error message is a friend, and lesson seven explains why.
Before you move on