python - 如何将输入函数与 def 函数一起使用?

标签 python function

我是编程新手。我对 python 编码(使用 def 函数)有点问题。

所以基本上代码必须给出 2 个数字中较小的数字。

问题: 编写代码以执行以下任务:

  1. 定义一个函数 smaller_num 接受两个数字 确定并返回两者中较小的数。
    向用户询问两个号码
    使用函数判断较小的数并显示结果

所以我有用户输入而不是调用函数并在变量中添加值。

我的代码是这样的:

def smaller_num(x,y):
    if x>y:
        number= y
    else:
        number= x
    return number

smaller_num(x= input("Enter first number:-") ,y= input("Enter second number:-"))

print("The smaller number between " +  str(x) + " and " + str(y) + " is " + str(smaller_num))

如何纠正?现在它不起作用,因为没有定义“x”。但是我觉得我在 def 函数和 input 函数中都定义清楚了。那么我该如何解决这个问题呢?

感谢那些回答这个问题的人。

最佳答案

您实际上从未全局定义过 xy。您只在执行 def smaller_num(x, y) 时在函数中定义了它。

当你执行 smaller_num(x= input("Enter first number:-") ,y= input("Enter second number:-")) ,您并不是在创建名为 xy 的变量,您只是在为函数创建参数。

为了修复代码,在调用函数之前创建变量 xy:

def smaller_num(x, y): ## Can be rephrased to  def smaller_num(x, y):
    if x > y:          ##                          if x > y:
        number = y     ##                              return y
    else:              ##                          else:
        number = x     ##                              return x
return number

x = input("Enter first number:-")
y = input("Enter second number:-")
result = smaller_num(x, y)
print("The smaller number between " +  str(x) + " and " + str(y) + " is " + str(result))

您的代码无法正常工作的另一个原因是您没有将函数的返回值重新分配给变量。当您从函数返回 某些内容时,以及再次调用该函数时,您需要将值赋给一个变量,就像我这样:result = smaller_num(x, y).

当你调用你的函数时,你从来没有把值赋给一个变量,所以它被浪费了。


此外,您使用的是 Python 3 还是 2.7?在 python 3 中使用 input() 将返回一个字符串,要将其转换为整数,您可以在 input()int()函数。

关于python - 如何将输入函数与 def 函数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30729216/

相关文章:

vba - 基于行 ID 的特定列标题的行数据

python - 如何将文件中的单词插入列表中?

python - python ggplot 还在开发中吗?

python "If max number of steps is exceeded, break the loop"

Python pandas 夹板字符串,添加行,每列不同

解析函数字符串时的 JavaScript eval() "syntax error"

php - 使用 php 函数在字符串中搜索单词

python - 如何: Get a Python Scrapy to run a simple xpath retrieval

javascript - 清除全局函数内函数的超时

c - 弹丸运动程序 : What's wrong with this program?