, ,

How Do You Read Input and Print Output in Python? (Python for Beginners, Part 4)

Python input() and print() explained plainly: why input is always text, converting with int() and float(), reading a ValueError calmly, and the expense tracker going interactive.

Python for Beginners · Part 4 of 20

Here is a program that talks back. Put it in a file called greet.py and run it:

greet.py
name = input('Your name: ')
print('Hello,', name)
terminal
Your name: Asha
Hello, Asha

The program printed Your name: and then stopped and waited. You typed Asha, pressed Enter, and it greeted you by name. Two built in functions did all of it. input asked the question and read your answer, and print put the greeting on screen. Everything in Part 3 was the program talking to itself. This is the program talking to a person.

Bottom lineinput() shows an optional prompt, waits for the user to type one line, and hands that line back as text. print() displays whatever values you give it. The single fact that trips up every beginner: input always returns a string, even when the user types a number. Wrap it in int() or float() before you do any arithmetic, and the rest is easy.

You need Part 3 behind you, the part where you met variables and the int, float and str types. Add Python 3 and about twenty minutes. Nothing new to install. Type or paste each block and run it, and your screen should match the output shown.

print: putting things on screen

You have used print since Part 2, but it does more than show one value. Give it several values separated by commas and it prints them on one line with a single space between each.

python
print('Groceries', 250.0)
print('a', 'b', 'c')
output
Groceries 250.0
a b c

Notice you did not convert 250.0 to text first. When you pass values to print with commas, it turns each one into text for you and never complains about mixing a str and a float. That is different from joining with a plus sign, which does complain. Keep both tools in mind: commas for quick display, the plus sign when you need one finished string.

Two knobs: sep and end

Two settings change how print behaves. sep is what goes between the values, a space by default. end is what goes after the last value, a newline by default, which is why each print lands on its own line.

python
print('2026', '07', '03', sep='-')
print('Loading', end='')
print('...done')
output
2026-07-03
Loading...done

The first line glued the three pieces with a hyphen instead of a space. The second line set end to an empty string, so the next print continued on the same line rather than dropping down. You will not reach for these every day, but the day you want output on one line, this is how.

CallWhat it doesOutput
print('a', 'b')Default space betweena b
print('a', 'b', sep='')Nothing betweenab
print('a', 'b', sep=', ')Comma and space betweena, b
print('a', end='')No line break aftera (next print joins on)
print( 'a' , 'b' ) a sep b then end adds a new line sep sits between values

print places sep between the values and end after the last one.

input: reading what the user types

The input function pauses your program and waits for the person to type a line and press Enter. Whatever you pass inside the brackets is shown first as a prompt, so the user knows what you want. The prompt is optional, but leaving it out gives a blank pause that looks like the program froze, so nearly always include one.

prompt shown Amount: user types press Enter '250' a str

Whatever the user types comes back as a string, even the digits 250.

That last box is the whole lesson. Read a value with input and check its type, and you always get str, no matter what was typed.

python
age = input('Age: ')
print(type(age))
output
Age: 30
<class 'str'>

You typed 30, which looks like a number, but Python handed back the text '30'. To run the file, open a terminal in the folder that holds it and use python greet.py on Windows, or python3 greet.py on macOS and Linux.

Watch the quote marksThe prompt inside input is a string, so it lives in quotes. If you paste this code from a web page and the run stops with a SyntaxError pointing at the prompt, your editor probably turned the straight quotes into curly ones. Delete them and retype the quotes yourself. It is a five second fix once you know to look.

Add two numbers the user types

Here is the mistake almost everyone makes on their first interactive program, shown on purpose so you recognise it later. Ask for two numbers and add them.

add.py
a = input('First number: ')
b = input('Second number: ')
print(a + b)
terminal
First number: 10
Second number: 5
105

You asked for 10 and 5 and got 105, not 15. Nothing is broken. Both values came in as text, and the plus sign joins text end to end, so '10' and '5' became '105'. This is the same string versus number rule from Part 3, now wearing a keyboard. The fix is to convert each answer to a number as it arrives.

add.py
a = int(input('First number: '))
b = int(input('Second number: '))
print(a + b)
terminal
First number: 10
Second number: 5
15

Read int(input('First number: ')) from the inside out. The inner input gets the text, and the outer int turns it into a whole number, all in one line. Use float instead when the answer might have a decimal point, like a price. Reach for int for counts and float for money and measurements.

When the user types something odd

What if someone types letters where you expected a number? Try converting the word ten:

python
int('ten')
traceback
Traceback (most recent call last):
  File "add.py", line 1, in <module>
    int('ten')
ValueError: invalid literal for int()
with base 10: 'ten'

A traceback is not a scolding. It is Python telling you exactly what happened, and the habit that will save you hours is to read the last line first. It says ValueError, then in plain words that int could not make a number out of 'ten'. The word literal just means the exact text you handed it. For now, know that this can happen. In Part 12 you will catch it and ask the user to try again instead of letting the program stop.

Traceback (most recent call last): File add.py, line 1 int('ten') ValueError: invalid literal … read this line first

The last line names the error and the cause. Start there, then look up.

