我正试图列出一份外太空旅行中携带的重量清单。我试图展示有多少人会来的方式是:
def flcr():
try:
Value1 = int(input())
except ValueError:
print("That was an incorrect format! Try again.")
flcr()
global x
x = Value1
然后用户必须逐个输入权重。这就是我所尝试的:
def enter():
print("How much is each flight crew member bringing on the trip? Enter one entry at a time, this will be Earth weight.")
amount1()
def amount1():
try:
if x > 0:
equation1 = [float(input())]
x - 1
amount1()
else:
print(listFlcr)
except ValueError:
print("That was an incorrect format! Try again.")
enter()
当我输入权重时,我假设x
只是重置自身,而不是用1减去自身,因此我的输入是无限的。我想有一个代码,可以让我输入正确的权重,所以如果我说有两个人来,我只能输入两个权重
如果有人能帮我,我将不胜感激
在该函数中比较x之前,不需要全局
通常对我来说,我发现将我想要全局的东西称为
globals()[‘x’]
更容易。这样我就知道不会有什么奇怪的事情发生。如果globals()引用类似于字典的全局命名空间,globals()['x']将始终指向全局变量x如果它是全球性的,那么首先要在全球范围内声明它。在所有函数之外,
x = None
,或x=0,或x=''您当前的实现存在许多问题
您正在使用递归重复获取输入,这意味着您有一个函数(
flcr
,amount1
),该函数在提供有效输入之前一直调用自身。虽然这可以用于用户输入,但通常是不必要的。有更好的方法来ask for user input until they give a valid response,作为mentioned in the comments,使用循环代替代码
x-1
不更新x
。它实际上什么也不做,因为结果没有存储在任何地方。如果您使用的是IDE或linter,它可能会警告您这是一个“无意义的语句”。你可能想要的是x = x - 1
。您正在使用globals来跟踪需要输入多少权重以及到目前为止输入了多少权重。虽然这个也可以工作,但它同样是不必要的。将飞行机组成员的数量作为函数参数传递会更简单
下面是一个解决方案,它用
while
循环替换递归调用,并从一个函数中获取人数,然后将结果传递给另一个函数以获取权重:以下是示例输出:
我知道你的问题是关于如何根据用户输入更新全局变量。。。但是我认为您有一个全局
x
,因为您使用的是递归调用。一个更干净的解决方案是去掉递归和全局变量尝试替换:
与:
相关问题 更多 >
编程相关推荐