***Welcome to ashrafedu.blogspot.com * * * This website is maintained by ASHRAF***

Tuesday, April 27, 2021

Reading Input from the Keyboard

Python’s built-in input
function is used to read input from the keyboard. The input function reads a
piece of data that has been entered at the keyboard and returns that piece of
data, as a string, back to the program.



General
format:



variable =
input(prompt)



In the general format, prompt
is a string that is displayed on the screen.



Example:



name = input('What is
your name? ')



When the above
statement executes, the following things happen:



• The string 'What is
your name? ' is displayed on the screen.



• The program pauses
and waits for the user to type something on the keyboard and then to press the
Enter key.



• When the Enter key is
pressed, the data that was typed is returned as a string and assigned to the
name variable.



Reading
numeric data using input function



The input function
always returns the user’s input as a string, even if the user enters numeric
data. This can be a problem if you want to use the value in a math operation.
Math operations can be performed only on numeric values, not strings.



Python has built-in
functions that you can use to convert a string to a numeric type.


Example:



string_value =
input('How many hours did you work? ')



hours =
int(string_value)



OR



hours = int(input('How
many hours did you work? '))



The int( ) and float( )
functions work only if the item that is being converted contains a valid
numeric value. If the argument cannot be converted to the specified data type,
an error known as an exception occurs.


No comments:

Post a Comment