如何根据用户输入的数量更新全局变量?

2024-10-01 22:40:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图列出一份外太空旅行中携带的重量清单。我试图展示有多少人会来的方式是:

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减去自身,因此我的输入是无限的。我想有一个代码,可以让我输入正确的权重,所以如果我说有两个人来,我只能输入两个权重

如果有人能帮我,我将不胜感激


Tags: anformatinputthatdef权重printtry
3条回答

在该函数中比较x之前,不需要全局

通常对我来说,我发现将我想要全局的东西称为globals()[‘x’]更容易。这样我就知道不会有什么奇怪的事情发生。如果globals()引用类似于字典的全局命名空间,globals()['x']将始终指向全局变量x

如果它是全球性的,那么首先要在全球范围内声明它。在所有函数之外,x = None,或x=0,或x=''

您当前的实现存在许多问题

  1. 您正在使用递归重复获取输入,这意味着您有一个函数(flcramount1),该函数在提供有效输入之前一直调用自身。虽然这可以用于用户输入,但通常是不必要的。有更好的方法来ask for user input until they give a valid response,作为mentioned in the comments,使用循环代替

  2. 代码x-1不更新x。它实际上什么也不做,因为结果没有存储在任何地方。如果您使用的是IDE或linter,它可能会警告您这是一个“无意义的语句”。你可能想要的是x = x - 1enter image description here

  3. 您正在使用globals来跟踪需要输入多少权重以及到目前为止输入了多少权重。虽然这个也可以工作,但它同样是不必要的。将飞行机组成员的数量作为函数参数传递会更简单

下面是一个解决方案,它用while循环替换递归调用,并从一个函数中获取人数,然后将结果传递给另一个函数以获取权重:

def get_num_people():
    while True:
        try:
            return int(input("How many people are coming? "))
        except ValueError:
            print("That was an incorrect format! Try again.")

def get_weights(num_weights):
    print("How much is each flight crew member bringing on the trip?")
    all_weights = []
    while len(all_weights) < num_weights:
        try:
            all_weights.append(int(input()))
        except ValueError:
            print("That was an incorrect format! Try again.")

    print(all_weights)
    return all_weights

num_people = get_num_people()
get_weights(num_people)

以下是示例输出:

$ python test.py
How many people are coming? 2
How much is each flight crew member bringing on the trip?
12
33
[12, 33]

$ python test.py
How many people are coming? 3
How much is each flight crew member bringing on the trip?
abc
That was an incorrect format! Try again.
89
def
That was an incorrect format! Try again.
100
4
[89, 100, 4]

我知道你的问题是关于如何根据用户输入更新全局变量。。。但是我认为您有一个全局x,因为您使用的是递归调用。一个更干净的解决方案是去掉递归和全局变量

尝试替换:

Value1 = int(input()) 

与:

Value1 = int(str(input("")))

相关问题 更多 >

    热门问题