Site icon TestingDocs.com

Get User Input in Python

Introduction

In this tutorial, we will learn to get user input in Python. We can get user input by using the input() function.

Get User Input

You can use the input() function to get user input in Python. This function pauses your program and waits for the user to type something. When the user presses the Enter key, the function returns the text the user typed as a string.

Example

Let’s consider the below statement:

name = input(“Enter your name: “)

The left side of the assignment statement is the variable name that holds a value whatever the user enters. On the right side is a call to the function input(). The task of the input() function is to wait and get the text the user enters. The function will wait until the user hits the enter key. We have passed an argument to the input function “Enter your name: “. The function uses this string to prompt the user. Good programs use meaningful text that conveys the message to the user. Choose a meaningful text message in your program.

Good
name = input(“Enter a number between 1 and 100: “)

Bad
name = input(“number”)

input() functions wait for the user to enter some text. Once the user presses the Enter key input(), it returns whatever the user typed to the variable as string.

Screenshot

Code Listing

Let us see a simple program.


#Python program to demonstrate user input

#main function

def main():

   a=input("Enter an integer a : ")

   b=input("Enter an integer b : ")

   total=add(a,b)

   print(total)


#add function

def add(a,b):

   return int(a) + int(b)

main()

Python Tutorials

Python Tutorial on this website can be found at:

https://www.testingdocs.com/python-tutorials/

More information on Python is available at the official website:

https://www.python.org

Exit mobile version