Variables and Types
Python assigns a type to every value. The type determines which operations are valid on that value and how those operations behave. A variable is a name bound to a value; the name itself carries no type, and rebinding a name to a value of a different type is permitted.
The four built-in types used most often are int for whole numbers, float
for real numbers, str for text, and bool for truth values.
<class 'str'> <class 'int'> <class 'float'> <class 'bool'>
Conversion between types
The type names double as conversion functions. int("120") produces the
integer 120; str(120) produces the string "120". Conversion is explicit in
Python: adding a string to an integer raises TypeError rather than guessing
what was intended.
121 1.02 42 reads
Conversion fails when the text does not represent a valid value of the target
type. int("twelve") raises ValueError, as does int("3.5"), because int accepts
only whole-number string representations. float("3.5") succeeds. This asymmetry
matters when validating input read from a file, where both forms occur.
120 -> 120 0.51 -> ValueError: invalid literal for int() with base 10: '0.51' twelve -> ValueError: invalid literal for int() with base 10: 'twelve'
Numeric operators
Division with / always produces a float, even when the operands divide
exactly: 6 / 3 is 2.0, not 2. Floor division with // discards the
fractional part and returns an integer when both operands are integers. The
modulo operator % returns the remainder.
3.5 3 1 2.0 <class 'float'>
These three operators together handle position arithmetic. A coding-sequence position divided by three gives the codon number; the remainder gives the offset within that codon. Note that the results below are zero-based, which is the convention Python uses throughout.
position 0: codon 0, offset 0 position 1: codon 0, offset 1 position 2: codon 0, offset 2 position 3: codon 1, offset 0 position 4: codon 1, offset 1 position 5: codon 1, offset 2
Floating-point precision
float values are stored in binary and cannot represent every decimal
fraction exactly. 0.1 + 0.2 evaluates to a value marginally greater than
0.3, so comparing floats with == is unreliable. Compare with a tolerance
instead, or round both sides to a fixed number of decimal places.
0.30000000000000004 False True
Task
Write describe(value). It receives a string and must return:
"int <n>"if the string converts to a whole number."float <f>"if it converts to a real number but not a whole one."str <value>"otherwise.
Attempt the int conversion before the float conversion, because int("3")
and float("3") both succeed and the integer classification takes precedence.
Test cases · 3
| # | via | input | expected stdout |
|---|---|---|---|
| 1 | stdin | 120 | int 120 |
| 2 | stdin | 0.51 | float 0.51 |
| 3 | stdin | TP53 | str TP53 |
Hints · 2
01Hint
int('3.5') raises ValueError, but float('3.5') does not.
02Hint
Wrap each conversion in its own try/except ValueError block.