Lesson 3 of 6 · Python

Data types and user input

Programs become interactive when people can provide information. Learn the basic Python data types, collect input with input() and convert text into numbers before doing calculations.

The four basic data types

str stores text, int stores whole numbers, float stores decimal numbers and bool stores either True or False. These types affect which operations are valid.

Use type(value) to inspect a value while learning. For example, type(12) returns int, while type("12") returns str. They look similar on screen but behave differently.

Collect information with input()

The input() function pauses the program and waits for the user to type something. It always returns the entered value as a string, even when the person types digits.

That means age = input("Age: ") stores text. To calculate with that value, convert it first with int(). Use float() when decimal values are allowed.

Convert only when it makes sense

Type conversion changes a value from one type to another. int("20") works because the text contains a whole number. int("twenty") fails because the text cannot be interpreted as an integer.

Do not convert every input blindly in a real application. Validate user input and handle invalid values before relying on them. This lesson focuses on the normal, valid-input path.

main.py
name = input("Enter your name: ")
age = int(input("Enter your age: "))

print("Hello", name)
print("Next year you will be", age + 1)
types.py
price = 49.50
quantity = 3
in_stock = True

total = price * quantity
print(type(price))
print("Bill:", total)
print("Available:", in_stock)

Try it yourself

The code examples above are for reference. Copy the relevant example into the editor, press Run, then change it and run it again.

Code Campus
Your turn

Ask the user for the price of one item and how many items they want. Convert both values to numbers and print the total bill.

Show a hint
price = float(input("Price: "))
quantity = int(input("Quantity: "))
print("Total:", price * quantity)

#CodeCampus

Code Campus