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
  Make Groups with the List Elements quest 2 241 Jul-11-2021, 09:58 AM
Last Post: perfringo
Question How to make a 3D List of Excel Spreadsheets? chatguy 4 575 Jan-24-2021, 05:24 AM
Last Post: buran
  Finding global extrema of oscillating function JoeRogan 0 408 Dec-22-2020, 01:49 AM
Last Post: JoeRogan
  Undo interation to make a single list? DustinKlent 2 518 Nov-29-2020, 03:41 AM
Last Post: DustinKlent
  How do i make a new lists out of an list ozezn1 1 479 Oct-28-2020, 10:19 PM
Last Post: Gribouillis
  Parameters aren't seen inside function Sancho_Pansa 8 740 Oct-27-2020, 07:52 AM
Last Post: Sancho_Pansa
  Make list of dates between today back to n days Mekala 3 626 Oct-03-2020, 01:01 PM
Last Post: ibreeden
  Spyder Quirk? global variable does not increment when function called in console rrace001 1 446 Sep-18-2020, 02:50 PM
Last Post: deanhystad
  How to make a list of values from a dictionary list? faryad13 2 662 Sep-03-2020, 03:45 PM
Last Post: faryad13
  List index out of range error when attempting to make a basic shift code djwilson0495 4 908 Aug-16-2020, 08:56 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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