Fixed values and changing types
A constant is a named value that is set once at the start and never changed while the program runs. In pseudocode we write CONSTANT SEAT_PRICE = 12. In Python the rule is to use capital letters, as in SEAT_PRICE = 12. Constants are useful because a price used in ten places can be changed in one place, the name says what the number means, and nobody types a different value by mistake. Casting changes a type. int() makes an integer, float() makes a real number, str() makes a string and bool() makes a Boolean. int(7.9) cuts off the decimal part and gives 7. bool(0) and bool("") are False, but any other number or non-empty text is True, even the text "False". Casting a word to a number, such as int("abc"), stops the program with a ValueError.
1CONSTANT SEAT_PRICE = 12 2INPUT seats 3total ← seats * SEAT_PRICE 4OUTPUT "Total: ", total
Total: 48
1SEAT_PRICE = 12 2seats = int(input("Seats? ")) 3total = seats * SEAT_PRICE 4print("Total:", total)
Total: 48
| Expression | Value | Type |
|---|---|---|
| int("12") | 12 | integer |
| int(7.9) | 7 | integer |
| float("2.5") | 2.5 | real |
| str(7) | "7" | string |
| bool(0) | False | Boolean |
| bool(5) | True | Boolean |
| bool("") | False | Boolean |
| bool("False") | True | Boolean |
1n = int(input("Number? ")) 2print(n + 1)
ValueError: invalid literal for int() with base 10: 'abc'
Constants and casts (no computer). Part 1: write a short program for a stall with a constant PRICE_PER_KG = 3 and the weights 2, 5 and 9 kilos. Work out the three totals. Then change the constant to 4 and say how many lines you must change. Part 2: make cards with eight casts, such as int("5"), float("5"), str(5), bool(0), bool("0"), bool(""), int(3.99) and bool("stop"). Write the result under each, then check with an adult or in Python. If you have a computer or tablet, run the stall program with both prices.
| Expression | Value | Type |
|---|---|---|
| int("40") | ? | ? |
| float(3) | ? | ? |
| str(25) | ? | ? |
| bool(0) | ? | ? |
| bool("stop") | ? | ? |
1a = input("First? ") 2b = input("Second? ") 3print(a * b)
TypeError: can't multiply sequence by non-int of type 'str'