简体   繁体   中英

How to update a global variable based on number of user inputs?

I am trying to make a list of weights that are being brought to a trip to outer space. The way I have tried to show how many people are coming is this:

def flcr():
    try:
        Value1 = int(input())
    except ValueError:
        print("That was an incorrect format! Try again.")
        flcr()
    global x
    x = Value1

Then the user has to input the weights one by one. This is what I tried:

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()

When I input the weights though, I assume x just resets itself instead of subtracting itself by 1, so my input is infinite. I want to have a code that will allow me to enter the right amount of weights, so if I say there are 2 people coming, I can only input two weights.

If someone could help me out I would greatly appreciate it!

You don't need global before the comparison of x in that function.

Generally for me, I find it easier to refer to things I want global as globals()['x'] . That way I know nothing weird will happen. If globals() refers to global namespace, represented similar to a dictionary, globals()['x'] will always point to the global variable x.

If it is intended to be global, declare it globally before everything else. Outside all the functions, x = None , or x = 0, or x = ''.

There are a number of issues with your current implementation.

  1. You are using recursion to repeat getting inputs, which means you have a function ( flcr , amount1 ) that calls itself until valid inputs are provided. While this could work for user inputs, it is usually unnecessary. There are better ways to ask for user input until they give a valid response , and as mentioned in the comments , use a loop instead.

  2. The code x-1 does not update x . It actually does nothing because the result is not stored anywhere. If you are using an IDE or a linter, it could warn you that this is a "pointless statement". What you probably wanted was x = x - 1 . 在此处输入图像描述

  3. You are using globals to track how many weights need to be input and how many were input so far. While this could also work, it is again unnecessary. It would be simpler to just pass the number of flight crew members as a function argument .

Here's a solution that replaces the recursive calls with while loops and gets the number of people from one function, then passes the result of that to another function for getting the weights:

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)

Here's the sample output:

$ 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]

I know that your question was about how to update the global variable based on user inputs, ... but I think you have a global x because you were using recursive calls. A cleaner solution would be to get rid of both recursion and the global variable.

try to replace:

Value1 = int(input()) 

with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM