← Back to course

User Input and Type Conversion

User Input and Type Conversion

Welcome back.

In the previous lesson, you learned about variables and data types.

You learned how to store values like:

name = "Anna"
age = 25
price = 19.99
is_student = True

Very good.

Your programs can now remember values.

But there is still one problem.

The values are written directly inside the code.

That means the program always uses the same data.

Useful.

But not very interactive.

A real program often needs to ask the user for information.

For example:

What is your name?
How old are you?
How many products do you want?
What is the price?

This is where input() enters the story.

input() lets your program ask questions.

The user answers.

Python stores the answer.

Then your program can use it.

Suddenly your program is not just talking.

It is listening.

A dangerous upgrade.

But useful.

What You Will Learn

In this lesson, you will learn:

By the end of this lesson, your programs will be able to talk with users.

Not intelligently.

Not like a chatbot.

But enough to ask a question and use the answer.

Small interaction.

Big step.

Very Python.

What Is input()?

input() is a Python function that asks the user for information.

Example:

name = input("What is your name? ")

print(f"Hello, {name}!")

When you run the program, Python shows:

What is your name?

Then the user types something.

For example:

Anna

Then Python stores "Anna" inside the variable name.

After that, the program prints:

Hello, Anna!

Very nice.

Very polite.

The program asked.

The user answered.

Python remembered.

Nobody cried.

Excellent progress.

Your First input() Program

Create a file:

input_example.py

Write:

name = input("What is your name? ")

print(f"Hello, {name}!")

Run it:

python input_example.py

or:

python3 input_example.py

You will see:

What is your name?

Type your name and press Enter.

Example:

Viktor

Then the program prints:

Hello, Viktor!

Congratulations.

Your program is now interactive.

It asks.

It waits.

It responds.

Very simple.

Very important.

Very “my program has learned basic manners”.

The Text Inside input()

The text inside input() is called a prompt.

Example:

input("What is your name? ")

The prompt is what the user sees.

Good prompt:

name = input("What is your name? ")

Bad prompt:

name = input()

This works, but the user sees nothing.

The program just waits.

The user may think the program is broken.

And honestly, fair.

Always write a clear prompt.

Computers do not explain themselves naturally.

You must help them.

Like tiny confused metal children.

Store Input in a Variable

Usually, you store input in a variable.

Example:

city = input("Where do you live? ")

print(f"You live in {city}.")

If the user types:

Rome

Output:

You live in Rome.

The flow is:

Ask a question.
User types an answer.
Store answer in a variable.
Use the variable.

This pattern is very common.

You will use it again and again.

Like making coffee.

But with more syntax.

Multiple Questions

You can ask more than one question.

Example:

name = input("What is your name? ")
city = input("Where do you live? ")
language = input("What programming language are you learning? ")

print(f"Hello, {name}!")
print(f"You live in {city}.")
print(f"You are learning {language}.")

Example interaction:

What is your name? Anna
Where do you live? Rome
What programming language are you learning? Python

Output:

Hello, Anna!
You live in Rome.
You are learning Python.

Now your program collects several pieces of information.

This is already useful.

Small form.

Small database feeling.

But without the database.

For now.

input() Always Returns a String

Very important detail:

input() always returns a string.

Even if the user types a number.

Example:

age = input("How old are you? ")

print(type(age))

If the user types:

25

Python stores it as:

"25"

Not:

25

Output:

<class 'str'>

This is important.

Very important.

Python sees user input as text.

Because from the keyboard, everything arrives as text.

Python does not guess.

Python does not say:

This looks like a number, so I will be creative.

No.

Python says:

Text.
Definitely text.
Good luck.

Very strict.

Very honest.

The Problem with Numbers from input()

Try this:

age = input("How old are you? ")

next_year = age + 1

print(next_year)

If the user types:

25

You might expect:

26

But Python gives an error.

Why?

Because age is a string.

This means Python sees:

"25" + 1

That is text plus number.

Python refuses.

And honestly, it should.

This is like trying to add a banana to a calculator.

Interesting.

Not valid.

Convert Input to int

If you want a whole number, use int().

Example:

age_text = input("How old are you? ")
age = int(age_text)

next_year = age + 1

print(f"Next year you will be {next_year}.")

If the user types:

25

Output:

Next year you will be 26.

Here:

int(age_text)

converts the string "25" into the integer 25.

Now Python can do math.

Very good.

The calculator banana has been removed.

Shorter Version

You can convert input directly:

age = int(input("How old are you? "))

next_year = age + 1

print(f"Next year you will be {next_year}.")

This is common.

But for beginners, the longer version is sometimes easier to understand:

age_text = input("How old are you? ")
age = int(age_text)

Both are correct.

Use the one that feels clearer.

Clear code is better than code that looks clever but makes your brain leave the building.

Convert Input to float

If you need a decimal number, use float().

Example:

price = float(input("Product price: "))
quantity = int(input("Quantity: "))

total = price * quantity

print(f"Total: {total}")

Example:

Product price: 19.99
Quantity: 3

Output:

Total: 59.97

Use:

int()

for whole numbers.

Use:

float()

for decimal numbers.

Simple rule.

Useful rule.

Rule that saves many headaches.

Decimal Numbers Use a Dot

In Python, decimal numbers use a dot:

19.99

Not a comma:

19,99

Correct input:

19.99

Wrong input:

19,99

If the user types:

19,99

and your program uses float(), Python will complain.

Python expects a dot.

Python does not care that many countries use a comma for prices.

Python has chosen the dot.

The dot is law.

Tiny dot.

Big authority.

Simple Greeting Program

Create a file:

greeting.py

Write:

name = input("What is your name? ")
city = input("Where do you live? ")

print(f"Hello, {name}!")
print(f"{city} sounds like a nice place.")

Run it.

Example:

What is your name? Anna
Where do you live? Rome

Output:

Hello, Anna!
Rome sounds like a nice place.

This program does not do much.

But it uses real interaction.

Input.

Variables.

Output.

That is a useful pattern.

Many larger programs are just this pattern with more steps and more coffee.

Simple Age Program

Create a file:

age_program.py

Write:

name = input("What is your name? ")
age = int(input("How old are you? "))

next_year = age + 1

print(f"Hello, {name}.")
print(f"Next year you will be {next_year} years old.")

Example:

What is your name? Anna
How old are you? 25

Output:

Hello, Anna.
Next year you will be 26 years old.

Now your program uses:

Small program.

Real concepts.

Very good.

Simple Shop Program

Create a file:

shop_input.py

Write:

customer_name = input("Customer name: ")
product_name = input("Product name: ")
price = float(input("Product price: "))
quantity = int(input("Quantity: "))

total = price * quantity

print("----- Receipt -----")
print(f"Customer: {customer_name}")
print(f"Product: {product_name}")
print(f"Price: {price}")
print(f"Quantity: {quantity}")
print(f"Total: {total}")

Example interaction:

Customer name: Anna
Product name: Keyboard
Product price: 70
Quantity: 2

Output:

----- Receipt -----
Customer: Anna
Product: Keyboard
Price: 70.0
Quantity: 2
Total: 140.0

This is much more interesting.

The user gives the data.

The program calculates the result.

This is how many useful scripts begin.

Not with fireworks.

With input.

And a suspicious amount of patience.

Making Output Cleaner

Sometimes floats print more decimals than you want.

For money, you may want two decimal places.

Use:

print(f"Total: {total:.2f}")

Example:

price = 19.99
quantity = 3

total = price * quantity

print(f"Total: {total:.2f}")

Output:

Total: 59.97

The part:

:.2f

means:

show this number with 2 decimal places

This is useful for prices.

Very useful.

Because money with many random decimals looks like a tax document having a nervous breakdown.

Cleaner Shop Program

Update shop_input.py:

customer_name = input("Customer name: ")
product_name = input("Product name: ")
price = float(input("Product price: "))
quantity = int(input("Quantity: "))

total = price * quantity

print("----- Receipt -----")
print(f"Customer: {customer_name}")
print(f"Product: {product_name}")
print(f"Price: {price:.2f}")
print(f"Quantity: {quantity}")
print(f"Total: {total:.2f}")

Now the output looks cleaner:

----- Receipt -----
Customer: Anna
Product: Keyboard
Price: 70.00
Quantity: 2
Total: 140.00

Much better.

Readable output matters.

A program should not only work.

It should also not look like it was assembled by a tired raccoon.

Unless that is the theme.

Usually not.

Common Mistake: Forgetting int()

Wrong:

age = input("How old are you? ")

next_year = age + 1

print(next_year)

This fails because age is text.

Correct:

age = int(input("How old are you? "))

next_year = age + 1

print(next_year)

If you want math, convert input to a number.

Remember:

input() gives text.
Math needs numbers.

Simple.

Important.

Very Python.

Common Mistake: Using int() for Decimal Numbers

Wrong:

price = int(input("Product price: "))

If the user types:

19.99

Python will complain.

Because int() expects a whole number.

Use:

price = float(input("Product price: "))

Rule:

Age, quantity, number of items -> int
Price, weight, temperature -> float

Not always perfect.

But good for beginners.

Common Mistake: Typing Text When Python Expects a Number

If your program says:

age = int(input("How old are you? "))

and the user types:

banana

Python will crash.

Because:

int("banana")

does not make sense.

Python cannot convert banana into a number.

This is not Python being difficult.

This is Python being reasonable.

Later, we will learn how to handle errors properly.

For now, type the kind of data the program asks for.

If it asks for age, do not answer with fruit.

Usually good life advice too.

Common Mistake: Missing Space in Prompt

This is not broken:

name = input("What is your name?")

But the user will type right after the question:

What is your name?Anna

Better:

name = input("What is your name? ")

Notice the space before the closing quote:

"? "

This makes the input easier to read:

What is your name? Anna

Tiny detail.

Better experience.

Programming is full of tiny details pretending to be small.

Common Mistake: Not Saving the File

You edit your code.

You run the program.

Nothing changes.

Why?

Often because the file was not saved.

Classic.

Very classic.

Almost traditional.

Before running your program, save the file.

Your editor may show a dot or marker when the file has unsaved changes.

Save.

Run.

Check.

This rhythm matters:

edit
save
run

Not:

edit
panic
run old version
panic more

input() with Empty Answers

The user can press Enter without typing anything.

Example:

name = input("What is your name? ")

print(f"Hello, {name}!")

If the user just presses Enter, name becomes an empty string:

""

Output:

Hello, !

Not beautiful.

But valid.

Later, we will learn how to check for empty input.

For now, just know it can happen.

Users are creative.

Sometimes too creative.

Mini Program: Minutes to Seconds

Create a file:

minutes_to_seconds.py

Write:

minutes = int(input("Minutes: "))

seconds = minutes * 60

print(f"{minutes} minutes is {seconds} seconds.")

Example:

Minutes: 5

Output:

5 minutes is 300 seconds.

This program asks for a number.

Converts it.

Calculates.

Prints result.

Simple.

Useful.

A tiny calculator has entered the room.

Mini Program: Celsius to Fahrenheit

Create a file:

temperature.py

Write:

celsius = float(input("Temperature in Celsius: "))

fahrenheit = (celsius * 9 / 5) + 32

print(f"{celsius:.1f}°C is {fahrenheit:.1f}°F.")

Example:

Temperature in Celsius: 20

Output:

20.0°C is 68.0°F.

This uses:

Very good practice.

