Can you add 2 global variables work inside a function while inside a while loop?

Question:

I am trying to build a function with a loop inside.

import time
#example

def infiniteloop2():
  while True:
    print("hi")
    time.sleep(1)  
  
infiniteloop2()

One thing I encountered was errors in adding 2 global variables.

import time
x=7
y=3
#example

def infiniteloop2():
  while True:
    print("hi")
    x=x+y
    time.sleep(1)  
    
infiniteloop2()

This code gives me an error. What am I missing?

Asked By: Andrew

||

Answers:

I’ve tried your code and I didn’t get any errors. Could you specify what error you get?

Edit: You need to add global before adding them.
Edit 2: If you want to change a global variable add global keyword inside the function. Hope this helps.

import time
x=7
y=3
#example

def infiniteloop2():
  while True:
    global x
    x=x+y
    print("hi")
    print(x+y)
    time.sleep(1)  
    
infiniteloop2()
Answered By: ademclk