Take user input and pass it to a Function in Python

avatar

Borislav Hadzhiev

Last updated: Aug 23, 2022

banner

Photo from Unsplash

Take user input and pass it to a Function in Python #

To take user input and pass it to a function:

  1. Use the input() function to take user input.
  2. Use the int() class to convert the input string to an integer if taking numeric input.
  3. Pass the input value in a call to the function.
main.py
# ✅ Take integers as user input and pass them to function def sum(a, b): return a + b a = int(input('Enter an integer: ')) # 👉️ 2 b = int(input('Enter another integer: ')) # 👉️ 2 print(sum(a, b)) # 👉️ 4 # --------------------------------------------------------- # ✅ Take strings as user input and pass them to function def concat(a, b): return a + b a = input('Enter a string: ') # 👉️ 'hello ' b = input('Enter another string: ') # 👉️ 'world' print(concat(a, b))

pass user input to function

The first example takes integers from user input and passes them to a function.

The input function takes an optional prompt argument and writes it to standard output without a trailing newline.

The function then reads the line from input, converts it to a string and returns the result.

The input() function is guaranteed to return a string, even if the user entered a number.

This is why we used the int() class to convert the strings to integers.

main.py
def sum(a, b): return a + b a = int(input('Enter an integer: ')) # 👉️ 2 b = int(input('Enter another integer: ')) # 👉️ 2 print(sum(a, b)) # 👉️ 4

The last step is to pass the user input values as arguments in a function call.

If you are taking strings from user input, you don't have to use the int() class.

main.py
def concat(a, b): return a + b a = input('Enter a string: ') # 👉️ 'hello ' b = input('Enter another string: ') # 👉️ 'world' print(concat(a, b))

pass user input to function strings

The concat function takes 2 strings and uses the addition (+) operator to concatenate them.

main.py
print('hello ' + 'world') # 👉️ 'hello world' print('one ' + 'two') # 👉️ 'one two'
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.