Cannot figure out why I am getting UnboundLocalError - python

I am trying to get the code to "except" a string for an int. - "length". When I put except ValueError, I get back "Please enter a number", but more error is added. I also added to except UnboundLocalError, but that does not seem to work. Please let me know what I'm doing wrong! Here is my code:
import random
import string
def RPG():
try:
RPG = ""
count = 0
length = int(
input("How many characters would you like in your password? "))
except (ValueError, UnboundLocalError):
print("Please enter a number.")
while count != length:
upper = [random.choice(string.ascii_uppercase)]
lower = [random.choice(string.ascii_lowercase)]
num = [random.choice(string.digits)]
symbol = [random.choice(string.punctuation)]
everything = upper + lower + num + symbol
RPG += random.choice(everything)
count += 1
continue
if count == length:
print(RPG)
# could also use string.printable for digits, letters, punct., and whitespace.
RPG()
Here is what I got back from using this code and typing a string instead of an integer into length:
How many characters would you like in your password? j
Please enter a number.
Traceback (most recent call last):
File "c:\Users\jkelly\Desktop\python\code.py", line 28, in <module>
pwd()
File "c:\Users\jkelly\Desktop\python\code.py", line 14, in pwd
while count != length:
UnboundLocalError: local variable 'length' referenced before assignment
I only expect the "Please enter a number", not the rest of the error, any help would be greatly appreciated. Thank you for your time!

The problem with the original code is that while count != length always gets executed, no matter the try-except part. This can be avoided by only proceeding to the while loop if an ValueError or UnboundLocalError was not raised. By initializing c=1 before the try-except and changing it to 0 only in the try part, the program only proceeds to the while loop if exception didn't happen.
import random
import string
def RPG():
c=0
try:
RPG = ""
count = 0
length = int(
input("How many characters would you like in your password? "))
except (ValueError, UnboundLocalError):
print("Please enter a number.")
c=1
if c==0:
while count != length:
upper = [random.choice(string.ascii_uppercase)]
lower = [random.choice(string.ascii_lowercase)]
num = [random.choice(string.digits)]
symbol = [random.choice(string.punctuation)]
everything = upper + lower + num + symbol
RPG += random.choice(everything)
count += 1
continue
if count == length:
print(RPG)
# could also use string.printable for digits, letters, punct., and whitespace.
RPG()

If you cause an error, the rest of the program will still be executed. You need to repeat the input, until you get the correct input.
import random
import string
def RPG():
while True:
try:
RPG = ""
count = 0
length = int(
input("How many characters would you like in your password? "))
break
except (ValueError, UnboundLocalError):
print("Please enter a number.")
while count != length:
upper = [random.choice(string.ascii_uppercase)]
lower = [random.choice(string.ascii_lowercase)]
num = [random.choice(string.digits)]
symbol = [random.choice(string.punctuation)]
everything = upper + lower + num + symbol
RPG += random.choice(everything)
count += 1
continue
if count == length:
print(RPG)
# could also use string.printable for digits, letters, punct., and whitespace.
RPG()

Related

How to exit loop when input is nothing

