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 MagicMock
>>> input = MagicMock(side_effect=['Mark Watney', '42', '42.0', '42,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: 'Mark Watney'
>>>
>>> print(name)
Mark Watney
>>>
>>> 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: 42
>>>
>>> print(age)
42
>>> type(age)
<class 'str'>
>>>
>>> age = int(age)
>>> print(age)
42
>>>
>>> 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: 42.0
>>>
>>> age = int(age)
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: '42.0'
>>>
>>> age = float(age)
>>> print(age)
42.0
>>>
>>> type(age)
<class 'float'>

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

>>> age = input('What is your age: ')  #input: 42,0
>>>
>>> age = int(age)
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: '42,0'
>>>
>>> age = float(age)
Traceback (most recent call last):
ValueError: could not convert string to float: '42,0'
>>>
>>> float(age.replace(',', '.'))
42.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=['Mark', '42'])
>>>
>>>
>>> name = input('Type your name: ')
>>> name
'Mark'
>>>
>>> age = input('Type your age: ')
>>> age
'42'
>>>
>>> name = input('Type something else: ')
Traceback (most recent call last):
StopIteration

5.3.6. Assignments

# %% 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

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

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

# %% English
# 1. Ask user to input his/her name
# 2. Define `result: str` with text from user
# 3. `Mock` will simulate inputting of name `Mark` by user
# 4. Use `input()` function as normal
# 5. Run doctests - all must succeed

# %% Polish
# 1. Poproś użytkownika o wprowadzenie imienia
# 2. Zdefiniuj `result: str` z tekstem wprowadzonym od użytkownika
# 3. `Mock` zasymuluje wpisanie `Mark` przez użytkownika
# 4. Skorzytaj z funkcji `input()` tak jak normalnie
# 5. Uruchom doctesty - wszystkie muszą się powieść

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

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> assert input.call_count == 1, \
'Call `input()` function'
>>> assert input.call_args, \
'Ask user the question'

>>> result
'Mark'
"""

# Mock will simulate inputting of name `Mark` by user
from unittest.mock import Mock
input = Mock(side_effect=['Mark'])


# Ask user to type his/her name
# type: str
result = ...