nameerror - Python 3.7 代码不会循环并返回名称错误
问题描述
首先,我对编程很陌生,所以请耐心等待。我当前的代码存在以下问题,我无法弄清楚。我无法根据用户输入结束循环。现在代码返回名称错误。有谁知道我该如何解决这个问题?感谢您的时间。
def gcd(a,b):
start_over = "true"
while start_over == "true":
while True:
a = int(input("Enter your first positive whole number: "))
if a < 1 :
print(a ,"IS NOT A POSITIVE WHOLE NUMBER")
print("")
continue
else:
break
while True:
b = int(input("Enter your second positive whole number: "))
if b < 1 :
print(b ,"IS NOT A POSITIVE WHOLE NUMBER")
print("")
continue
else:
break
if (b==0):
return a
else:
return gcd(b,a % b)
gcf = gcd(a,b)
print("the GCD of", a,"and", b,"is: ", gcf)
redo_program = input("To perform another computation type Y/Yes or to quit type N/No: ").lower()
if redo_program == "y" or "yes":
start_over = "true"
else:
start_over ="null"
print("GOODBYE")
gcd(a,b)
解决方案
您的代码混淆并交织了两个部分。大概你想
- 向用户询问两个号码
- 递归计算它们的最大公约数
但是该gcd
函数既需要两个数字作为参数,也要求用户输入数字(从而忽略参数),并且还递归调用自身。
名称错误来自最后一行,gcd(a, b)
您试图获取的 GCDa
和b
- 但a
尚未b
输入(因为您只在函数内部执行此操作)。
即使该位有效,您的函数也会计算出,为了计算两个较大数字的 GCD,它需要事先计算两个较小数字的 GCD。到目前为止,一切都很好 - 除了您从未实际计算较小数字的 GCD,而是要求用户提供新的、不相关的数字对来计算 GCD,而忘记计算前一对数字。
另请注意,您的if b == 0
条件return
在两个分支中都有,因此不会gcd
到达函数中低于它的代码。
所以要做你想做的事,试着改变你的代码以适应这个伪代码:
function gcd(a, b)
calculate GCD without asking user anything
presume user wants to continue
loop while user wants to continue
ask for two numbers
calculate GCD
print result
ask the user if they want to continue
此外,你还有一些奇怪的字符串。这并不是一个真正的错误,除非我错过了一些让字符串"true"
指示真值或"null"
无值的字符串,但它是非常非常糟糕的形式 - 在 Python 中有特殊值True
和None
这些角色(你甚至True
正确使用中while True
)。
推荐阅读
- react-native - React Native:文本字符串必须在
零件 - javascript - 如何抽象现有的 firebase CRUD 操作,以便能够迁移到 node.js 中的另一个数据库
- amazon-s3 - 如何列出存储桶中所有对象的版本及其各自的元数据 (x-amz-meta-version)
- django - Django查询集过滤器基于父级的父级
- c++ - 我的 c++ 程序没有输入就终止了。我该怎么办?
- c# - 我的数据库项目的gridview和更新仍然有问题
- javascript - 抛出“requirejs is not defined”错误怎么办?
- aws-lambda - 我们如何强制 AWS Lamda 在 VPC 中安全运行?
- c# - Crystal Report 仅在底部显示总和
- java - SpringBoot 应用 NoClassDefFoundError