1.2.1.8 PCEP-30-02 Practice Test Compendium – Basic Input/Output
Basic Input/Output
The
input()
function is used to interact with the user, allowing them to suspend program execution and to enter a sequence (including an empty one) of characters, which is the function's result.If the user presses
<Enter>
while providing no other input, theinput()
function returns an empty string as a result. For example, thename
variable is assigned with a string inputted by the user:name = input()
The
input()
function accepts an optional argument which is a string; the argument is printed on the screen before the actual input begins. For example, the user is prompted to input the name:name = input('What is your name?')
To convert the user's input into an integer number, the
int()
function can be used.An operation during which the data changes its type is called type casting. For example, the user is asked to input a year of birth. The input is converted into an integer number and assigned to the
b_year
variable:b_year = int(input('What is your year of birth?'))
To convert the user's input into a float number, the
float()
function can be used. For example, the user is asked to input a height measured in meters. The input is converted into a float number and assigned to them_stature
variable:m_stature = float(input('What is your height in meters?'))
If the
int()
orfloat()
is not able to perform the conversion due to the incorrect contents of the user's input, theValueError
exception is raised.Unless otherwise specified, the printed values are separated by single spaces. For example, the following snippet sends
1 2 3
to the screen:print(1, 2, 3)
If the invocation makes use of the
sep
keyword parameter, the parameter's value (even when it's empty) is used to separate outputted values instead of spaces. For example, the following snippet sends1*2*3
to the screen:print(1, 2, 3, sep='*')
Unless otherwise specified, each
print()
function invocation sends the newline character to the screen before its completion, therefore eachprint()
function's output starts on a new line. For example, the following snippet produces two lines of output on the screen:print('Alpha')
print('Bravo')
If the invocation makes use of the
end
keyword parameter, the parameter's value is (even when it's empty) used to complete the output instead of the newline. For example, the following snippet produces one line of output on the screen:print('Alpha', end='')
print('Bravo')
The
end
andsep
parameters can be used together. For example, the following snippet produces one line of asterisk-separated letters:print('A', 'B', sep='*', end='*')
print('C')
Last updated