Python has a small set of built-in types. The four you will use constantly are
int, float, str and bool.
A variable is a name bound to a value. You do not declare a type; the value carries its own type.
gene = "TP53"
position = 7676154
frequency = 0.51
is_pathogenic = True
print(type(gene), type(position), type(frequency), type(is_pathogenic))
Checking and converting types
type() reports a type. The type names double as conversion functions.
depth = "120"
print(type(depth))
print(int(depth) + 1)
print(float("0.51") * 2)
print(str(42) + " reads")
Conversion fails if the text is not a valid number:
value = "twelve"
try:
print(int(value))
except ValueError as error:
print("could not convert:", error)
Integer and float division
/ always produces a float. // discards the remainder. % gives the
remainder.
print(7 / 2)
print(7 // 2)
print(7 % 2)
This matters for codon arithmetic: a coding position divided by 3 gives the codon number, and the remainder gives the position within the codon.
Task
Write describe(value). It receives a string, and must:
- Return
"int <n>"if the string converts to a whole number. - Return
"float <f>"if it converts to a decimal number but not a whole one. - Return
"str <value>"otherwise.
Check int before float, because int("3") succeeds and float("3") also
succeeds.
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.