SO, I'm a complete noob when it comes to programming, only just started learning python over the weekend gone. Anyway, as a challenge from one of the Youtube tutorials, I was suppose to write a program that can find all the numbers from defined range, that when divided by 4 will give me 0 reminder and then they will be listed. so i took it a bit further and below is what I've got so far.
# Program that let's you find all numbers in any range defined by user
# that can be divided without any reminder by the number also defined by user
print('Find all numbers in range...')
while True:
try:
x = int(input('From: ')) # begining of the range
y = int(input('.. to: ')) # end of the range
z = int(input('.. that can be divided by: ')) # value of the number to divide by
except ValueError: # in case of a nonint input
print('You should enter a valid number!')
continue
for a in range(x, y):
try:
if a % z == 0:
print(a, [a / z], end = ' ')
except ZeroDivisionError: # issue with implementing this exception
pass
To the point when instead of using pass statement, I try to do
print('You can\'t divide by 0!!') # or similar
it prints the string (x, y) times. Any suggestions? Many thanks in advance
The problem is that you are try/except'ing inside the for loop. If you don't want the program to terminate upon hitting the exception, just break the loop after printing your warning.
print('Find all numbers in range...')
while True:
try:
x = int(input('From: ')) # begining of the range
y = int(input('.. to: ')) # end of the range
z = int(input('.. that can be divided by: ')) # value of the number to divide by
except ValueError: # in case of a nonint input
print('You should enter a valid number!')
continue
for a in range(x, y):
try:
if a % z == 0:
print(a, [a / z], end = ' ')
except ZeroDivisionError:
print ("Cannot divide by zero")
break