Python Forum
How to make global list inside function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to make global list inside function
#1
from output import welcome, more, byebye, summary, invalid, emptylist, close
def food():
global choice
    x = 1
    while x > 0 and x <= 15:
        try:
            more()
            x = int(input("Enter your choice: "))
            choice.append(x)
        except:
            invalid()
    else:
        choice.remove(20)
        if len(choice) == 0:
            emptylist()
        else:
            choice.sort()
            print ("This is your selection:",choice)
            close()
print(choice)
the code is shown above but I can't do "print(choice)"
Larz60+ write Nov-25-2020, 09:14 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.

I added for you this time. Please use bbcode tags on future posts.
Reply
#2
you need to indent lines 1 and 19
you should avoid using globals, instead, return choice.
example:
def food():
    x = 1
    while x > 0 and x <= 15:
        try:
            more()
            x = int(input("Enter your choice: "))
            choice.append(x)
        except:
            invalid()
    else:
        choice.remove(20)
        if len(choice) == 0:
            emptylist()
        else:
            choice.sort()
            print ("This is your selection:",choice)
            close()
    return choice

print(food())
Reply
#3
Alright. Thank you so much but the actual problem is as below:

#main Module

from output import menu

from userinput import userinfo, orders, food

menu()
userinfo()
orders()
print (choice)

#userinput Module

from output import welcome, more, byebye, summary, invalid, emptylist, close

def userinfo():
    x = input("Enter your name: ").title()
    y = input("Enter your phone number: ")
    a = welcome(x)

choice = []

def orders():
    order = int(input("Enter your choice: "))
    while order >= 0:
        try:
            if order == 0:
                byebye()
                order = -1
            elif order >= 1 and order <= 15:
                choice.append(order)
                food()
                order = -1
            elif order == 16:
                summary()
                order = -1
            elif order >= 17:
                emptylist()
                order = int(input("Enter your choice: "))
        except:
            invalid()

def food():
    x = 1
    while x > 0 and x <= 15:
        if x > 0 and x <= 15:
            more()
            x = int(input("Anymore? "))
            choice.append(x)
        else:
            invalid()
    else: 
        choice.remove(20)
        if len(choice) == 0:
            emptylist()
        else:
            choice.sort()
            close()
            print ("This is your selection:",choice)

#output Module

#Order Menu
def menu():
    print (
        '''
                   Welcome to Sonic Kitchen Takeaway                     
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   |                 ~~Please select your choice~~                      |
   | -----Meat--RM3.00/dish              -----Rice-----                 |
   | [1] Butter Chicken                  [11] Half Rice (RM1.00)        |
   | [2] Sweet and Sour Chicken          [12] Full Rice (RM2.00)        |
   | [3] Steam Fish                                                     |  
   | [4] Butter Pork                     -----Soup--RM4.00/dish         | 
   | [5]Gilled Pork                      [13] Chicken Soup              |
   |                                     [14] Fish Soup                 |  
   | -----Vegetable--RM2.00/dish         [15] Vegetable Soup            |  
   | [6] Fried Cabbage                                                  |  
   | [7] Fried Kale                      [16] Order Summary             |  
   | [8] Fried Spinach                                                  |
   | [9] Tomato Egg                                                     |
   | [10]Fried Bean Sprout               [0] Exit                       |
   ----------------------------------------------------------------------
   Operating Hour: 10am - 7pm     Contact Number: 019 - 1385 3375        
       '''
    )
    return ("")

def welcome(x):
    print("Hi,",x,'.Welcome to Sonic Kitchen delivery.')

def more():
    print("Thank you! Enter 20 to exit from order.")

def byebye():
    print("Thank you for visiting Sonic Kitchen Denivery!")

def summary():
    print("View Summary")

def invalid():
    print("Invalid input. Try Again.")

def emptylist():
    print("You did not order anything.")

def close():
    print("Thank you for ordering Sonic Kitchen!")
So with the three modules. I run the MAIN module but the error state is as below:
NameError: name 'choice' is not defined
Reply
#4
Line 10, try:

print(userinput.choice)
Reply
#5
Nope. It is still error
#Main Module

from output import menu

from userinput import userinfo, orders, food

menu()

userinfo()

orders()

print(userinput.choice)
Error:
Traceback (most recent call last): File "C:\Users\Owner\Desktop\Python Assignment\main.py", line 13, in <module> print(userinput.choice) NameError: name 'userinput' is not defined
Sad Sad Sad
Reply
#6
I know nothing about the code above but indeed in this snippet there is no userinput defined.

from userinput import userinfo, orders, food
Maybe you should import from userinput also choice?
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#7
It is solved with import choice from userinput. Thank you so much.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why doesn't list require global keyword? johnywhy 9 652 Jan-15-2024, 11:47 PM
Last Post: sgrey
  with open context inside of a recursive function billykid999 1 552 May-23-2023, 02:37 AM
Last Post: deanhystad
  Why do I have to repeat items in list slices in order to make this work? Pythonica 7 1,258 May-22-2023, 10:39 PM
Last Post: ICanIBB
  How do I call sys.argv list inside a function, from the CLI? billykid999 3 753 May-02-2023, 08:40 AM
Last Post: Gribouillis
  help me to make my password list in python >>> Oktay34riza 0 552 Dec-23-2022, 12:38 PM
Last Post: Oktay34riza
  Function global not readable by 'main' fmr300 1 1,297 Jan-16-2022, 01:18 AM
Last Post: deanhystad
  Need to parse a list of boolean columns inside a list and return true values Python84 4 2,037 Jan-09-2022, 02:39 AM
Last Post: Python84
  Make Groups with the List Elements quest 2 1,935 Jul-11-2021, 09:58 AM
Last Post: perfringo
Question How to make a 3D List of Excel Spreadsheets? chatguy 4 2,679 Jan-24-2021, 05:24 AM
Last Post: buran
  Finding global extrema of oscillating function JoeRogan 0 1,618 Dec-22-2020, 01:49 AM
Last Post: JoeRogan

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020