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
You can try to raise an exception Check the below sample
#!/usr/bin/env python3
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])
except ZeroDivisionError as err: # issue with implementing this exception
raise Exception("Cannot divide by zero", err)
how you call answering your own question? so I tried one thing that i haven't earlier instead of pass I used break statement and vuala. next I will try to make it write the results into a simple .txt file, here is the code so far for anybody interested
# 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: # in case of variable z = 0
print('You shoudln\'t divide by 0!!')
break
break
You could validate the divisor entered by the user before entering the loop. Then you do not need to check for division by zero errors in the for loop:
while True:
try:
x = int(input('From: '))
y = int(input('.. to: '))
z = int(input('.. that can be divided by: '))
if z == 0:
print('You can\'t divide by 0!!')
continue
except ValueError: # in case of a nonint input
print('You should enter a valid number!')
continue
for a in range(x, y):
if a % z == 0:
print(a, [a / z], end = ' ')
print()
In your code, the only way that the ZeroDivisionError could be catched is if the content of the variable z is 0. At this point, I'm noticing some problems in your code :
Before passing x and y to range() function, you should ensure that x < y
You should always ensure that z is not null and then the script will just check wether it can divide in the way you want it or not.
Here is my proposition :
# 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
numbers = range(x, y)
if len(numbers) > 0 and z != 0: #Check if the list is empty and if the divider is not null
for number in numbers:
if number % z == 0:
print(number, [number / z])
else:
print("Invalid numbers passed")`
Related
I'm new to python and I'm looking to code a small calculator for divisions, that includes while loops and if conditionals
My code looks like this:
a = input('first number')
while type(a)!=int:
try:
a=int(a)
print('imput number is correct ',a)
except:
print('Imput data is not correct ')
a=input('first number')
b = input('second number')
while type(b)!=int and b!=0:
try:
b=int(b)
print('Imput data is correct',b)
except:
print(' imput data is not a number, please only imput numbers ')
b=input('second number')
while b==0:
try:
c=1/b
print('imput number is correct ',b)
except ZeroDivisionError:
print('Cant divide by 0')
b=input('second number again')
if type(a)==int and type(b)==int and b!=0:
c=a/b
print('the result is: ',c)
The program suddenly ends after you imput 0 a second time in the second number space, but the proccess should keep asking for a value that is a number and different from 0
After b=input('second number again') is executed, b is a string, so b == 0 is False(a string is never equal to an integer).
You'll find this easier if you write a common function to get the user input. Something like this:
def get_input(prompt, nonZero=False):
while True:
try:
if (n := int(input(prompt))) == 0 and nonZero:
raise ValueError('Value must be non-zero')
return n
except ValueError as e:
print(e)
a = get_input('Input first number: ')
b = get_input('Input second number: ', True)
print(a/b)
this is my problem
Can you help me?
Thanks
Write a program that asks the user to repeatedly ask for a number until the word "done" is typed, then by entering "done" the three values of "sum of numbers", "number of numeric inputs", "average of numbers". Print.
Your application should use try and except when the user enters a non-numeric input, show him the "Invalid input" error message and go to the number request again.
Like the following example:
Enter a number: 4
Enter a number: 5
Enter a number: bad data
Invalid input
Enter a number: 7
Enter a number: done
16
3
5.333333333333333
I type the code below
while True :
try:
number = input ('Enter number: ')
n = int (number)
except:
print('Invalid input')
if n == 'done' :
break
x = None
y = None
for Total in [n] :
x = x + n
print (x)
for num in [n] :
y = y + 1
print (y)
for Average in [n] :
x = x + n
y = y + 1
aver = x / y
print ( aver)
And when I type "done" it displays a "Invalid input" warning
Enter number: 2
Enter number: 3
Enter number: 4
Enter number: done
Invalid input
Enter number:
When you type 'done', number becomes equal to the string 'done'
n = int (number) is then the same as n = int ('done'), which raises an exception, because 'done' can't be parsed as a base-10 integer
Note that since the call int ('done') raised an error, the value of n doesn't change
So you get to the except clause and print('Invalid input')
Since the value of n remained the same, n == 'done' is False
Thus, the loop continues
You can fix it by moving the check inside the except clause:
while True:
try:
number = input ('Enter number: ')
n = int (number)
except:
if number == 'done':
break
print('Invalid input')
Also note that this code:
for Total in [n] :
...
...will create a list with one element [n] and iterate over this list once, because there's only one element. So, it won't really compute any sum.
Furthermore, this code will attempt to add a number to None:
x = None
y = None
for Total in [n] :
x = x + n
print (x)
On the first iteration, x = x + n will evaluate to x = None + <integer>, which is invalid since None can't be added to anything.
Moreover, judging by your input, you want to input multiple numbers, however the first while loop will overwrite the variable n with a new number on each iteration, so all previous numbers will be lost.
You should accumulate these numbers somewhere:
numbers = []
while True:
try:
number = input ('Enter number: ')
n = int (number)
except:
if number == 'done':
break
print('Invalid input')
else:
# There was no exception
numbers.append(n)
I am trying to self learn python and have written a basic program to add sum of 1st n numbers of digits. When I am giving an integer input, it is executing perfectly but on non-integer input, throwing an error NameError: name 'add_it_up' is not defined. My program is written below.
try:
x = int(input('Enter the number upto which you want to add :'))
try:
def add_it_up(x):
sum = 0
for num in range(x + 1):
sum = sum + num
print(sum)
except TypeError:
print("Sorry we are facing a problem")
except ValueError:
print("Please enter an intiger value only")
add_it_up(x)
You are defining a function in the try block, not running it. Put the add_it_up function outside the try/except and then call it inside. Like this:
def add_it_up(x):
sum = 0
for num in range(x + 1):
sum = sum + num
print(sum)
try:
x = int(input('Enter the number upto which you want to add :'))
try:
add_it_up(x)
except TypeError:
print("Sorry we are facing a problem")
except ValueError:
print("Please enter an intiger value only")
scope of add_it_up function is inside of try statement only, this is why yuo are getting the errror.
def add_it_up(x):
sum_ = 0
for num in range(x + 1):
sum_ = sum_ + num
return sum_
try:
x = int(input('Enter the number upto which you want to add :'))
try:
result = add_it_up(x)
print(result)
except TypeError:
print("Sorry we are facing a problem")
except ValueError:
print("Please enter an intiger value only")
I had to use 'try' and 'except' to calculate sum of numbers and account of invalid input. When user enters 'done', the program prints out result. What are he mistakes?
total = 0
count = 0
while True :
try :
x = (input('enter an input \n'))
y = float(x)
print('your number is : ', y)
count = count+1
total = total + x
except :
if x == 'done':
break
else :
print('invalid input')
print ('sum is' , total , 'and average is' , total/count)
You are doing:
x = (input('enter an input \n'))
y = float(x)
print('your number is : ', y)
count = count+1
total = total + x
i.e. attempting to add to total what was inputed by user as str, you should add float value, i.e.:
x = (input('enter an input \n'))
y = float(x)
print('your number is : ', y)
count = count+1
total = total + y
I suggest changing your except block so that it displays the error instead of "invalid input":
except Exception as e:
if x == 'done':
break
else:
print(e)
This way it will tell the user what was wrong with the input -- and if anything else happens to go wrong in your code, it'll be easier to figure out!
Another option is to change your except to only catch ValueErrors:
except ValueError as e:
if x == 'done':
break
else:
print(e)
Any other kind of error (say, a TypeError) will then raise as normal.
The structure of your code is not correct. If the try is not successful, the x don't have value. You should check the "done" before the float casting. I have written a working version code.
Code:
total = 0
count = 0
while True:
try:
x = input("enter an input \n")
if x == "done":
break
y = float(x)
print("your number is : ", y)
count += 1 # Use the '+=' for incrementation.
total += y # You should add the float type to total.
except Exception:
print("invalid input")
print("sum is", total, "and average is", total / count)
Output:
>>> python3 test.py
enter an input
1
your number is : 1.0
enter an input
2
your number is : 2.0
enter an input
test
invalid input
enter an input
done
sum is 3.0 and average is 1.5
I have 2 inputs to type and I want to loop through them if the user would enter incorrect input. What I did is I set while True and then try and except and then continue. However in case of second input if the input is wrong then whole loop is repeated from the start - that is from the first input. I would like it to be repeated from the second input. The only thing that I can think of is to put break in the code after first correct input and then set another while True for the second input. What are better ways to do this?
while True:
try:
a = int(input("Type positive integer: "))
except ValueError:
print(" Enter a positive NUMBER!")
continue
if a <= 0:
print("Input can't be 0 or negative!")
continue
else:
try:
b = int(input("Type second positive integer: "))
except ValueError:
print(" Enter a positive NUMBER!")
continue
if b <= 0:
print("Input can't be 0 or negative!")
continue
else:
break
Since your condition is the same for each loop, you could try storing the try-except part as a function which returns the value (or a bool indicating success or failure with a parameter for the value), running the lambda in a for loop for each input you require, storing the result in a list and then getting what you need out as a tuple.
E.g.
def try_get_number_input():
try:
value = int(input("Type positive integer: "))
except ValueError:
print(" Enter a positive NUMBER!")
return False, 0
if value <= 0:
print("Input can't be 0 or negative!")
return False, 0
return True, value
# We require 2 inputs from the user
required_inputs = 2
received_inputs = []
for num in range(0, required_inputs):
values = try_get_number_input()
while not values[0]:
values = try_get_number_input()
received_inputs.append(values[1])
This ensures that the code is DRY (doesn't repeat itself) and is easily changeable (if you require 3 inputs instead, you can easily change it rather than having to add another branch of your while loop)
def getNumber(second=False):
while True:
try:
if second:
number = int(input("Type second positive integer: "))
else:
number = int(input("Type positive integer: "))
except ValueError:
print(" Enter a positive NUMBER!")
continue
if number <= 0:
print("Input can't be 0 or negative!")
continue
return number
a, b = getNumber(second=False), getNumber(second=True)
print(a,b)
You asked what a for loop would look like, here's one example:
vals = []
for msg in ['', 'second ']:
while True:
try:
n = int(input(f"Type {msg}positive integer: ")) # PY3.6
# n = int(input("Type {}positive integer: ").format(msg))) # <=PY3.5
except ValueError:
print(" Enter a positive NUMBER!")
continue
if n <= 0:
print("Input can't be 0 or negative!")
continue
vals.append(n)
break
a, b = vals
you can use decorator for retry logic and single function to read int value
def retry(func):
def wrapper(msg):
while True:
try:
return func(msg)
except Exception as e:
print(e)
return wrapper
#retry
def read_int(msg):
try:
a = int(input(msg))
except:
raise ValueError('Invalid Number')
else:
if a < 0:
raise ValueError('Number should be positive')
return a
a = read_int('type valid positive number: ')
b = read_int('type other valid positive number: ')
print(a, b)