Pythonbeginner 7 min
Integers, floats, strings and booleans, and how to convert between them.
The four basic types of value in Python, how to check a type with type(), and how to convert between them.
Many beginner bugs are type bugs, like trying to add a number to text. Knowing the types explains the error messages.
The everyday types:
7, -3.3.14."hello".True or False (capital first letter).type(value) tells you the type.
You can convert with int(), float(), str(). This is called casting.
Useful arithmetic: + - * / and also // (whole-number division), % (remainder) and ** (power). Note that / always gives a float.
7 / 2 is 3.5, because / always returns a float.7 // 2 drops the remainder and gives 3; 7 % 2 is that remainder, 1.7 ** 2 is seven squared, 49.type() shows int, float, str and bool.int("5") turns the text into the number 5 so adding 3 gives 8. "5" + "3" joins two strings into 53.Convert the string "42" to an integer and double it. Then try "42" + 1 and read the error.
"5" + 3 raises a TypeError. Convert first.true is not defined. Use True./ to give a whole number. Use // for that.int("abc") raises a ValueError.int, float, str, bool.type() checks a type; int(), float(), str() convert./ returns a float, // returns a whole number.Next: making decisions.
a = 7
b = 2
print(a / b) # 3.5
print(a // b) # 3
print(a % b) # 1
print(a ** b) # 49
print(type(a)) # <class 'int'>
print(type(3.5)) # <class 'float'>
print(type("hi")) # <class 'str'>
print(type(True)) # <class 'bool'>
text = "5"
print(int(text) + 3) # 8
print(text + "3") # 53