6.1 Function input ()
The function input () lets the program pause and waits for some text input from the user. After the user input is obtained, Python stores it in a variable. For example:
message = input ("Tell Me Something:")
Print (message)
The function input () accepts a parameter. The program waits for user input and continues to run after the user presses the ENTER key. The input is stored in the variable message, and the next print (message) renders the input to the user.
Tell me Something:hello everyone! Hello everyone!
Write a clear program
Whenever you use the function input (), you should specify a clear and unambiguous hint that accurately indicates what information you want the user to provide, as follows:
Name = input ("Please enter your name:") print ("Hello," "! ")
Please enter your Name:aaazhello,aaaz!
Sometimes, the hint may be more than one line. In this case, you can store the hint in a variable and then pass the variable to function input ().
" If you are the Are,we can personalize the messages you see. " "= input (prompt) print (" \nhello, ""! ")
This example shows a way to create a multiline string. Line 1th stores the first half of the message in the variable prompt, and in row 2nd, the operator + = appends a string to the end of the string stored in prompt.
Use INT () to get numeric input
When using the input () function, Python interprets the user input as a string. Take a look at the interpreter sessions that let users enter their age:
>>> age = Input ("")What old is you >>> age ' + '
The user enters the number 21, but when we request that Python provide the value of the variable age, it returns ' 21 '-a numeric string representation of the user's input.
>>> age = Input ("")What old is youTraceback ( Most recent call last): '<stdin>'1 in <module >int()
When you try to use the input for numeric comparisons, Python has an error because it cannot compare numbers to strings.
To solve this problem, you can use the function int (), which gives Python input as a numeric value. the function int () Converts the string representation of a number to a numeric representation:
>>> age = Input ("")How old is youint. int(age) - True
Use the function int () in the actual program. The procedure below determines whether a person is tall enough to ride a roller coaster.
Height = input ("" "int(height)if: Print ("\nyou is tall enough to ride! " Else: print ("\nyou ' ll be able to ride if you ' re a little older . ")
Modulo operator
When working with numeric information, the modulo operator (%) is a useful tool that divides two numbers and returns the remainder:
4 3 1 5 3 2 6 3 0
You can use the modulo operation to determine whether a number is odd or even.
Number = input ("Enter a number, and I ' ll tell you if it's even or odd:") number=int(number)ifNumber%2==0: Print ("\nthe number"+ STR (number) +"is even.")Else: Print ("\nthe number"+ STR (number) +"is odd.")
Python essay 6 (user input ())