Casting to the right type
Input always gives back a string. A string that looks like a number is still only text. If you use + on two strings, Python joins them, so "12" + "15" makes "1215". To calculate, you must cast the text to a number first. Wrap the input command in int() for whole numbers, or in float() for real numbers. Use str() to turn a number into text. If the text cannot be a number, such as abc, Python stops with an error. Casting is important because Python does not guess the type.
1mon = input("Pages read on Monday? ") 2tue = input("Pages read on Tuesday? ") 3total = mon + tue 4print("Total pages:", total)
Total pages: 1215
1mon = int(input("Pages read on Monday? ")) 2tue = int(input("Pages read on Tuesday? ")) 3total = mon + tue 4print("Total pages:", total)
Total pages: 27
1km = float(input("Distance in km? ")) 2metres = km * 1000 3print("Metres:", metres)
Metres: 2500.0
| Cast | Result | Type |
|---|---|---|
| int("12") | 12 | whole number |
| float("2.5") | 2.5 | real number |
| float("3") | 3.0 | real number |
| str(7) | '7' | text |
| int("abc") | ValueError: invalid literal for int() with base 10: 'abc' | error |
Cast cards (no computer): write the digits 5 and 3 on four small cards, two in quotation marks ("5" and "3") and two without (5 and 3). Rule 1: the plus sign on two quoted cards means ‘stick the cards side by side’. Show 53. Rule 2: on two plain cards it means ‘add’. Show 8. Rule 3: a quoted card cannot be added to a plain card: say ‘error’. Make up three more pairs for your partner to solve. Then write the cast you would need to change a quoted card into a number. If you have a computer or tablet, test the three rules in IDLE with an adult.
1start = input("Start page? ") 2end = input("End page? ") 3print(end - start)
TypeError: unsupported operand type(s) for -: 'str' and 'str'
1a = int(input("First number? ")) 2b = int(input("Second number? ")) 3print(a + b)
1packs = input("Packs of stickers? ") 2total = packs * 3 3print(total)
444