Variables & data types
Computer Science · Python
Question 1 of 10
0What does this Python code print? x = 2 y = 5 x = x * y y = x * 2 print(y)
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Variables & data types explained
In Python, a variable is created the moment you give it a value with the = sign, and you do not write its type in advance. Python still has types. The common ones are int for whole numbers, float for decimal numbers, str for text and bool for True or False. The built-in type() function reports the type of any value.
Python is dynamically typed, so a name can later refer to a value of a different type, although changing types is usually confusing and best avoided. Names are case-sensitive, cannot start with a digit and cannot be reserved words such as if or for.
Converting between types is done with functions named after the target type. int("42") gives the number 42, str(42) gives the text "42" and float("3.5") gives 3.5. Converting text that is not a number, such as int("abc"), raises a ValueError. Converting a float with int() removes the decimal part rather than rounding it, so int(3.9) is 3.
x = 7
y = "7"
print(type(x), type(y))
print(x + int(y) * 2)
print(str(x) + y)
Worked example
Trace the program above.
- type(x) reports int and type(y) reports str, so the first line shows the two types.
- int(y) turns "7" into 7, then 7 * 2 = 14, and x + 14 = 21.
- str(x) gives "7", and joining it with y using + gives "77" as text.
Note that x + y on its own would raise a TypeError, because Python will not add an integer and a string.
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
What does this Python code print? x = 4 y = 1 x = x - y y = x * 2 print(y)
Medium
What does this Python code print? s = "16" n = int(s) * 9 print(n + len(s))
Hard
What does this Python code print? x = -23 y = 2 print(x % y)