Python

input() fuction in Python

Click for All Topics

input() fuction in Python

  • It is a built-in function that allows user input.
  • When we execute the input() function ,it stops the program execution and waits for user response and after getting the input it starts the further execution of the program.
  • It takes optional arguments and returns entered input by user in string format.
  • When users don’t provide any input ,it returns empty string.

Syntax –

input(prompt)

Parameter –

  • prompt(optional) →   a string, that displays a message when the function executes.
  • return → returns provided input strings by user, default value is empty strings ‘ ’ .

Example 1: Basic Input

				
					# Simple input and display
user_name = input("Enter your name: ")
print("Hello, " + user_name +" this is edSlash" + "!")

# Output -
# Enter your name: Harshil
# Hello Harshil, this is edSlash!
				
			
  • In the above example ,firstly the input function executes and display the message (’Enter your name:’) on the user console and gets user name as an input.
  • After getting the input is stored in user_name variable.
  • Finally it prints the user name with the welcome message on the output screen.

 

 

Example 2: Numeric Input and Conversion

				
					# Taking age as input and performing a calculation
age_str = input("Enter your age: ")
age = int(age_str)  # Convert the entered string to an integer
future_age = age + 10
print("In 10 years, you will be", future_age, "years old.")

# Output - 
# Enter your age: 20
# In 10 years, you will be 30 years old.
				
			

Example 3: Conditional Input

				
					# Using input in a conditional statement
response = input("Do you want to continue? (yes/no): ")
if response.lower() == 'yes':
    print("Continuing...")
else:
    print("Cancelled.")


# Output -
# Do you want to continue? (yes/no): no
# Cancelled.
				
			

Example 4: Multiple Inputs

				
					# Taking multiple inputs and performing a calculation
length_str = input("Enter the length: ")
width_str = input("Enter the width: ")

length = float(length_str)  # Convert the entered strings to floats
width = float(width_str)

area = length * width
print("The area is:", area)

# Output -
# Enter the length: 10
# Enter the width: 5
# The area is: 50.0
				
			

Example 5: Input Validation

				
					# Handling invalid input with a try-except block
try:
    quantity_str = input("Enter the quantity: ")
    quantity = int(quantity_str)
    if quantity > 0:
        print("Valid input. Quantity:", quantity)
    else:
        print("Please enter a positive quantity.")
except ValueError:
    print("Invalid input. Please enter a valid integer.")


# Output -
# Enter the quantity: 10
# Valid input. Quantity: 10