0

I'm having trouble figuring out why the "redo" variable isn't updating after my "check_user_input" function runs. The message confirming it ran always shows up, but the while loops dependent on "redo" never run. I'm not sure if the problem is that the variable isn't updating, or the code just isn't checking the variable for whatever reason. Here's my code:

import random 

redo = 0

def check_user_input(input):
    try:
        val = int(input)
    except ValueError:
        redo = 1
        print("Please enter a positive integer")
        
    
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']

print("Welcome to the Password Generator!")

nr_letters= input("How many letters would you like in your password?\n")
check_user_input(nr_letters)
print ("redo:",redo)
while(redo == 1):
    nr_letters= input("How many letters would you like in your password?\n")
    check_user_input(nr_letters)

redo = 0
nr_symbols = input(f"How many symbols would you like?\n")
check_user_input(nr_symbols)
print ("redo:",redo)
while(redo == 1):
    nr_symbols = input("How many symbols would you like in your password?\n")
    check_user_input(nr_symbols)
    
redo = 0
nr_numbers = input(f"How many numbers would you like?\n")
check_user_input(nr_numbers)
print ("redo:",redo)
while(redo == 1):
    nr_numbers= input("How many numbers would you like in your password?\n")
    check_user_input(nr_numbers)

passwordlength = nr_letters + nr_numbers + nr_symbols


nr_letters = int(nr_letters)
nr_symbols = int(nr_symbols)
nr_numbers = int(nr_numbers)


chars = ""
for x in range (0, nr_letters): 
  char = random.choice(letters) 
  chars += char

nums = ""
for y in range (0, nr_numbers):
  num = random.choice(numbers)
  nums += num

syms = "" 
for z in range (0, nr_symbols): 
  symb = random.choice(symbols)
  syms += symb

print(f"Here is your password: {chars}{nums}{syms}")

1 Answers1

0

check_user_input is referencing a local redo variable. If you want to access redo at the top level, you need to add global redo to your check_user_input function like so:

def check_user_input(input):
    global redo  # <-- This tells python to use the top level `redo` var
    try:
        val = int(input)
    except ValueError:
        redo = 1
        print("Please enter a positive integer")
Josh Clark
  • 964
  • 1
  • 9
  • 17