I'm trying to work out the average of numbers that the user will input. If the user inputs nothing (as in, no value at all) I want to then calculate the average of all numbers that have been input by the user upto that point. Summing those inputs and finding the average is working well, but I'm getting value errors when trying to break the loop when the user inputs nothing. For the if statement I've tried
if number == ''
First attempt that didn't work, also tried if number == int("")
if len(number) == 0
This only works for strings
if Value Error throws up same error
Full code below
sum = 0
while True :
number = int(input('Please enter the number: '))
sum += number
if number == '' :
break
print(sum//number)
Error I'm getting is
number = int(input('Please enter the number: '))
ValueError: invalid literal for int() with base 10:>
Any help much appreciated!
EDIT: Now getting closer thanks to the suggestions in that I can get past the problems of no value input but my calculation of average isn't working out.
Trying this code calculates fine but I'm adding the first input twice before I move to the next input
total = 0
amount = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
total = number + number
amount += 1
except:
break
total += number
print(total/amount)
Now I just want to figure out how I can start the addition from the second input instead of the first.
sum = 0
while True :
number = input('Please enter the number: '))
if number == '' :
break
sum += int(number)
print(sum//number)
try like this
the issue is using int() python try to convert input value to int. So, when its not integer value, python cant convert it. so it raise error. Also you can use Try catch with error and do the break.
You will always get input as a string, and if the input is not a int then you cant convert it to an int. Try:
sum = 0
while True :
number = input('Please enter the number: ')
if number == '' :
break
sum += int(number)
print(sum//number)
All of the answers dont work since the print statement referse to a string.
sum = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
except:
break
sum += number
print(sum//number)
including a user_input will use the last int as devisor.
My answer also makes sure the script does not crash when a string is entered.
The user has to always input something (enter is a character too) for it to end or you will have to give him a time limit.
You can convert character into int after you see it isn't a character or
use try & except.
sum = 0
i = 0
while True :
try:
number = int(input('Please enter the number: '))
except ValueError:
break
i += 1
sum += number
try:
print(sum/number)
except NameError:
print("User didn't input any number")
If you try to convert a character into int it will show ValueError.
So if this Error occurs you can break from the loop.
Also, you are trying to get the average value.
So if a user inputs nothing you get NameError so you can print an Error message.

How to ignore previous input?

I'm trying to create a while loop function with digits. Basically, my function is to keep adding up numbers until a non-digit is entered, and then I can break the loop. However, when I enter a non-digit input, the non-digit also get added to the equation and result in an error.
How can I exclude the non digit from the equation?
sum_num = 0
while True:
num = input("Please input a number: ")
sum_num = int(sum_num) + int(num)
if num.isdigit() != True:
print(sum_num)
break
I would be using a try except to catch the error. This makes it clear that you are avoiding such.
The reason your code doesn't work is because you are trying to add the "nondigit" (string) to a "digit" (integer) before you even check if this is possible, which you do after you've already caused the error. If you move the if statement above, your code will work:
sum_num = 0
while True:
num = input("Please input a number: ")
if num.isdigit() != True:
print(sum_num)
break
sum_num = int(sum_num) + int(num)
If you wrap it in a try/except it should do what you want.
while True:
num = input("Please input a number: ")
try:
sum_num = int(sum_num) + int(num)
except ValueError as ex:
print(sum_num)
break

How to Input numbers in python until certain string is entered

I am completing questions from a python book when I came across this question.
Write a program which repeatedly reads numbers until the user enters "done". Once done is entered, print out total, count, and average of the numbers.
My issue here is that I do not know how to check if a user specifically entered the string 'done' while the computer is explicitly checking for numbers. Here is how I approached the problem instead.
#Avg, Sum, and count program
total = 0
count = 0
avg = 0
num = None
# Ask user to input number, if number is 0 print calculations
while (num != 0):
try:
num = float(input('(Enter \'0\' when complete.) Enter num: '))
except:
print('Error, invalid input.')
continue
count = count + 1
total = total + num
avg = total / count
print('Average: ' + str(avg) + '\nCount: ' + str(count) + '\nTotal: ' + str(total))
Instead of doing what it asked for, let the user enter 'done' to complete the program, I used an integer (0) to see if the user was done inputting numbers.
Keeping your Try-Except approach, you can simply check if the string that user inputs is done without converting to float, and break the while loop. Also, it's always better to specify the error you want to catch. ValueError in this case.
while True:
num = input('(Enter \'done\' when complete.) Enter num: ')
if num == 'done':
break
try:
num = float(num)
except ValueError:
print('Error, invalid input.')
continue
I think a better approach that would solve your problem would be as following :
input_str = input('(Enter \'0\' when complete.) Enter num: ')
if (input_str.isdigit()):
num = float(input_str)
else:
if (input_str == "done"):
done()
else:
error()
This way you control cases in which a digit was entered and the cases in which a string was entered (Not via a try/except scheme).

Python3x Integer and String Input

I want the user to input a number
Give a number : he types "10" -but...
Give a number : he types "I want to type 10"
i want the program to just "count" the integer. Because if he types a string the program will stop
import random
goal = random.randrange(1,10)
n = 1
tries = 0
name = input("Dose to onoma sou ")
print("A game in Python")
while n != 0 :
value = int(input("madepse poio einai to noumero:"))
n = abs(value - goal)
print(value,n)
tries = tries + 1
if n >= 4 :
print("den eisai koda")
elif n > 0 and n <= 3 :
print("eisai koda")
else :
print("to vrikes")
print ("to score sou einai: ",tries)
skoros = str(tries)
score = open('score.txt', 'a')
score.write(name)
score.write(' ')
score.write(skoros)
score.write("\n")
score.close
This will take any input and pull the first number out of it. \d matches any digit 0-9, and + means "one or more".
import re
while True:
user = input('Enter a number: ')
match = re.search(r'\d+',user)
if match:
value = int(match.group(0))
break
else:
print("I didn't see a number in that response.")
print(value)
Well, you could just manually loop through the string and store the position of the number using isdigit().
The following approach expects the number to be the only one in the string (multi digit allowed):
start = None
stop = None
for i in range(len(input)):
c = input[i]
if c.isdigit():
if start == None:
start = i
stop = i
try:
number = int(input[start:stop])
catch:
print("invalid input")
EDIT:
I guess there would be some nice and easy Regex solution, but I'll leave my hands off of it, as I am not too experienced with it...

Python Traceback error in while loop after error handling

I have created a program in Python 3.4.1 that;
asks for a whole number,
verifies that it is a whole number,
throws an error message and asks for the number to be re-input if not a whole number,
once the number is verified adds it to a list,
ends if -1 is input.
mylist = []
def checkint(number):
try:
number = int(number)
except:
print ("Input not accepted, please only enter whole numbers.")
number = input("Enter a whole number. Input -1 to end: ")
checkint(number)
number = input("Enter a whole number. Input -1 to end: ")
checkint(number)
while int(number) != -1:
mylist.append(number)
number = input("Enter a whole number. Input -1 to end: ")
checkint(number)
This all works fine, except in one scenario. If a non-whole number is input e.g. p (which gives an error message) followed by -1 to end the program, I get this message:
Traceback (most recent call last):
File "C:/Users/************/Documents/python/ws3q4.py", line 15, in <module>
while int(number) != -1:
ValueError: invalid literal for int() with base 10: 'p'
I don't understand why this is happening, as the input of p should never get as far as
while int(number) != -1:
Here is a minimal example to illustrate the issue:
>>> def change(x):
x = 2
print x
>>> x = 1
>>> change(x)
2 # x inside change
>>> x
1 # is not the same as x outside
You need to fix the function to return something, and assign that to number in the outer scope:
def checkint(number):
try:
return int(number) # return in base case
except:
print ("Input not accepted, please only enter whole numbers.")
number = input("Enter a whole number. Input -1 to end: ")
return checkint(number) # and recursive case
number = input("Enter a whole number. Input -1 to end: ")
number = checkint(number) # assign result back to number
Also, it is better to do this iteratively rather than recursively - see e.g. Asking the user for input until they give a valid response.

Categories

Resources