-1
import random
people=0
def intake (testage):
    if testage <= 18:
        print("Person accepted!")
        people=people+1
    else:
        print("Person Denied!")
while people <= 150:
    age=random.randint(0,81)
    intake(age)
print("At capacity!")

on line 2 the variable people comes up with errors if I define it or if I don't define it

  • Note that using globals is a really bad idea - it makes code hard to read, and hard to use. Instead, return a value from your function and use that to do something. If you need to have data accessible from a range of functions, consider making a class. – Herker Feb 09 '22 at 09:09

2 Answers2

1

You're assigning to the variable people from inside the function intake. This makes the function intake's version of people different from the one that's defined outside the function.

To use the same people inside intake, you need to declare people as global.

import random
people=0
def intake (testage):
    global people # declare people as global
    if testage <= 18:
        print("Person accepted!")
        people=people+1 # now, people is the same one as above
    else:
        print("Person Denied!")
while people <= 150:
    age=random.randint(0,81)
    intake(age)
print("At capacity!")
theoctober19th
  • 364
  • 3
  • 13
0
import random;

people=0;

def intake (testage):
    global people
    if testage <= 18:
        print("Person accepted!");
        people += 1;
    else:
        print("Person Denied!");
        
while people <= 150:
    age=random.randint(0,81);
    intake(age);
print("At capacity!")
Thang Le
  • 21
  • 2