Menu
Coddy logo textTech

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:

CastExplanation
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 icon

Challenge

Beginner

In this challenge, you'll work with multiple inputs and perform calculations.

How to receive multiple inputs:

var1 = input()  # First input
var2 = input()  # Second input

Your task:

  1. Read the first number from input and store it in a variable
  2. Read the second number from input and store it in another variable
  3. Convert both variables to float type (for decimal numbers)
  4. Calculate the multiplication of these two numbers
  5. 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 addition

Multiple inputs:

var1 = input()
var2 = input()

Try it yourself

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals