The input() function takes input from the user and returns it. Show
Examplename = input("Enter your name: ") print(name) # Output: # Enter your name: James # JamesThe syntax of input() function is: input([prompt])input() ParametersThe input() function takes a single optional argument:
input() Return ValueThe input() function reads a line from the input (usually from the user), converts the line into a string by removing the trailing newline, and returns it. If EOF is read, it raises an EOFError exception. Example 1: How input() works in Python?# get input from userinputString = input() print('The inputted string is:', inputString)Output Python is interesting. The inputted string is: Python is interestingExample 2: Get input from user with a prompt# get input from userinputString = input('Enter a string:') print('The inputted string is:', inputString)Output Enter a string: Python is interesting. The inputted string is: Python is interesting
In Python, Using the input() function, we take input from a user, and using the print() function, we display output on the screen. Using the input() function, users can give any information to the application in the strings or numbers format. After reading this article, you will learn:
Also, Solve
Python Input() functionIn Python 3, we have the following two built-in functions to handle input from a user and system.
In Python 2,we can use the following two functions:
The input() function reads a line entered on a console or screen by an input device such as a keyboard, converts it into a string. As a new developer, It is essential to understand what is input in Python. What is the input?The input is a value provided by the system or user. For example, suppose you want to calculate the addition of two numbers on the calculator, you need to provide two numbers to the calculator. In that case, those two number is nothing but an input provided by the user to a calculator program. There are different types of input devices we can use to provide data to application. For example: –
In Python, there are various ways for reading input from the user from the command line environment or through the user interface. In both cases, the user is sending information using the keyboard or mouse. Python Example to Accept Input From a UserLet see how to accept employee information from a user.
Output: Enter Employee Name: Jessa Enter salary: 8000 Enter Company name: Google Printing Employee Details Name Salary Company Jessa 8000 GoogleHow input() Function Workssyntax input([prompt])
Note: If you enter an integer or float number, still, it will convert it into a string. If you want to number input or input in other data types, you need to perform type conversion on the input value. Let’s understand this with an example. Example to check data type of input value number = input("Enter roll number ") name = input("Enter age ") print("\n") print('Roll number:', number, 'Name:', name) print("Printing type of a input values") print("type of number", type(number)) print("type of name", type(name))Output: Enter roll number 22 Enter age Jessa Roll number: 22 Name: Jessa Printing type of a input values type of number <class 'str'> type of name <class 'str'>As you know whatever you enter as input, the input() function always converts it into a string. Read How to check if user input is a number or string. Take an Integer Number as input from UserLet’s see how to accept an integer value from a user in Python. We need to convert an input string value into an integer using an int() function. Example: # program to calculate addition of two input integer numbers # convert inout into int first_number = int(input("Enter first number ")) second_number = int(input("Enter second number ")) print("\n") print("First Number:", first_number) print("Second Number:", second_number) sum1 = first_number + second_number print("Addition of two number is: ", sum1)Output: Enter first number 28 Enter second number 12 First Number: 28 Second Number: 12 Addition of two number is: 40Note: As you can see, we explicitly added a cast of an integer type to an input function to convert an input value to the integer type. Now if you print the type of first_number you should get integer type. type(first_number ) will return <class 'int'> Take Float Number as a Input from UserSame as integer, we need to convert user input to the float number using the float() function marks = float(input("Enter marks ")) print("\n") print("Student marks is: ", marks) print("type is:", type(marks))Output: Enter marks 74.65 Student marks is: 74.65 type is: <class 'float'>
Accept one integer and one float number from the user and calculate the multiplication of both the numbers. Show Solution num1 = int(input("Enter integer number ")) num2 = float(input("Enter float number ")) print("\n") product = num1 * num2 print("Multiplication is:", product) Get Multiple inputs From a User in One LineIn Python, It is possible to get multiple values from the user in one line. We can accept two or three values from the user. For example, in a single execution of the input() function, we can ask the user his/her name, age, and phone number and store it in three different variables. Let’ see how to do this.
Output: Enter your name, Age, Percentage separated by space Jessa 18 72.50 User Details: Jessa 18 72.50Also, you can take the list as input from the user to get and store multiple values at a time. Read: How to take a list as an input from a user. Accept Multiline input From a UserAs you know, the input() function does not allow the user to provide values separated by a new line. If the user tries to enter multiline input, it reads only the first line. Because whenever the user presses the enter key, the input function reads information provided by the user and stops execution. Let’s see how to gets multiple line input. We can use a loop. In each iteration of the loop, we can get input strings from the user and join them. You can also concatenate each input string using the + operator separated by newline (\n). Example: # list to store multi line input # press enter two times to exit data = [] print("Tell me about yourself") while True: line = input() if line: data.append(line) else: break finalText = '\n'.join(data) print("\n") print("Final text input") print(finalText)Output: Tell me about yourself My Name is Jessa I am a software engineer Final text input My Name is Jessa I am a software engineerPython Input() vs raw_input()
The difference between the input() and raw_input() functions is relevant only when using Python 2.
Let’s see how to use raw_input() in Python 2. Example 1: Python 2 raw_input() function to take input from a user # Python 2 code # raw_input() function name = raw_input("Enter your name ") print "Student Name is: ", name print type(name) age = raw_input("Enter your age ") print "Student age is: ", age print type(age)Output: Enter your name Jessa Student Name is: Jessa <type 'str'> Enter your age 18 Student age is: 18 <type 'str'>Note: As you can see, raw_input() converted all user values to string type. Example 2: Python 2 input() function to take input from a user # Python 2 code # input() function name = input("Enter your Name ") print "Student Name is: ", name print type(name) age = input("Enter your age ") print "Student age is: ", age print type(age)Output: Enter your Name Jessa Student Name is: Jessa <type 'str'> Enter your age 18 Student age is: 18 <type 'int'>Note: As you can see, input() converted all user values to appropriate data type. Note: To get the this behavior of input() in Python 3, use eval(input('Enter Value')) Command Line inputA command line interface (CLI) is a command screen or text interface called a shell that allows users to interact with a program. For example, On windows, we use the Command Prompt and Bash on Linux. command line or command-line interface is a text-based application for viewing, handling, and manipulating files on our computer. The command line also called cmd, CLI, prompt, console, or terminal. On command-line, we execute program or command by providing input/arguments to it. Also, output and error are displayed A command line. We can run Python programs on the command line. The command line input is an argument that we pass to the program at runtime. Python provides following modules to work with command-line arguments.
Python sys moduleThe Python sys module is the basic module that implements command-line arguments in a simple list structure named sys.argv.
Steps: Write the below code in a file and save it as a sample.py from sys import argv print("Total argument passed :", len(argv))Run the below command on the command line python sample.py 20 30 40Output Total argument passed : 4Here 10, 20, 30 are command-line arguments passed to the program. Each input represents a single argument.
Note: argv is not an array. It is a list. This is a straightforward way to read command-line arguments as a string. See the following example to check the type of argv Example from sys import argv print(type(argv)) # Output <class 'list'>Now let’s see another example where we display all command-line arguments passed to the program. Example : To Display command line argumnets from sys import argv print("All command line inputs") for value in argv: print(value)Run the below command on the command line python sample.py 20 30 40Output C:\Anaconda3>python sample.py 20 30 40 All command line inputs sample.py 20 30 40Note : The space is separator between command line arguments. In Python, by default, command-line arguments are available in string format. Based on our requirement, we can convert it into the corresponding type by using the typecasting method. See the following example where we change the data type of arguments using the int() method. Example from sys import argv # calculate the addition of two command line input print('Argument one:') print('Argument Two:') add = int(argv[1]) + int(argv[2]) print('Addition is:', add)Output If we try to access arguments with out of the range index on the command line, we will get an error. from sys import argv print(argv[2]) print(argv[3])Output C:\Anaconda3>python sample.py 20 Traceback (most recent call last): File "sample.py", line 3, in <module> print(argv[2]) IndexError: list index out of rangeOutput in PythonPython has a built-in print() function to display output to the standard output device like screen and console. Example 1: Display output on screen # take input name = input("Enter Name: ") # Display output print('User Name:', name)Output: Enter Name: Jessa User Name: JessaExample 2: Display Output by separating each value name = input('Enter Name ') zip_code = int(input('Enter zip code ')) street = input('Enter street name ') house_number = int(input('Enter house number ')) # Display all values separated by hyphen print(name, zip_code, street, house_number, sep="-")Output: name = input('Enter Name ') Enter Name Jessa Enter zip code 412365 Enter street name abc street Enter house number 234 Jessa-412365-abc street-234Output FormattingMost of the time, we need to format output instead of merely printing space-separated values. For example, we want to display the string left-justified or in the center. We want to show the number in various formats. You can display output in various styles and formats using the following functions.
Now, Let see each one by one. str.format() to format outputstr.format(*args, **kwargs)
Let see this with an example: print('FirstName - {0}, LastName - {1}'.format('Ault', 'Kelly'))Note: Here {0} and {1} is the numeric index of a positional argument present in the format method. i.e., {0} = Ault and {1} = Kelly. Anything that not enclosed in braces {} is considered a plain literal text. Let see different ways to display output using a format() method. You can find various Formatting options here. Format Output String by its positionsfirstName = input("Enter First Name ") lastName = input("Enter Last Name ") organization = input("Enter Organization Name ") print("\n") print('{0}, {1} works at {2}'.format(firstName, lastName, organization)) print('{1}, {0} works at {2}'.format(firstName, lastName, organization)) print('FirstName {0}, LastName {1} works at {2}'.format(firstName, lastName, organization)) print('{0}, {1} {0}, {1} works at {2}'.format(firstName, lastName, organization))Output: Enter First Name Ault Enter Last Name Kelly Enter Organization Name Google Ault, Kelly works at Google Kelly, Ault works at Google FirstName Ault, LastName Kelly works at Google Ault, Kelly Ault, Kelly works at GoogleAccessing Output String Arguments by namename = input("Enter Name ") marks = input("Enter marks ") print("\n") print('Student: Name: {firstName}, Marks: {percentage}%'.format(firstName=name, percentage=marks))Output: Enter Name Jhon Enter marks 74 Student: Name: Jhon, Marks: 74%Output Alignment by Specifying a Widthtext = input("Enter text ") print("\n") # left aligned print('{:<25}'.format(text)) # Right aligned print('{:>25}'.format(text)) # centered print('{:^25}'.format(text))Output: Enter text This is a sample text This is a sample text This is a sample text This is a sample textSpecifying a Sign While Displaying Output Numberspositive_number = float(input("Enter Positive Number ")) negative_number = float(input("Enter Negative Number ")) print("\n") # sign '+' is for both positive and negative number print('{:+f}; {:+f}'.format(positive_number, negative_number)) # sign '-' is only for negative number print('{:f}; {:-f}'.format(positive_number, negative_number))Output: Enter Positive Number 25.25 Enter Negative Number -15.50 +25.250000; -15.500000 25.250000; -15.500000Display Output Number in Various Formatnumber = int(input("Enter number ")) print("\n") # 'd' is for integer number formatting print("The number is:{:d}".format(number)) # 'o' is for octal number formatting, binary and hexadecimal format print('Output number in octal format : {0:o}'.format(number)) # 'b' is for binary number formatting print('Output number in binary format: {0:b}'.format(number)) # 'x' is for hexadecimal format print('Output number in hexadecimal format: {0:x}'.format(number)) # 'X' is for hexadecimal format print('Output number in HEXADECIMAL: {0:X}'.format(number))Output: Enter number 356 The number is:356 Output number in octal format : 544 Output number in binary format: 101100100 Output number in hexadecimal format: 164 Output number in HEXADECIMAL: 164Display Numbers as a float typenumber = float(input("Enter float Number ")) print("\n") # 'f' is for float number arguments print("Output Number in The float type :{:f}".format(number)) # padding for float numbers print('padding for output float number{:5.2f}'.format(number)) # 'e' is for Exponent notation print('Output Exponent notation{:e}'.format(number)) # 'E' is for Exponent notation in UPPER CASE print('Output Exponent notation{:E}'.format(number))Output: Enter float Number 234.567 Output Number in The float type :234.567000 padding for output float number234.57 Output Exponent notation2.345670e+02 Output Exponent notation2.345670E+02Output String AlignmentLet’s see how to use str.rjust(), str.ljust() and str.center() to justify text output on screen and console. text = input("Enter String ") print("\n") print("Left justification", text.ljust(60, "*")) print("Right justification", text.rjust(60, "*")) print("Center justification", text.center(60, "*"))Output: Enter String Jessa Left justification Jessa******************************************************* Right justification *******************************************************Jessa Center justification ***************************Jessa****************************Next StepsTo practice what you learned in this article, I have created a Quiz and Exercise.
References:
|