5.3. String Input

  • input() always returns str

  • Good practice: add space at the end of prompt

  • Good practice: always .strip() text from user input

  • Good practice: always sanitize values from user prompt

5.3.1. SetUp

Simulate user input (for test automation):

>>> from unittest.mock import Mock
>>> input = Mock(side_effect=['Alice', '30', '30.0', '30,0'])

5.3.2. Input Str

input() function argument is prompt text, which "invites" user to enter specific information. Note colon-space (": ") at the end. Space is needed to separate user input from prompt. Without it, user inputted text will be glued to your question.

>>> name = input('What is your name: ')  #input: 'Alice'
>>>
>>> print(name)
Alice
>>>
>>> type(name)
<class 'str'>

5.3.3. Input Int

input() always returns a str. To get numeric value type conversion to int is needed.

>>> age = input('What is your age: ')  #input: 30
>>>
>>> print(age)
30
>>> type(age)
<class 'str'>
>>>
>>> age = int(age)
>>> print(age)
30
>>>
>>> type(age)
<class 'int'>

5.3.4. Input Float

Conversion to float handles decimals, which int does not support:

>>> age = input('What is your age: ')  #input: 30.0
>>>
>>> age = int(age)
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: '30.0'
>>>
>>> age = float(age)
>>> print(age)
30.0
>>>
>>> type(age)
<class 'float'>

Conversion to float cannot handle comma (',') as a decimal separator:

>>> age = input('What is your age: ')  #input: 30,0
>>>
>>> age = int(age)
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: '30,0'
>>>
>>> age = float(age)
Traceback (most recent call last):
ValueError: could not convert string to float: '30,0'
>>>
>>> float(age.replace(',', '.'))
30.0

5.3.5. Automated Input

  • mock - an object with pretends to be something else

  • mocks are used in testing, to simulate output

>>> from unittest.mock import Mock
>>> input = Mock(side_effect=['Alice', '30'])
>>>
>>>
>>> name = input('Type your name: ')
>>> name
'Alice'
>>>
>>> age = input('Type your age: ')
>>> age
'30'
>>>
>>> name = input('Type something else: ')
Traceback (most recent call last):
StopIteration

5.3.6. Assignments

# %% About
# - Name: Type Str Input
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Ask user to input his/her name
# 2. Define `result: str` with text from user
# 3. Use `input()` function
# 4. Run doctests - all must succeed

# %% Polish
# 1. Poproś użytkownika o wprowadzenie imienia
# 2. Zdefiniuj `result: str` z tekstem wprowadzonym od użytkownika
# 3. Skorzystaj z funkcji `input()`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'

>>> assert type(result) is str, \
'Variable `result` has an invalid type; expected: `str`.'

>>> assert input.call_count == 1, \
'Function `input` was not called; call function using `input(...)`.'

>>> assert input.call_args, \
'Function `input` was not called with proper prompt; call function using `input(prompt)`.'

>>> result
'Alice'
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports
from unittest.mock import Mock
input = Mock(side_effect=['Alice'])

# %% Types
result: str

# %% Data

# %% Result
result = ...

# %% About
# - Name: Type Str Input
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Ask user to input his/her age
# 2. Define `result: int` with text from user (as int)
# 3. Use `input()` function
# 4. Run doctests - all must succeed

# %% Polish
# 1. Poproś użytkownika o wprowadzenie wieku
# 2. Zdefiniuj `result: int` z tekstem wprowadzonym od użytkownika (jako int)
# 3. Skorzystaj z funkcji `input()`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'

>>> assert input.call_count == 1, \
'Function `input` was not called; call function using `input(...)`.'

>>> assert input.call_args, \
'Function `input` was not called with proper prompt; call function using `input(prompt)`.'

>>> assert type(result) is int, \
'Variable `result` has an invalid type; expected: `int`.'

>>> result
20
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports
from unittest.mock import Mock
input = Mock(side_effect=['20'])

# %% Types
result: int

# %% Data

# %% Result
result = ...