In practiceA common pattern is to read and convert on the same line, like qty = int(input('Quantity: ')). It is tidy and you will see it everywhere. The tradeoff is that if the user types something wrong, the crash points at that packed line and you cannot see the raw text they entered. While you are learning, splitting it into two lines, read first then convert, makes a stumble easier to follow. Pack it back together once the logic is solid.
Project check-in: the tracker starts askingIn Part 3 your expenses.py held one expense in fixed variables. Now let the user type it. Replace the hard coded lines so the program asks for a category and an amount, then reads them back:
expenses.py
print('My Expense Tracker')
category = input('Category: ')
amount = float(input('Amount: '))
print('You spent', amount, 'on', category)
terminal
My Expense Tracker
Category: Groceries
Amount: 250
You spent 250.0 on Groceries
The amount uses float so a price like 12.50 works, which is why 250 comes back as 250.0. The tracker now takes real input instead of numbers you baked in. It still forgets everything the moment it ends and only holds one expense. Part 5 teaches it to make a decision about what you typed, and Part 6 lets it accept several expenses in a row.
Your turnWrite a program that asks for a price and a quantity, then prints the total cost. Convert the price with float and the quantity with int. Match the run below, typing 3.5 and 4 when asked.
expected terminal
Price: 3.5
Quantity: 4
Total: 14.0
Show solution
solution.py
price = float(input('Price: '))
qty = int(input('Quantity: '))
print('Total:', price * qty)
terminal
Price: 3.5
Quantity: 4
Total: 14.0
Interview question you might hearA screener asks: a user enters 7 and your program prints 14 when you expected 7. What is likely going on? A strong answer notices the value was probably added to itself as text or doubled by accident, but the sharper reading is the classic one. Input arrives as a string, so if you wrote print(reply + reply) thinking it would add, you got the text joined instead. Convert with int or float before any maths. Interviewers ask this because the string versus number slip is the most common bug in beginner code.
Where this shows up in your first jobAlmost no real program invents its own data. It reads a form field, a config file, a command line argument, a row from a database, and every one of those arrives as text that has to be checked and converted before you can trust it. The habit you are building here, never assume input is the type you want, prove it and convert it, is exactly what separates code that works on your machine from code that survives a real user. This tiny int(input(…)) move is the seed of input validation, and you will do a grown up version of it in Part 12.
A real opinionYou will see beginners reach for the walrus operator or clever one liners to read and check input in a single expression. Skip that early. Clear beginner code reads top to bottom: show a prompt, read the answer, convert it, use it. Four plain lines that anyone can follow beat one dense line that shows off. Save the compact tricks for when the simple version is second nature and the extra density actually earns its keep.

Quick answers before Part 5

Does the prompt in input have to be there? No, input() with empty brackets works, but the program then waits with no message and looks stuck. Always give a short prompt so the user knows what to type.

Why does my number act like text after input? Because input always returns a string. Even '30' is text until you convert it. Wrap it in int() or float() the moment you read it.

What is the difference between int and float here? Use int when the value is a whole count, like a quantity. Use float when it can have a decimal point, like a price or a weight. Converting a decimal string with int will error, so match the tool to the data.

My program crashed with a ValueError. Did I break Python? No. It means a conversion got text it could not turn into a number, usually a typo or an empty answer. Read the last line of the traceback, it names the value that caused it. Handling this cleanly comes in Part 12.

How do I print things on the same line? Pass end='' to the first print so it does not add a line break, and the next print continues beside it.

You can now ask the user a question, read their answer, convert it to the number type you need, show results with print and its sep and end settings, and read a ValueError without flinching.

Part 5 is where your program grows a brain. You will use if, elif and else to react to what the user typed, and the tracker will start flagging an expense that looks too big. Keep expenses.py exactly as it is now. We build straight on top of it again.

Put it together: a tiny tip calculator

One small program uses everything from this part at once. It asks for a bill and a tip percent, works out the tip, and prints a clean total. Build it up so each line has a reason. Start by reading the two numbers the user types.

tip.py
bill = float(input('Bill amount: '))
pct = float(input('Tip percent: '))

Both use float, not int, because a bill can be 39.50 and a tip percent can be 12.5. Now do the arithmetic. The tip is the bill times the percent over one hundred, and the total adds the two. Round both to two decimal places so you do not get the long trailing digits you met in Part 3.

tip.py
bill = float(input('Bill amount: '))
pct = float(input('Tip percent: '))
tip = round(bill * pct / 100, 2)
total = round(bill + tip, 2)
print('Tip:', tip)
print('Total:', total)
terminal
Bill amount: 40
Tip percent: 10
Tip: 4.0
Total: 44.0

Read it top to bottom and nothing is hidden. Two answers come in as text and become floats, two calculations turn them into a tip and a total, and two prints show the result. That plain shape, read then convert then compute then show, is the backbone of almost every small program you will write for a long while. If a user types a word instead of a number, you already know what happens: a ValueError, with the cause on the last line. You will teach the program to handle that gracefully in Part 12, but the logic here is complete and correct as it stands.

References

Python docs: the input() built in function
Python docs: the print() built in function, sep and end
Python tutorial: input and output

Python for Beginners · Part 4 of 20
« Previous: Part 3  |  Complete Guide  |  Next: Part 5

About The Author


Discover more from Journal of Intelligent Infrastructure – By Dr Pranay Jha

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

Architect’s Toolkit

About the Author

Dr. Pranay Jha is a Cloud and AI Consultant with 18+ years of experience in hybrid cloud, virtualization, and enterprise infrastructure transformation. He specializes in VMware technologies, multi-cloud strategy, and Generative AI solutions. He holds a PhD in Computer Applications with research focused on Cloud and AI, has published multiple research papers, and has been a VMware vExpert since 2016 and a VMUG Community Leader.

Discover more from Journal of Intelligent Infrastructure - By Dr Pranay Jha

Subscribe now to keep reading and get access to the full archive.

Continue reading