-1

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?

Also, my question was closed due to an apparent duplicate. There is a difference because there is a loop, and instead of print functions there is an + operator. unless you are the person who is reviewing this, you can ignore this part.

Andrew
  • 27
  • 8

1 Answers1

0

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()
ademclk
  • 112
  • 1
  • 3
  • 10
  • 1
    oops! wrong code! The right code is 2 variables. I tried x=x+y inside the loop and it gave an error. – Andrew Aug 03 '22 at 16:22