Keep getting Infinite loop in try-except block - python-3.x

I'm trying to make a list from user input but only if the input is numbers, and Im using a try except block with ValueError to display an error message and repeat, but I keep getting stuck in an infinite loop after the except block. I'm not familiar with error handling so I don't know how to fix it.
print('Input coords: x y z')
coords = input('Nether coords: ')
while True:
try:
coordslist = [int(i) for i in coords.split()]
except ValueError:
print('Please use numbers and proper format: x y z')
else:
from time import sleep
print('Converting', end='')
sleep(.5)
print('.', end='')
sleep(.5)
print('.', end='')
sleep(.5)
print('.')
convertedcoords = [i * 8 for i in coordslist]
print(convertedcoords)
break
finally:
print('Done')
I tried putting break in the except block but it just stopped entirely. Is it something with the while statement or am I formatting wrong in general?
Thanks

Related

Additional ValueError Exception

I am new with exceptions. Especially multiple exceptions.
I am able to excuse this code with positive numbers and raise the ValueError with negative numbers.
My issue is how to "add" an additional exception for ValueError if I were to use a non-integer.
I maybe making it hard than it is.
def findFirstEvenInteger(number_list):
"""Def even integer. The following rest of the function utilizes a modulo operator
that checks if the number is even."""
for element in number_list:
if element % 2 == 0:
return element
raise ValueError
nn = int(input("Please enter any length of elements: "))
meep = []
for x in range(nn):
x = int(input())
meep.append(x)
try:
print("The first even integer in the list: " + str(findFirstEvenInteger(meep)))
except ValueError:
print("All the number are odd")

While True looping the results of a 'if elif' statement

I'm experimenting with While loops and I encountered this:
CODE:
x = int(input('Guess the number 1-10'))
while True:
if (x == 8):
print('yay!')
break
else:
print('No No')
RESULT:
No No
No No
No No
No No
No No
No No
No No
No No
forever until I stop it...
Some people have suggested to use break, but I don't want to stop it on one try when they get it wrong, I want it to give multple tries until they get the right number. What can I do?
You want to ask the user for input in every iteration:
while True:
x = int(input('Guess the number 1-10'))
if (x == 8):
print('yay!')
break
else:
print('No No')

How to make the try function only print my message once

I've tried using the try() function, but when i try: and then type print() it just prints the message non-stop. how do i make it only print once?
def inputInt(minv, maxv, message):
res = int(input(message))
while (res > minv) and (res < maxv):
try:
print("Good job.")
except:
print("Invalid input")
Have you tried with break?
Take a look at this and this to get more clarification, but if you want that at the one time the try jumps to the except, it should print it once only, breakis the thing.
I must say this loop will go on forever as you are not changing res. Even if it goes in the try or in the except.
The code that could raise an exception should be in the try. The input should be inside the while. Catch expected exceptions in case an unexpected exception occurs. A naked except is bad practice and can hide errors.
Here's a suggested implementation:
def inputInt(minv, maxv, message):
while True: # Loop until break
try:
res = int(input(message)) # Could raise ValueError if input is not an integer.
if minv <= res <= maxv: # if res is valid,
break # exit while loop
except ValueError: # Ignore ValueError exceptions
pass
print("Invalid input") # if didn't break, input or res was invalid.
return res # Once while exits, res is good
x = inputInt(5,10,"enter number between 5 and 10: ")

Python code skips try/except clause

I am working on a class assignment in which I need to raise two exceptions.
First Exception: I am supposed to raise and handle an exception if a user's entry is less than 0 or greater than 100. The code should then ask the user for the digit again.
Second Exception: If a particular file is not found, the exception requests the file name and then search happens again.
In both cases, I cannot make the exception happen. In other words, if in the first exception, I enter a digit greater than 100 or less 0, the program continues and simply doesn't record anything for this entry. If I print the user's entry, I get "none" rather than the error message that the except clause should display. Likewise in the second exception, if the file is not found, the code simply stops executing rather than firing the exception.
I have tried manually raising an exception (as in this question/answer), but that creates a traceback which I do not want-- I just want the first exception to print the error message and call a function and the second to request input and call a function.
First exception:
def grade():
#input student's average grade
avgGrade = int(input("Enter average grade: "))
try:
if avgGrade > 0 and avgGrade < 100:
return avgGrade
except ValueError:
print("Grade must be numeric digit between 0 and 100")
grade()
Second exception:
def displayGrades(allStudents):
try:
#open file for input
grade_file = open(allStudents, "r")
#read file contents
fileContents = grade_file.read()
#display file contents
print(fileContents)
grade_file.close()
except IOError:
print("File not found.")
allStudents = input("Please enter correct file name: ")
displayGrades(allStudents)
Sounds like the exercise is to raise the exception and handle it. You really need a loop for continuation rather than recursion, e.g.:
def grade():
while True:
try:
avgGrade = int(input("Enter average grade: "))
if avgGrade < 0 or avgGrade > 100:
raise ValueError()
except ValueError:
print("Grade must be numeric digit between 0 and 100")
continue # Loop again
break # Exit loop
return avgGrade
But this is contrived for the purpose of the exception, as exceptions are not really needed in this case.
For your other example this is less contrived because the downstream function raises the exception, e.g.:
def displayGrades(allStudents):
while True:
try:
with open(allStudents, "r") as grade_file:
...
except IOError:
allStudents = input("Please enter correct file name: ")
continue
break
Though I would caution mixing arg passing and user input in the same function - usually the exception would be caught and handled where the user is originally providing the file name. So in this example, it would probably be the calling function.
For your first one, you have to raise it manually as python won't guess your logic and raise it for you.
def grade():
#input student's average grade
avgGrade = int(input("Enter average grade: "))
try:
if avgGrade > 0 and avgGrade < 100:
return avgGrade
else:
raise ValueError()
except ValueError:
print("Grade must be numeric digit between 0 and 100")
return grade()
For the second one, You have to return the value in the second call.
use return displayGrades(allStudents) instead of displayGrades(allStudents)
Try this:
def get_value(data_list, index):
return data_list[index]
# Sample list data
my_list = ['a', 'b', 'c']

Finding variables in a list

I am looking for error checking while searching a list, I ran into an issue with loading an unloading. I am looking for a way to have the script return what variable failed.
thisList = ['tacos', 'beer', 'cheese']
try:
x = thisList.index('beer')
y = thisList.index('eggs')
except ValueError as e:
DO AWESOME
At this point I would like single out y.
Thank you in advance.
As far as I know, this is not possible using a single try/except.
Instead, you could either use one try/except for each of the problematic lines...
try:
x = thisList.index('beer')
except ValueError as e:
print("x not found")
try:
y = thisList.index('eggs')
except ValueError as e:
print("y not found")
... or write yourself a helper function, like find for strings, that instead of raining an exception returns some special sentinel value that you can check afterwards.
def find(l, e):
try:
return l.index(e)
except ValueError:
return -1
x = find(thisList, 'beer') # x is 1
y = find(thisList, 'eggs') # y is -1

Resources