简体   繁体   中英

Unsupported operand type error when trying to multiply function parameter by an integer

I'm trying to make a simple function that takes an argument and multiplies it by an integer to return it multiple times. I attempted to do so with python 3 code that looks like this:

def user_input(x):
    print(x)


def repeat(y):
    return 5*y


repeat(user_input(input('Get input ')))

This code is supposed to take the argument y , in this case, the user_input function and multiply it by 5 so it should repeat 5 times. But whenever I run the program I get the following error:

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType' This error occurs in return 5*y and I understand that for some reason it interprets y as a None type. How would I have it interpreted as the appropriate type?

In programming languages, there are 2 things that we use functions for:
Their side affects
This includes things like:

  • printing to the screen
  • changing the value of a variable

Their return value
This is the value that functions "return" (just like mathematical functions).

Your problem

You have a function that has a side affect (printing to the screen), but no return value. If a function doesn't explicitly return anything, then python returns the value "None".

Solution

If you want to use the value from your first function as an argument with the second you could do something like this:

def user_input(x):
    return x

def repeat(x):
    return x*5

print(repeat(user_input("this is some user input")))

This will print out the return value of repeat, which is taking in the return value of user input, which is taking in a string.

Clean Up

As a side note, the user input function does nothing now, it simply returns the value that it is passed, so you can do the following:

def repeat(x):
    return x*5

print(repeat(input(">>> ")))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM