Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Most pythonic way to take user input with a fucntion

I was wondering what the most pythonic way to take user input with a function is.

In the first example, I have what I see most often, which is to take input outside the function.

#Example1
def add(num1,num2):
    return num1+num2

num1=int(input('num1: '))
num2=int(input('num2: '))
add(num1,num2)

The second example takes user input directly inside the parenthesis when you call the function, which also works well.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#Example2
def add(num1,num2):
    return num1+num2
add(int(input('num1: ')),int(input('num2: ')))

However, if I try to take input from within the function I get an error. Is there a way to do this from within?

#Example3
def add(num1,num2):
    num1=int(input('num1: '))
    num2=int(input('num2: '))
    return num1+num2
add(num1,num2)

Which is the preferred way?

>Solution :

If you’re assigning to num1 and num2 only within the function, you don’t need to be passing them as arguments any more. Indeed, you can’t pass them as arguments because the code outside of the function doesn’t know what value has been entered for them. That’s why you’re getting an exception, the names num1 and num2 are unbound.

Just delete the arguments:

def add():                    # get rid of parameters here
    num1=int(input('num1: '))
    num2=int(input('num2: '))
    return num1+num2
add()                         # and don't try to pass any arguments

As for what is preferred, probably you want some variation on example 1. If you want the user input to be collected by a function, make it a separate function. The user-input collecting function can call the add function with the values, just like your global code did, without polluting the global namespace.

def add(num1,num2):            # this is unchanged from the early examples
    return num1+num2

def do_stuff():                # put the user input in another function
    num1=int(input('num1: '))
    num2=int(input('num2: '))
    print(add(num1,num2))      # or return here, or do whatever makes sense
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading