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")
Related
I've been trying to work on this assignment but for some reason the function I wrote won't return the list I specified and throws a name 'numbers' is not defined error at me when printing the list outside the function.
def inputNumbers():
try:
initial_number_input = int(input("Please enter the first number: "))
except ValueError:
print("This is not a number.")
return inputNumbers()
else:
numbers = []
numbers.append(initial_number_input)
if initial_number_input == 0:
return numbers
else:
i = 0
while True:
try:
number_input = int(input("Please enter the next number: "))
except ValueError:
print("This is not a number.")
continue
else:
numbers.append(number_input)
i += 1
if number_input == 0:
break
return numbers
inputNumbers()
print(numbers)
I'm still very new to programming so I am open to whatever suggestions you may have :D
Note that if I print(numbers) above return numbers at the end of the function, it does print the list.
Thanks
When you return a value from a function it needs to be assigned to something. At the moment you are returning numbers but nothing is using it.
To actually use the returned value your last 2 lines should be
numbers = inputNumbers()
print(numbers)
You can also just print the returned value without assigning it to a variable with
print(inputNumbers())
question:
Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore it.
Input:
7 ,2 , bob, 10, 4, done.
Desired output:
Invalid input
Maximum is 10
Minimum is 2
Actual output:
Invalid input
Invalid input
Maximum is 10
Minimum is 2
Code:
largest=-1
smallest=None
while True:
num =input("Enter a number: ")
try:
if num == "done" :
break
elif smallest is None:
smallest=int(num)
elif int(num)<smallest:
smallest=int(num)
elif int(num)>largest:
largest=int(num)
else:
raise ValueError()
except ValueError:
print("Invalid input")
print("Maximum is",largest)
print("Minimum is",smallest)
I think there's a more Pythonic way of doing this. Try this:
inputList = []
while True:
num = input("Enter a number:")
try:
num = int(num)
inputList.append(num)
except:
if num == "done":
break
else:
print ("Invalid input. Ignoring...")
print ("Maximum is:",max(inputList))
print ("Minimum is:",min(inputList))
Edit: This code works with Python3. For Python2, you might want to use raw_input() instead of input()
You are already capturing the ValueError in Exception,
So inside, try, you are raising ValueError there you leave the scope for this error.
When you accept input, and it accepts 4 as input, which is neither larger than largest (i.e. 10) nor smaller than the smallest (i.e. 2). So it lands in else part and raises ValueError (as per your code). Hence prints Invalid input twice in your case. So this part is unnecessary as well as makes your solution bogus.
Again, from efficiency point of view -
1 - You are checking smallest == None for every input, which takes O(1) time and is unnecessary if you take it any integer
Here is the solution you are looking for :-
largest=None
smallest=None
while True:
try:
num = input("Enter a number: ")
num = int(num)
if smallest is None:
smallest = num
if largest is None:
largest = num
if num < smallest:
smallest = num
elif num > largest:
largest = num
except ValueError:
if num == 'done':
break
else:
print("Invalid input")
continue
print("Maximum is",largest)
print("Minimum is",smallest)
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)
So the code before behaved properly before my "while type(number) is not int:" loop, but now when the user presses 0, instead of generating the sum of the list, it just keeps looping.
Would really appreciate some help with this! Thank you!
List = []
pro = 1
while(pro is not 0):
number = False
while type(number) is not int:
try:
number = int(input("Please enter a number: "))
List.append(number)
except ValueError:
print("Please only enter integer values.")
if(number == 0):
Sum = 0
for i in List:
Sum = i + Sum
ans = 0
print(Sum)
Actually, this should keep looping forever for all numbers the user may input, not just zero.
To fix this, you can just add this break condition after (or before, it doesnt really matter) appending:
number = int(input("Please enter a number: "))
List.append(number)
if number == 0:
break
So I got it to work, when written like this:
List = []
pro = 1
while(pro is not 0):
while True:
try:
number = int(input("Please enter a number: "))
List.append(number)
break
except ValueError:
print("Please only enter integer values.")
if(number == 0):
Sum = 0
for i in List:
Sum = i + Sum
pro = 0
print(Sum)
But I don't really understand how this is making it only take int values, any clarification would be really helpful, and otherwise thank you all for your help!
I'm guessing that you want to end while loop when user inputs 0.
List = []
pro = 1
while pro is not 0:
try:
number = int(input("Please enter a number: "))
List.append(number)
# This breaks while loop when number == 0
pro = number
except ValueError:
print("Please only enter integer values.")
Sum = 0
for i in List:
Sum += i
print(Sum)
EDIT: I have also cleaned the unnecessary code.
Put if number == 0: inside while type(number) is not int: loop like this:
List = []
while True:
try:
number = int(input("Please enter a number: "))
if number == 0:
Sum = 0
for i in List:
Sum = i + Sum
print(Sum)
break
List.append(number)
except ValueError:
print("Please only enter integer values.")
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")`