Cast
Part of the Fundamentals section of Coddy's Python journey — lesson 27 of 77.
To convert the input to a different type, we need to cast.
To cast a string to an int (a whole number), we will write:
var = input()
var = int(var)Or in one line,
var = int(input())If the input is a number, i.e. 5, 4, 54 then var will hold a number. If the input contains an invalid number: 5ab, bb, akt, etc. then the program will fail.
Here is a table that shows how to cast to different types:
| Cast | Explanation |
| int() | Convert to a whole number |
| float() | Convert to a real number |
| bool() | Convert to a boolean |
| str() | Convert to a string |
It is important to use the right type because it can affect the output.
Adding two strings will result in:
"5" + "5" = "55"
Adding two numbers will result in:
5 + 5 = 10
Challenge
BeginnerIn this challenge, you'll work with multiple inputs and perform calculations.
How to receive multiple inputs:
var1 = input() # First input
var2 = input() # Second inputYour task:
- Read the first number from input and store it in a variable
- Read the second number from input and store it in another variable
- Convert both variables to float type (for decimal numbers)
- Calculate the multiplication of these two numbers
- Print the result
Example:
If the inputs are 2 and 4.5, your program should output 9.0
Remember: Each test case contains exactly two inputs, one after the other.
Cheat sheet
Casting in Python:
# Convert string to int
var = int(input())
# Convert string to float
var = float(input())
# Convert to boolean
var = bool(input())
# Convert to string
var = str(input())Important: Adding strings concatenates them, while adding numbers performs arithmetic:
"5" + "5" = "55" # String concatenation
5 + 5 = 10 # Numeric additionMultiple inputs:
var1 = input()
var2 = input()Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2