0

My question is how do you allow a public chat value to affect a def for example:

c = 1
def dd():
    if c == 1:
        print("hi")
    else:
        c = input()
        dd()

dd()

When I run this I get an error since for the var "c" isn't defined. How can I fix this? (Keep in mind this is just a simple example of my problem)

Honestly I tried nothing since there is only 1 way to fix this issue.

  • *there is only 1 way to fix this issue* So you do know how to fix it... – Guy Jul 17 '23 at 12:12
  • You probably should not be using a global variable here, and you *certainly* should not be using recursion to implement a loop. – chepner Jul 17 '23 at 12:28

3 Answers3

0
c = 1
def dd():
    global c
    if c == 1:
        print("hi")
    else:
        c = input()
        dd()

dd()

Python, doesn't understand your previously assigned varibles in your function. If you would want understand of python that old variable, you must use in the function "global" thing. You can see the example above.

Sâlih
  • 1
  • 1
0

First of all, I am assuming by "def" you mean a Python function. I am also assuming that you want to print "Hi!" when the user sends input.

In that case, here is some example code:

c = 0
def dd():
  global c
  if c == 0:
    c = input("Message: ")
    dd()
  else:
    print("Hi! You said \""+c+"\".")

dd()

Also, if you knew how to solve this question, why did you ask?

Python Nerd
  • 171
  • 1
  • 9
  • Basically, for a function to affect a "public" variable, you must put `global some_variable` at the top of the function (the first lines of the function). The rest of the function can be used normally. – Python Nerd Jul 17 '23 at 12:23
0

This code raises an UnboundLocalError: this happens when you use a global variable in a function where in the same function also a local variable of the same name is defined. You define c in the function, whilst also using c to check its global value. This is by Python rules not allowed. You can use global c to use the globally defined c in the function, which does not yield an error. However, your current function does stay in an endless loop.

Lexpj
  • 921
  • 2
  • 6
  • 15
  • Nothing is "disallowed" here; the semantics are just not what the OP expects. – chepner Jul 17 '23 at 13:57
  • I should clarify: the way this code is written is disallowed: obviously because it does not run. The original matter is not in question: I do not state that what they are doing is disallowed. My context of disallowed talks about the `UnboundLocalError` that occurs. – Lexpj Jul 17 '23 at 15:14