Also useful if you ever need to understand weather in another measurement system.

Because apparently humanity enjoys variety.

Mini Program: Simple Calculator

Create a file:

calculator.py

Write:

first_number = float(input("First number: "))
second_number = float(input("Second number: "))

sum_result = first_number + second_number
difference = first_number - second_number
product = first_number * second_number
division = first_number / second_number

print(f"Sum: {sum_result}")
print(f"Difference: {difference}")
print(f"Product: {product}")
print(f"Division: {division}")

Example:

First number: 10
Second number: 5

Output:

Sum: 15.0
Difference: 5.0
Product: 50.0
Division: 2.0

This is a real beginner project.

Small.

But real.

It asks for input.

Converts input.

Performs calculations.

Prints results.

This is the foundation of many programs.

Just with fewer buttons and fewer meetings.

Be Careful with Division by Zero

If the user enters:

0

as the second number, this line will fail:

division = first_number / second_number

Because division by zero is not allowed.

Python will show an error:

ZeroDivisionError

For now, avoid using zero as the second number.

Later, when we learn conditions, we will fix this properly.

The future lesson will save us.

For now, we politely avoid mathematical explosions.

Practice

Create a file:

practice_input.py

Ask the user for:

Then calculate:

birth year = current year - age

Example:

name = input("Name: ")
city = input("City: ")
favorite_language = input("Favorite programming language: ")
age = int(input("Age: "))
current_year = int(input("Current year: "))

birth_year = current_year - age

print(f"Hello, {name}!")
print(f"You live in {city}.")
print(f"You like {favorite_language}.")
print(f"You were born around {birth_year}.")

Run it.

Change the answers.

Run again.

The program should adapt to the user input.

That is the point.

Same code.

Different data.

Different output.

Beautiful.

Mini Challenge

Create a file:

order_total.py

Your program should ask for:

Then calculate:

subtotal = product price * quantity
total = subtotal + shipping cost

Print a receipt like this:

----- Order Summary -----
Customer: Anna
Product: Keyboard
Price: 70.00
Quantity: 2
Subtotal: 140.00
Shipping: 5.00
Total: 145.00

Example solution:

customer_name = input("Customer name: ")
product_name = input("Product name: ")
price = float(input("Product price: "))
quantity = int(input("Quantity: "))
shipping = float(input("Shipping cost: "))

subtotal = price * quantity
total = subtotal + shipping

print("----- Order Summary -----")
print(f"Customer: {customer_name}")
print(f"Product: {product_name}")
print(f"Price: {price:.2f}")
print(f"Quantity: {quantity}")
print(f"Subtotal: {subtotal:.2f}")
print(f"Shipping: {shipping:.2f}")
print(f"Total: {total:.2f}")

After it works, change the values.

Try different products.

Try different quantities.

Try decimal prices.

But do not type banana where Python expects a number.

Python is not ready for fruit commerce yet.

Beginner Checklist

When your input program fails, check:

Did I save the file?
Am I running the correct file?
Did I close all parentheses?
Did I close all quotes?
Did I convert number input with int() or float()?
Did I type a number when the program expected a number?
Did I use a dot for decimal numbers?
Did I divide by zero?
Did I spell variable names correctly?

Most errors are small.

Small does not mean harmless.

A missing quote can stop an entire program.

Very dramatic.

Very educational.

Very Python.

Summary

Today you learned:

This is a big step.

Your programs are now interactive.

They can ask questions.

They can use answers.

They can calculate results from user data.

That is how many useful scripts begin.

Not huge.

Not fancy.

But useful.

And useful is powerful.

Next Lesson

In the next lesson, we will learn conditions.

You will learn how to make decisions with:

if
else
elif

Your program will be able to ask questions like:

Is the user old enough?
Is the password correct?
Is the number positive or negative?
Is the product available?

This is where programs start making choices.

Very important.

Very powerful.

Slightly dangerous.

Perfect.