Taking Input from User

What is User Input?

So far, all the values in your programs were hardcoded — meaning you wrote them directly in the code like name = "Gagan".

But real programs ask the user to enter data. Like when an app asks "Enter your name" or "Enter your password". That's user input.

In Python, we use the input() function for this.


Basic Syntax


    name = input("Enter your name: ")
    print(f"Hello, {name}!")

Run this program. It will:

  1. Show the message Enter your name: on screen
  2. Wait for you to type something
  3. When you press Enter — it stores what you typed in the name variable
  4. Then prints the greeting

Try it! Type your name and press Enter. Output will be:

Enter your name: Gagan
Hello, Gagan!

How input() Works

variable = input("Message to show user: ")
  • Whatever you write inside the quotes is shown to the user as a prompt
  • Whatever the user types gets stored in the variable
  • User input is always stored as a String — this is very important, we'll come back to this

More Examples


    name = input("What is your name? ")
    city = input("Which city are you from? ")
    language = input("Which language are you learning? ")

    print(f"Hi {name}!")
    print(f"So you are from {city}")
    print(f"Great choice learning {language}!")

Output:

What is your name? Gagan
Which city are you from? Delhi
Which language are you learning? Python
Hi Gagan!
So you are from Delhi
Great choice learning Python!

IMPORTANT — Input is Always a String

This is where beginners get confused. Let's see the problem:


    age = input("Enter your age: ")
    print(type(age))

Output:

Enter your age: 22
<class 'str'>

Even though you typed 22 (a number), Python stored it as "22" (a string). So if you try to do math with it:


    age = input("Enter your age: ")
    next_year_age = age + 1   # ERROR!
    print(next_year_age)

This will give you a TypeError because you can't add a string and a number.


Solution — Convert Input to Number

Use int() or float() to convert:


    age = input("Enter your age: ")
    age = int(age)                    # convert string to integer

    next_year_age = age + 1
    print(f"Next year you will be {next_year_age} years old")

Output:

Enter your age: 22
Next year you will be 23 years old

Shortcut — do it in one line:


    age = int(input("Enter your age: "))       # integer
    price = float(input("Enter price: "))      # decimal number

This is the most common way you'll see it written in real code.


When to Use int() vs float()


    # Use int() when you expect a whole number
    age = int(input("Enter your age: "))
    quantity = int(input("Enter quantity: "))

    # Use float() when you expect a decimal number
    price = float(input("Enter price: "))
    height = float(input("Enter your height: "))

    # Use nothing (plain input) when you expect text
    name = input("Enter your name: ")
    city = input("Enter your city: ")


Real World Example — Simple Calculator

Let's build your first interactive program!


    print("=== Simple Calculator ===")

    num1 = float(input("Enter first number: "))
    num2 = float(input("Enter second number: "))

    addition = num1 + num2
    subtraction = num1 - num2
    multiplication = num1 * num2
    division = num1 / num2

    print(f"\nResults:")
    print(f"{num1} + {num2} = {addition}")
    print(f"{num1} - {num2} = {subtraction}")
    print(f"{num1} * {num2} = {multiplication}")
    print(f"{num1} / {num2} = {division}")

Output:

=== Simple Calculator ===
Enter first number: 10
Enter second number: 4

Results:
10.0 + 4.0 = 14.0
10.0 - 4.0 = 6.0
10.0 * 4.0 = 40.0
10.0 / 4.0 = 2.5

Notice the \n in print(f"\nResults:") — this prints a blank line before "Results". \n means new line. Useful for spacing output nicely.


Another Example — Bill Splitter


    print("=== Bill Splitter ===")

    total_bill = float(input("Enter total bill amount: "))
    num_people = int(input("How many people? "))

    each_person = total_bill / num_people

    print(f"\nTotal bill: Rs.{total_bill}")
    print(f"Number of people: {num_people}")
    print(f"Each person pays: Rs.{each_person}")

Output:

=== Bill Splitter ===
Enter total bill amount: 1200
How many people? 4

Total bill: Rs.1200.0
Number of people: 4
Each person pays: Rs.300.0

Formatting Decimal Output

Sometimes the output looks messy with too many decimal places:


    result = 10 / 3
    print(result)   # 3.3333333333333335  — too many decimals

You can control how many decimal places to show using :.2f inside f-strings:


    result = 10 / 3
    print(f"{result:.2f}")    # 3.33  — only 2 decimal places
    print(f"{result:.1f}")    # 3.3   — only 1 decimal place
    print(f"{result:.0f}")    # 3     — no decimal places

Update the bill splitter:


    print(f"Each person pays: Rs.{each_person:.2f}")   # Rs.300.00

Much cleaner!


Quick Summary of What You've Learned So Far

You now know:

  • print() — display output
  • Variables and data types (str, int, float, bool)
  • Math operations
  • input() — take user input
  • int(), float(), str() — type conversion
  • f-strings — combine variables with text

These are the absolute foundations of Python. Everything else builds on top of this.


Exercise 🏋️

Build a Personal Info Card program:

  1. Ask the user for: name, age, city, and favorite hobby
  2. Calculate: what year they were born (hint: 2025 - age)
  3. Print a nicely formatted info card like this:
=============================
        PERSONAL INFO CARD
=============================
Name     : Gagan
Age      : 22
City     : Delhi
Hobby    : Coding
Born in  : 2003
=============================

This combines everything — input, variables, math, and f-strings. Give it a try!

No comments:

Post a Comment

Loops, Break and Continue in Python

What are Loops? Imagine you want to print "Hello" 100 times. Will you write print("Hello") 100 times? Obviously not. ...