Chp-2: Input and Output#

Chapter Objectives

By the end of this chapter, the student should be able to:

  • Explain the purpose of input() and print() functions in Python, for managing user input and showing output.

  • Apply input() to prompt users for input, handling different data types entered.

  • Apply print() to display output, understanding formatting options like separators and line breaks.

  • Use whitespace characters in Python output and manipulate them for formatting.

  • Use escape sequences to control whitespace characters in printed output.

input()#

The input() function is a built-in function used to obtain data or information from the user.

  • It returns a string.

  • To receive a number from the user, you’ll need to convert the output of the input() function to an integer or float.

  • You can include a message as a string to provide directions to the user.

  • Upon running the code, your message will be displayed, and a box will prompt the user for input.

  • After entering the input, the user should press the enter key.

In the following code, the user is prompted with the message Enter your birth year: .

input('Enter your birth year: ')

Two important points in the code above:

  1. Even though the user enters a number, the input() function returns a string.

    • To perform algebraic operations, you’ll need to convert it to an integer or float.

  2. We must assign the value given by the user to a variable to store and use it.

    • In the provided code, as no variable is used, there’s no way to access the given birth year in subsequent lines.

In the following code, we will once again ask for the user’s birth year, but this time we will assign it to a variable.

  • This way, we will be able to access the birth year through the variable birth_year in any cell.

  • Note that the type of the birth_year variable is string because the input() function returns any entered value as a string.

birth_year = input('Enter your birth year: ')

print('birth_year type:', type(birth_year))

Output
Enter your birth year: 2000
birth_year type: <class ‘str’>

  • If you intend to perform algebraic operations, such as calculating age, using the birth_year variable, you’ll need to convert it to a numerical type.

  • Otherwise, an error message will be generated.

birth_year = input('Enter your birth year: ')

age = 2024 - birth_year  # ERROR: integer 2024 -  string birth_year
  • To avoid this, convert birth_year to an integer. This can be done in a couple of different ways.

  • In the second line of the following code, the integer value of birth_year is used in subtraction.

birth_year = input('Enter your birth year: ')

age = 2024 - int(birth_year)    

print('Your age is', age)
print('birth_year type:', type(birth_year))

Output
Enter your birth year: 2000
Your age is 24
birth_year type: <class ‘str’>

  • In the above code, the type of birth_year was not changed; it remains a string because we did not assign a new value to it.

  • This can be accomplished in a concise manner at the very beginning of the code.

birth_year = input('Enter your birth year: ')
birth_year = int(birth_year)   # assign a new value to the birth_year variable

age = 2024 - birth_year 

print('Your age is', age)
print('birth_year type:', type(birth_year))

Output
Enter your birth year: 2000
Your age is 24
birth_year type: <class ‘int’>

  • There is a shortcut for performing this conversion.

  • Upon receiving input from the user, we can immediately convert that value to an integer.

  • In the following code, the input() function returns a string, and the int() function converts this string to an integer.

birth_year = int(input('Enter your birth year: '))  

age = 2024 - birth_year 

print('Your age is', age)
print('Birth year type:', type(birth_year))

Output
Enter your birth year: 2000
Your age is 24
Birth year type: <class ‘int’>

Quick Check!

