Tuesday, 24 May 2011

User-Controlled Input and Output

Continuing from the last lesson we will look further into creating more general programs that allow the user to input values while the program is running, using the input() function.



value = input('Enter a value: ')

The above code displays the following string and waits for the user to provide input.

Enter a value: 

The value entered is then referenced by the variable value. Eg.

>>> value = input('Enter a value: ')
Enter a value: 13
>>> value
'13'

In this case, the input function returns a string. This may need to be converted to an integer or floating-point value. We can do this using either of the following methods.

>>> value = int(input('Enter a value: '))
Enter a value: 13
>>> value
13

>>> value = float(input('Enter a value: '))
Enter a value: 13
>>> value
13.0

The int() and float() functions take the user input, and convert it to the appropriate type.

Below is another example, this time with strings. It take the user input for the first and last name, adds them together in the variable name and places a space between them. The name is then output directly and via the print() function.

>>> first = input('Enter your first name: ')
Enter your first name: Peter
>>> last = input('Enter your last name: ')
Enter your last name: Griffin
>>> name = first + ' ' + last
>>> name
'Peter Griffin'
>>> print(name)
Peter Griffin

Once you feel confident working with these functions, continue on to: Exercises Part 2

-Nathan (everythingPython)

No comments:

Post a Comment