Python from zero: a value has a type
Every Python value has a type. name is a str, cents is an int, and ready is a bool. The program prints latte $4.50 ready, then str int bool.
Zoe is one of GoByte's characters. This post was drafted by AI agents in Zoe's voice, then fact checked, run and edited by the GoByte team.
Python still has types. You do not write them in front of the name. The value carries the type, and type reports it. A cup label needs three values. name is a str, the drink. cents is an int, the price as a whole number of cents. ready is a bool, whether you can hand the drink over. You can add ints. You cannot add a string to a bool.
The value carries the type#
Python does not store the type on the name. The name is a binding to an object, and the object knows its type. cents = 450 binds cents to an int object. A later cents = "latte" rebinds the name. It does not convert the int. type(cents).__name__ asks the object what it is. True is a bool, and bool is a subtype of int, which is why a bool can surprise you in arithmetic. This program prints the label a cup would carry, then the type of each value, so you can see both.
- namestrlatte
- centsint450
- readyboolTrue
name = "latte"
cents = 450
ready = True
status = "ready" if ready else "sold out"
print(f"{name} ${cents // 100}.{cents % 100:02d} {status}")
print(type(name).__name__, type(cents).__name__, type(ready).__name__)
latte $4.50 ready
str int bool
The value decides the type#
name = "latte" stores a str. cents = 450 stores an int, 450 cents, which is $4.50. The int never holds the decimal point. cents // 100 is the dollars. cents % 100 is the leftover cents, and :02d prints them as two digits so 50 stays 50 and 5 would become 05. ready chooses the status word. The second print writes the type names, so you do not have to guess them.
A name can later point at a different type: cents = "450" is allowed, and cents is then a str. That freedom is why it helps to print the type while you are learning a function. If a result surprises you, print type(result).__name__ next to it.
Operators follow the type#
cents + 50 works while cents is an int. name + "!" joins text. name + cents raises TypeError, because a string and an int are not added. The error names both types. Read it. The label builds the dollars in the f-string, where you can see the conversion. The next lesson puts the name and the cents on one object and calls a method that returns the same kind of label.
Your product here? Partner with us
Back to topDiscussion
No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines
Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.