How to make the try function only print my message once - python-3.x

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: ")

Related

Why does having a return statement in my try block make the 'else' statement unreachable?

I'm learning exception handling in Python3 and can't seem to understand why the else statement in my if-else block is unreachable when using return in the try block.
def simple_division() -> float:
"""
:return: the quotient of a / b
"""
a, b = _git_int()
if a == 0:
return 0
else:
try:
return a / b
except ZeroDivisionError:
print("Uh, you can't divide by zero, bud.")
else:
print("This should execute if no exceptions are raised, right? but it doesn't")
finally:
print("This should execute either way.")
I spent some time debugging in order to figure out that the return statement in the try block was at fault... and I now understand that doing something like this circumvents the problem:
def simple_division() -> float:
"""
:return: the quotient of a / b
"""
a, b = _git_int()
if a == 0:
return 0
else:
try:
answer = a / b
except ZeroDivisionError:
print("Uh, you can't divide by zero, bud.")
else:
print("This DOES work")
return answer
finally:
print("This should execute either way.")
But I haven't yet found any documentation explaining why you can't have a return statement in a try block. Could someone explain this to me? What would be the best practice here?

Keep getting Infinite loop in try-except block

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

TypeError: method() takes 0 positional arguments but 1 was given

I wrote an input function python program,
But when run that code , IDE show that, "this function need to pass argument"
Even though ,I didn't declare any argument enter image description here
please help me how to solve this problem , Thank you in advance
list_number = list()
def input():
while True:
try:
number = input("Enter your number in to list = ")
if number == "Quit":
break
number = int(number)
list_number.append(number)
print(list_number)
except ValueError as e:
print(e)
def diagram():
display = ""
for i in list_number:
for j in range(i):
display = display +"#"
print(display)
display = ""
input()
diagram()
Several errors are noticed at glance:
mixture of namespace
You declared list_number as a global variable, but you cannot set value to it
directly insides a function. Instead, you can let the function return a value,
or use global statement to temporary allow a function to set a value to
a global variable temperary.
Read more on offical document, or search keyword python namespace for
relative articles.
name collision on builtin keyword
Some special word are reserved by python and could not be used as variable or
function name, input is amoung them.
BTW: The title of your question and example code layout is confusion! Follow the
tour to learn how to ask a better question and improve layout, so that people
can help you out.
Example code: though the test part has some bug I don't solved...
# remove: move it to a main progress for future design
# list_number = list()
# rename: input is a reserved name of builtins, pick another word
def myinput(*pargs):
if pargs:
for arg in pargs:
try:
yield int(arg)
except ValueError:
pass
else:
count = 0
while True:
# move out of `try` statement as it won't raise any exceptions
# imply lowercase for easier string comparison
userinput = input("Enter your number in to list: ").lower()
if userinput in ['quit', 'q']:
# for interactive, give user a response
print("Quit input procedure. Preparing Diagram...")
break
try:
number = int(userinput)
except ValueError:
# raise a error and the output will print to output by default
# there is no need to `print` an error
# and, for improve, you can raise a more specific message
# and continue your program
msg = "The program wants a number as input, please try again.\n"
msg += "Type `Quit` to exit input procedure."
print(msg)
continue
except KeyboardInterrupt:
msg = "You pressed Interrupt Keystroke, program exit."
print(msg)
return 0
# print a message and pass the value intercepted
count += 1
print("%d: number %d is added to queue." % (count, number))
yield number
def diagram(numbers):
# there is no need to iter a list by index
# and I am **not** sure what you want from your origin code
# if what you wnat is:
# join number with "#" sign
# then just use the builtins str.join method
# valid: is_list_like
if is_list_like(numbers):
numstr = map(str, numbers)
ret = "#".join(numstr)
else:
ret = "Nothing to export."
return ret
def is_list_like(obj):
"""fork from pandas.api.types.is_list_like,
search c_is_list_like as keyword"""
return (
# equiv: `isinstance(obj, abc.Iterable)`
hasattr(obj, "__iter__") and not isinstance(obj, type)
# we do not count strings/unicode/bytes as list-like
and not isinstance(obj, (str, bytes))
)
def main(*pargs):
# get a generator of user input
# if passed in values, accept parameter as user input for test
msgout = ""
if pargs:
# bug: test input not filtered by int() function
list_number = list(myinput(pargs))
print("Run builtin test module.")
else:
list_number = list(myinput())
count = len(list_number)
# process your input by whatever means you need
if count == 1:
msgout += "Received %d number from user input.\n" % count
else:
msgout += "Received %d numbers from user input.\n" % count
msgout += "The diagram is:\n%s" % diagram(list_number)
print(msgout)
def test():
"""simulate user input"""
userinputs = [
['a', 1, 5, 4, 9, 'q'],
[999, 'Quit'],
['q'],
]
for userinput in userinputs:
main(*userinput)
# test bug:
# 1. charactor is printed as output, too
if __name__ == "__main__":
# remove test() if you don't need it
test()
main()
Well I would change your function name from input to something else because you cannot have any function named anything from base python named in your function, This is probably the reason for your error.
Like the others said, input() is a builtin function in Python. Try this following code:
list_number = list()
def input_func():
while True:
try:
number = input("Enter your number in to list = ")
if number == "Quit":
break
number = int(number)
list_number.append(number)
print(list_number)
except ValueError as e:
print(e)
def diagram():
display = ""
for i in list_number:
for j in range(i):
display = display + "#"
print(display)
display = ""
input_func()
diagram()
Also, nice to note that try should be used more precisely only where the exception is expected to be thrown. You could rewrite input_func with that in mind, such as:
def input_func():
while True:
number = input("Enter your number in to list = ")
if number == "Quit":
break
try:
number = int(number)
except ValueError as e:
print(e)
else:
list_number.append(number)
print(list_number)

What is the difference between try/except and assert?

try:
def function_addition(x,y):
assert (y!=0)
total= x/y
return total
num1=float(input("Write a number :"))
num2=float (input("Write a second number:"))
result=function_addition(num1,num2)
assert (num2 !=0)
print (result)
except AssertionError:
print ("Error!Check your inputs")
I wrote the code above ,but I don't know why I got the same result when I do: except ZeroDivisionError:
So can I delete assert and replace it by except ZeroDivisionError ?
`
assert only check if a condition is true or not and throw an exception. A try/except block can run a few statements and check if any of them throw an exception so you can process it in the except part. Examples:
assert(1 == 2)
will give you an AsertionError.
try:
# some statements
# ...
except OSError as err:
#If an OSerror exception is thrown, you can process it here. For example:
print("OS error: {0}".format(err))
Your code will look like this:
def function_addition(x,y):
try:
assert (y!=0)
except:
raise ValueError('y is 0.')
total= x/y
return total
num1=float(input("Write a number :"))
num2=float (input("Write a second number:"))
try:
result=function_addition(num1,num2)
except ValueError as ve:
print(ve)
else:
print(result)
If you save it in a fun.py file and run it, you will have this output:
Write a number :1
Write a second number:2
0.5
# Run it again.
Write a number :0
Write a second number:0
y is 0.

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']

Resources