User Input in Python

  • In this chapter, you'll learn how to interact with your Python programs by taking user input. This allows your programs to be flexible and respond based on what the user provides.

  • The input() Function :
  • The primary tool for user input in Python is the input() function. It pauses your program's execution and waits for the user to type something. Whatever the user types is returned as a string by the input() function.


  • Here's the basic syntax :
  • user_input = input("Enter your name: ")

    This code displays the prompt "Enter your name: " on the screen. The user types their name and presses Enter. The program then stores the entered name in the variable user_input.


  • Examples of User Input:
  • 1. Greeting the User:
    name = input("What's your name?")
    print("Hello, " + name + "!")

    This program asks the user for their name and then prints a personalized greeting.


    2. Getting Numbers from the User:
    age = int(input("How old are you? "))
    print("You are", age, "years old.")

    Here, the program asks for the user's age. However, input() always returns a string. We use int() to convert the entered string to an integer before storing it in the age variable.


  • Examples: Basic Problems & Solutions
  • Python code
    #1. Write a program to accept the marks of student in Physics, Chemistry and Biology. Display the total marks and average marks.

    p = int(input("Enter the marks of physics:"))
    c = int(input("Enter the marks of chemistry:"))
    m = int(input("Enter the marks of math:"))
    b = int(input("Enter the marks of biology:"))
    s = p+c+m+b
    a=(p+c+m+b)/5
    print("Total=",s)
    print("average=",a)
    Python code
    2. Write a program to find the base area , surface area and volume of square pyramid BaseAreaofaSquarePyramid=𝑏² SurfaceAreaofaSquarePyramid=2bs+𝑏² VolumeofaSquarePyramid=1/3𝑏²ℎ [b – base length s – slant height h – height ]

    b = int(input("enter the base length"))
    h = int(input("enter the height"))
    s = int(input("enter the slant height"))
    B = float(b*b)
    S = float((2*b*s)+(b*b))
    V = float(b*b*h/3)
    print("base area=", B)
    print("surface area=", S)
    print("volume=", V)
    Key Points to Remember:
  • input() always returns a string, even if the user enters a number.
  • You might need to convert the user input to a different data type (like integer or float) using functions like int(), float(), etc., depending on how you plan to use it in your program.
  • You can provide informative prompts within the input() function to guide the user on what kind of input is expected.

  • Practice Exercises:
  • 1. Write a program that asks the user for their favorite color and then prints a message like "Your favorite color is blue!".
  • 2. Write a program that asks the user for two numbers and then prints their sum.