Sometimes
we would like to take the value for a variable from the user via their
keyboard. Python provides a built-in function called raw_input() that gest
input from the keyboard. When this function is called the program is stopped
from executing and waits for the user to give an input. The execution of the
program continues soon as the user presses Enter or Return key on keyboard.
After pressing Enter or Return key the raw_input() function returns what the
user typed as a string.
>>>input = raw_input(“Enter your name: “) James >>>print input James >>>type (input)
Before getting input from a user, it is a good idea to
print a prompt telling the user what to input. You can pass a string to
raw_input to be displayed to the user before pausing for input:
>>>name = raw_input(“Enter your name: \n”) Enter your name: James >>>print name James
The sequence \n at the end of the prompt represents a
newline which is a special character that causes a line break. That’s why the
user’s input appears below the prompt.
The raw_input function returns string but if you
expect the user to write an integer than you need to convert the string into
integer using int(). For example
>>>speed = (“Enter the maximum speed of your car(km/h): \n “) Enter the maximum speed of your car(km/h): 220.0 >>>distance=(“Enter a desired distance (km) : \n”) Enter a desired distance(km): 5.0 >>>type(speed)>>>type(distance) >>>v = int(speed) >>>type(speed) >>>s= int(distance) >>>type(distance) >>> t = s/v 0.0227272727273
If you don’t include transformation to integer for
this program the Python will return ValueError.
Nema komentara:
Objavi komentar