Every value has a type. The types so far: int, float, and str (string). The type function reports a value's type:
print(type(42))
print(type(4.5))
print(type("42"))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
The last line matters: "42" is a string, not a number. Arithmetic on it fails or misbehaves — "42" + "1" is "421", not 43.
Three functions convert between types:
int(x) converts to a whole number: int("42") is 42.float(x) converts to a decimal number: float("19.99") is 19.99.str(x) converts to a string: str(50) is "50".count_text = "42"
count = int(count_text)
print(count + 8)
Output:
50
int fails if the text is not a whole number: int("4.5") and int("hello") are errors.
The starter code creates count_text and price_text, both strings.
count — count_text converted to an int.price — price_text converted to a float.total holding count + 8.label — total converted to a string.total and its type.Run your code to see the output, then press Submit.
import unittest
class TestTypesAndConversion(unittest.TestCase):
def test_count_is_the_int_42(self):
self.assertEqual(count, 42)
self.assertIsInstance(count, int)
def test_price_is_the_float_19_99(self):
self.assertEqual(price, 19.99)
self.assertIsInstance(price, float)
def test_total_is_50(self):
self.assertEqual(total, 50)
def test_label_is_the_string_50(self):
self.assertEqual(label, "50")
self.assertIsInstance(label, str)
count_text = "42" price_text = "19.99" count = int(count_text) price = float(price_text) total = count + 8 label = str(total) print(total) print(type(total))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.