Create a variable and assign it the complex number \(4+5j\). Then, verify its type to confirm it is a complex number.```

Solution

number = float(input('Enter a number: '))
square = number**2
print('Square of', number, 'is', square)

Receipt Example#

  • You can use the input() function multiple times.

  • In the following example, the user enters the quantity of hamburgers and sodas, and the final receipt, including tax and tip, is printed.

    • The price of a hamburger is $5.

    • The price of a coke is $2.

    • The tip is 15%.

    • The tax is 10%.

  • Possible improvements:

    • You can also include the time and date by using the datetime module.

    • Consider rounding the tax, tip, and total amounts.

hamburger = int(input('Number of hamburgers:'))  
soda = int(input('Number of sodas:'))            

subtotal = hamburger*5+soda*2   
tip = subtotal*0.15
tax = subtotal*0.10
total = subtotal+tip+tax


print('Hamburger:',hamburger,'x 5= ',hamburger*5)
print('Soda     :',soda,'x 2= ',soda*2)
print('Tip      :         ',tip)
print('Tax      :         ',tax)
print('Total    :         ',total)

Output

Number of hamburgers:10
Number of sodas :20
Hamburger: 10 x 5= * 50
Soda : 20 x 2= 40
Tip : 13.5
Tax : 9.0
Total : 112.5

Whitespaces#

The following whitespace characters are frequently used in print statements for spacing.

  • \n: new line

    • Moves to the next line.

  • \t: tab

    • Inserts a tabulation

    • Inserts spaces up to the next tab stop, which occurs every 8th character.

  • \b: backspace

    • Deletes the character to the left.

  • \r: carriage return

    • Moves to the beginning of the line.

    • In Jupyter notebook, it does not delete any characters.

    • In Google Colab, it deletes all characters.

print('A\nB') # after A it moves to the next line
A
B
print('A       B')     # 7 spaces
print('A'+' '*7+'B')   # repetition of the string ' ' (one space) seven times
print('A\tB')          # tab
A       B
A       B
A	B
print('AA      B')      # 6 spaces
print('AA'+' '*6+'B')   # repetition of the string ' ' (one space) six times
print('AA\tB')          # tab
AA      B
AA      B
AA	B
print('AAA     B')       # 5 spaces
print('AAA'+' '*5+'B')   # repetition of the string ' ' (one space) five times
print('AAA\tB')          # tab
AAA     B
AAA     B
AAA	B
print('ABC\bD') # C is deleted by '\b'
ABCD
print('ABC\b\bD') # C and B are deleted by two '\b' s
ABCD

For Jupyter Notebook:

  • In the following code, after the character ‘C’, the carriage return \r moves the cursor to the beginning of the line, and ‘D’ overwrites ‘A’.

print('ABC\rD') # carriage return 
  • Output: DBC

  • Warning: In Google Colab, the output of the provided code is D.

Quick Check!

Find the output of the following code.

print('a\blas\nka')

Solution

las
ka

print()#

The print() function is a built-in function that displays output on the screen.

  • It has two significant parameters: sep and end.

sep parameter#

  • It is the separator parameter.

  • It determines what to insert between the comma-separated values in a print function.

  • The default value is a single space: ' '.

  • sep values are strings

name = 'Tom'
age = 25
print('A', age, 'B', name)            # by default there is one space between each value
A 25 B Tom
name = 'Tom'
print('A', age, 'B', name, sep='-')   #  values are separated by one '-' (dash)
A-25-B-Tom
name = 'Tom'
print('A', age, 'B', name, sep='***') #  values are separated by three '*'s (asterisk)
A***25***B***Tom

Quick Check!

Find the output of the following code.

number = 5
name = 'Joe'
print('A', number, 'B', name, sep='_' )

Solution

A_5_B_Joe

end parameter#

  • It determines what to print at the end of the output.

  • The default value of end parameter is the new line: '\n'.

  • end values are strings

Example

print('A')  # end='\n' by default, after printing A it moves to next line
print('B')  # end='\n' by default, after printing B it moves to next line
print('C')  # end='\n' by default, after printing C it moves to next line
print('D')  # end='\n' by default, after printing C it moves to next line
A
B
C
D

Example

print('A', end='--')  # end='--'           , after printing A it prints '--'
print('B')            # end='\n' by default, after printing B it moves to next line
print('C')            # end='\n' by default, after printing C it moves to next line
print('D')            # end='\n' by default, after printing C it moves to next line
A--B
C
D

Example

print('A', end='--')  # end='--'           , after printing A it prints --
print('B', end='+')   # end='+'            , after printing B it prints +
print('C')            # end='\n' by default, after printing C it moves to next line
print('D')            # end='\n' by default, after printing C it moves to next line
A--B+C
D

Example

print('A')            # end='\n' by default, after printing A it moves to next line
print('B', end='+')   # end='+'            , after printing B it prints +
print('C', end='?')   # end='+'            , after printing C it prints ?
print('D')            # end='\n' by default, after printing C it moves to next line
A
B+C?D

Quick Check!

Find the output of the following code.

print('A', end='5')
print('B')
print('C', end='#')
print('D', end='&')

Solution

A5B
C#D&

Examples#

Moving O (right)#

Use the print() function along with the letter ‘O’, the backspace ‘\b’, and the sleep() function from the time module to create a right-moving ‘O’.

  • Each print('\b O', end='') statement performs four actions:

    1. ‘\b’ deletes the ‘O’ that was printed before, moving the cursor one position to the left.

    2. Prints a space.

    3. Prints ‘O’.

    4. Since the end parameter is set to an empty string, it does not move to the next line.

import time
print('O', end='')           
time.sleep(1)
print('\b O', end='')     # Delete the 'O', print a space, then print 'O'.
time.sleep(1)
print('\b O', end='')
time.sleep(1)
print('\b O', end='')
time.sleep(1)
print('\b O', end='')
time.sleep(1)
print('\b O', end='')
time.sleep(1)
print('\b O', end='')

Moving O (left)#

Use the print() function along with the letter ‘O’, the backspace ‘\b’, and the sleep() function from the time module to create a left-moving ‘O’.

  • Each print('\b'*2 +'O', end='') statement performs four actions:

  1. The first ‘\b’ deletes the ‘O’ that was printed before, moving the cursor one position to the left.

  2. The second ‘\b’ moves the cursor one position to the left.

  3. Prints ‘O’.

  4. Since the end parameter is set to an empty string, the cursor does not move to the next line after printing the ‘O’.

import time
print(' '*5 + 'O', end='')     # Print 'O' after 5 spaces.    
time.sleep(1)
print('\b'*2 +'O', end='')     # Delete the 'O', print a space, then print 'O'.
time.sleep(1)
print('\b'*2 +'O', end='') 
time.sleep(1)
print('\b'*2 +'O', end='') 
time.sleep(1)
print('\b'*2 +'O', end='') 
time.sleep(1)
print('\b'*2 +'O', end='') 
time.sleep(1)
print('\b'*2 +'O', end='')