Python Forum
Why can't this code work.
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why can't this code work.
#1
Sorry for not using the correct python terminology I'm new to this. 

Every time I run this code 

x=0

def phone():
    if brand =='yes':
        x=x+1

def other():
    if x==1:
        print('it work')
        
brand = input('try this')
print(brand)
print(x)
phone()
It does this when the input is yes 

Error:
Traceback (most recent call last):   File "E:\HT\computing\practical\task 3 course work\test\test.py", line 21, in <module>     phone()   File "E:\HT\computing\practical\task 3 course work\test\test.py", line 12, in phone     x=x+1 UnboundLocalError: local variable 'x' referenced before assignment
Reply
#2
Python won't let you accidentally change a global variable from a function. There is a way to simply modify the global variable, however it's discouraged generally speaking and very heavily on this particular site.

As for what you're really trying to accomplish here... it looks like this is homework. Can you specify the requirements?
Reply
#3
Typically you want to do this sort of thing with parameters and return statements:
def increment(a):
    return a + 1

x = increment(x)
The value of x is passed as a parameter to the increment function. Internally, increment calls that value 'a'. It adds one to that value and returns it. That become the value of increment(x) in the final line, which is then assigned to x.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  my simple code wont work! help! simon12323121 2 1,990 Sep-05-2021, 09:06 AM
Last Post: naughtyCat
  My code does not work as expected (pygame) rohes_kaugummi 1 1,532 Aug-26-2021, 03:13 PM
Last Post: deanhystad
  I wrote a code but it does not work out as expected chinitayao226 2 1,835 Sep-23-2020, 09:14 PM
Last Post: SnowwyWolf
  A program for backing up documents (doesnt work(code is inside)) Richard_SS 4 3,366 Jun-05-2019, 03:47 PM
Last Post: heiner55
  I Can't Get This Sorting Function In This LinkedList Code To Work JayJayOi 10 7,835 Jan-11-2018, 01:14 AM
Last Post: JayJayOi
  Need help with getting this voting eligiblity code to work Beastly 1 2,490 Aug-16-2017, 03:46 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

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