Python Variables and Data Types
A variable is a name that refers to a value. You create one with the = sign. Python works out the type from the value, so you do not declare it.
rows = 1500 # int: a whole number
accuracy = 0.925 # float: a number with a decimal point
model = "linear" # str: text
trained = True # bool: True or False
print(rows, accuracy, model, trained)
print(type(rows), type(accuracy), type(model), type(trained))
Press Run. Then change a value and run it again.
Numbers
The usual arithmetic operators work on numbers. Division with / always returns a float. Use // for floor division and % for the remainder. ** raises to a power.
print(17 / 3) # division
print(17 // 3) # floor division
print(17 % 3) # remainder
print(2 ** 10) # power
Strings
Strings can be written with single or double quotes. + joins strings and len() returns the number of characters. An f-string puts values inside text: write f before the opening quote and put the variable in curly brackets.
name = "pandas"
print(name + " is a library")
print(len(name))
print(f"{name} has {len(name)} letters")
print(name.upper())
Converting between types
int(), float() and str() convert a value to that type. Data read from a file often arrives as text, so you will use these often.
price = "19.99"
quantity = "3"
total = float(price) * int(quantity)
print(total)
Try it
Change quantity to "three" and run the code. Python raises a ValueError, because that text cannot be read as a whole number. Reading error messages like this one is a core skill: the last line names the problem.