我是编程新手。我对 python 编码(使用 def 函数)有点问题。
所以基本上代码必须给出 2 个数字中较小的数字。
问题: 编写代码以执行以下任务:
- 定义一个函数 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 函数中都定义清楚了。那么我该如何解决这个问题呢?
感谢那些回答这个问题的人。
最佳答案
您实际上从未全局定义过 x
和 y
。您只在执行 def smaller_num(x, y)
时在函数中定义了它。
当你执行 smaller_num(x= input("Enter first number:-") ,y= input("Enter second number:-"))
,您并不是在创建名为 x
和 y
的变量,您只是在为函数创建参数。
为了修复代码,在调用函数之前创建变量 x
和 y
:
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/