【问题标题】:How to use the 'input' method to get a function argument (python)如何使用“输入”方法获取函数参数(python)
【发布时间】:2017-09-17 20:03:06
【问题描述】:

所以我在 python 中有这段代码:

num = input("Choose your number?")
def distance_from_zero(num):
    if type(num) == int or type(num) == float:
        return abs(num)
    else:
        return "Nope"

我试图让函数参数 (num) 成为用户输入的数字。

但是每当我运行代码时,我都会输入参数,但它不会返回任何内容,并且代码结束。

我该如何解决这个问题?我不确定是代码的定位,还是别的什么。

【问题讨论】:

  • 您只定义了函数。你没有打电话。
  • 使用与num 同名的参数定义函数并不意味着参数会自动传递给函数。

标签: python function return


【解决方案1】:

您需要调用您的函数:

distance_from_zero(num)

更新

def distance_from_zero(num):
     if type(num) == int or type(num) == float:
         return abs(num)
     else:
         return "Nope"
num = input()
distance_from_zero(num)

在python3中input()返回一个字符串,如果你正在使用你需要将它转换成int

int(input())

只是一个观察,这似乎是工作功能定义:

def fun(num = int(input())):
  print("num:",num)

fun()

【讨论】:

  • 你当然不能这样定义函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 2023-04-02
  • 2011-11-22
  • 2022-08-17
  • 1970-01-01
  • 1970-01-01
  • 2014-09-13
相关资源
最近更新 更多