Why does it give an error when typing "done"? - python

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)

Related

Logical flaw/s in my basic Python code to calculate sum of numbers?

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

How to stop a while loop processing integers with a string

I'm processing integer inputs from a user and would like for the user to signal that they are done with inputs by typing in 'q' to show they are completed with their inputs.
Here's my code so far:
(Still very much a beginner so don't flame me too much)
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num = int(input("Enter a number: "))
while num != "q":
num = int(input("Enter a number: "))
count += 1
total += num
del record[-1]
print (num)
print("The average of the numbers is", total / count)
main()
Any feedback is helpful!
You probably get a ValueError when you run that code. That's python's way of telling you that you've fed a value into a function that can't handle that type of value.
Check the Exceptions docs for more details.
In this case, you're trying to feed the letter "q" into a function that is expecting int() on line 6. Think of int() as a machine that only handles integers. You just tried to stick a letter into a machine that's not equipped to handle letters and instead of bursting into flames, it's rejecting your input and putting on the breaks.
You'll probably want to wrap your conversion from str to int in a try: statement to handle the exception.
def main():
num = None
while num != "q":
num = input("Enter number: ")
# try handles exceptions and does something with them
try:
num = int(num)
# if an exception of "ValueError" happens, print out a warning and keep going
except ValueError as e:
print(f'that was not a number: {e}')
pass
# if num looks like an integer
if isinstance (num, (int, float)):
print('got a number')
Test:
Enter number: 1
got a number
Enter number: 2
got a number
Enter number: alligator
that was not a number: invalid literal for int() with base 10: 'alligator'
Enter number: -10
got a number
Enter number: 45
got a number
Enter number: 6.0222
that was not a number: invalid literal for int() with base 10: '6.0222'
I'll leave it to you to figure out why 6.02222 "was not a number."
changing your code as little as possible, you should have...
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num.append(input("Enter a number: "))
while num[-1] != "q":
num.append(input("Enter a number: "))
count += 1
try:
total += int(num[-1])
except ValueError as e:
print('input not an integer')
break
print (num)
print("The average of the numbers is", total / count)
main()
You may attempt it the way:
def main():
num_list = [] #list for holding in user inputs
while True:
my_num = input("Please enter some numbers. Type 'q' to quit.")
if my_num != 'q':
num_list.append(int(my_num)) #add user input as integer to holding list as long as it is not 'q'
else: #if user enters 'q'
print(f'The Average of {num_list} is {sum(num_list)/len(num_list)}') #calculate the average of entered numbers by divide the sum of all list elements by the length of list and display the result
break #terminate loop
main()

I am trying to get my program to take only integers and stop when the user presses 0

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

Implementing ZeroDivisionError exception in python

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

Collatz sequence ends at 4

I am writing a Collatz sequence program using the practice projects from chapter 3 of Automate the boring stuff with python.
The program outline is:
Write a function named collatz() that has one parameter named number.
If number is even, then collatz() should print number // 2 and return
this value. If number is odd, then collatz() should print and return
3 * number + 1.
Then write a program that lets the user type in an integer and that
keeps calling collatz() on that number until the function returns the
value 1.
My code runs however it stops on 4 rather than 1. For every number I have tried so far the output goes past 1 back to 4.
example output:
6,3,10,5,16,8,4,2,1,4
I am using python 3.4.2
def collatz(number):
if number % 2 == 0:
number = number //2
print(number)
return number
elif number % 2 == 1:
number = 3 * number + 1
print(number)
return number
print ("pick a number:")
while True:
try:
number = int(input())
while number != 1:
number = collatz(number)
collatz(number)
break
except ValueError:
print("Error: Please enter a valid integer")
print("Magic! You are down to 1.")
The problem is that you call collatz() once more after the loop finishes with 1. Just remove that line, and it works fine.
Also if you move the "pick a number" to the input function, you can avoid the new line after the question and are asked again every time, if you input an invalid value.
Additionally you should also check if the number is greater than or equal to 1, to avoid endless loops. The code to do all that would look like that:
while True:
try:
number = int(input("pick a number: "))
if number < 1:
print("Error: Please enter a integer greater than or equal to 1 ")
continue
while number != 1:
number = collatz(number)
# removed the additional call to collatz
break
except ValueError:
print("Error: Please enter a valid integer")
print("Magic! You are down to 1.")
def collatz(number):
number = number // 2 if number % 2 == 0 else 3 * number + 1
print(number)
return number
number = int(input("Pick a Number\n"))
while number != 1:
number = collatz(number)
print("Magic! You are down to 1.")

Categories