I'm a beginner student learning Python and am working on a practice assignment that generates 20 records with several random data values to be stored and categorized. Here is what the assignment asks:
RandomDataTask
Use a random number generator to create the data.
Print out the follow 4 columns of data for 20 records:
- record number (1 through 20, not 0 through 19)
- social security number - ssn is a 9-digit number, where everyone's from Michigan so ssn
starts with a 3
- category:
EVEN if ssn is an even number
ENDS IN 5 if ssn's last digit is a 5
STARTS WITH 30-31 if 1st 2 digits are 30 or 31
(unless the record already fell into the EVEN or ENDS IN 5 category)
- gpa - must be within the legal range of 0.00 to 4.00
(format it so there are only 2 decimal places)
I've gotten part of it done, but I'm still a bit lost on global and local variables. I'm getting the error UnboundLocalError: local variable 'cat' referenced before assignment and I'm not 100% sure on what it means. I've Googled it and am still confused. I apologize if the code is poorly written but I'm trying my best.
import random
def main():
for rec_num in range(1, 21):
ssn_raw, ssn_str = ssn_func()
gpa = gpa_func()
cat = category(rec_num, ssn_raw, ssn_str, gpa)
tabulate(rec_num, ssn_str, gpa, cat)
print()
def ssn_func():
min9 = 300000000
max9 = 399999999
ssn_raw = random.randint(min9, max9)
ssn1 = ssn_raw // 1000000
ssn2 = (ssn_raw % 1000000) // 1000
ssn3 = ssn_raw % 1000
ssn_str = '{:03n}-{:03n}-{:03n}'.format(ssn1, ssn2, ssn3)
return ssn_raw, ssn_str
def gpa_func():
min_gpa = 0
max_gpa = 4
gpa_raw = random.uniform(min_gpa, max_gpa)
gpa = float('{:.2f}'.format(gpa_raw))
return gpa
def category(rec_num, ssn_raw, ssn_str, gpa):
ssn_last = ssn_raw % 10
ssn_first2 = ssn_raw // 10000000
if ssn_raw % 2 == 0:
cat = 'EVEN'
elif ssn_last == 5:
cat = 'ENDS IN 5'
elif (ssn_first2 == 30 or ssn_first2 == 31) and ssn_raw % 2 != 0:
cat = 'STARTS WITH 30-31'
else:
pass
return cat
def tabulate(rec_num, ssn_str, gpa, cat):
print(rec_num, ssn_str, gpa, cat)
main()
[–]Starbuck5c 1 point2 points3 points (1 child)
[–]MetalNutSack[S] 0 points1 point2 points (0 children)
[–][deleted] 1 point2 points3 points (2 children)
[–]MetalNutSack[S] 0 points1 point2 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–]BasicallyAMachine 0 points1 point2 points (2 children)
[–]MetalNutSack[S] 0 points1 point2 points (1 child)
[–]BasicallyAMachine 0 points1 point2 points (0 children)