I am completing questions from a python book when I came across this question.
Write a program which repeatedly reads numbers until the user enters "done". Once done is entered, print out total, count, and average of the numbers.
My issue here is that I do not know how to check if a user specifically entered the string 'done' while the computer is explicitly checking for numbers. Here is how I approached the problem instead.
#Avg, Sum, and count program
total = 0
count = 0
avg = 0
num = None
# Ask user to input number, if number is 0 print calculations
while (num != 0):
try:
num = float(input('(Enter \'0\' when complete.) Enter num: '))
except:
print('Error, invalid input.')
continue
count = count + 1
total = total + num
avg = total / count
print('Average: ' + str(avg) + '\nCount: ' + str(count) + '\nTotal: ' + str(total))
Instead of doing what it asked for, let the user enter 'done' to complete the program, I used an integer (0) to see if the user was done inputting numbers.
Keeping your Try-Except approach, you can simply check if the string that user inputs is done without converting to float, and break the while loop. Also, it's always better to specify the error you want to catch. ValueError in this case.
while True:
num = input('(Enter \'done\' when complete.) Enter num: ')
if num == 'done':
break
try:
num = float(num)
except ValueError:
print('Error, invalid input.')
continue
I think a better approach that would solve your problem would be as following :
input_str = input('(Enter \'0\' when complete.) Enter num: ')
if (input_str.isdigit()):
num = float(input_str)
else:
if (input_str == "done"):
done()
else:
error()
This way you control cases in which a digit was entered and the cases in which a string was entered (Not via a try/except scheme).
Related
the conditions are:
Repeatedly reads numbers until the user enters 'done'. Once 'done' is entered, break out of the loop.
If the user enters anything but a number, capture the error using a try-except construct and display the message "Bad Data"
Once 'done' is entered print out one of 2 messages:
If the total is greater or equal to 200 then:
"The total (the value in the total variable) for the numbers entered is Large"
If the total is less than 200 then:
"The total (the value in the total variable) for the numbers entered is Small"
count = 0
while count <= 200:
x = int(input('Please enter a number to add: '))
count = count + x
if x >= 200:
print('The total', count, 'for the number entered is Large')
break
elif x == 'done':
print ('The total',count,'for the number entered is Small')
break
elif x == ValueError:
print('Bad Data')
continue
Im a beginner so a little help would be cool.
When you accept the input value you need to check if it is a number before you try to convert it to an int. So you have two ways of doing this: either wrap the first line in a try except block to catch the value error or just check to see if the input they supply is actually a number. Also as Tim Roberts said above you can't check for "done" if you have already converted to an integer so that's why I have moved that check to the top of each example.
Version 1 (Try Except):
count = 0
while count <= 200:
user_input = input('Please enter a number to add: ')
if user_input.lower() == 'done':
print('The total', count, 'for the number entered is Small')
break
try:
x = int(user_input)
except ValueError:
print('Bad Data')
continue
count = count + x
if x >= 200:
print('The total', count, 'for the number entered is Large')
break
Version 2 (Check if number):
count = 0
while count <= 200:
user_input = input('Please enter a number to add: ')
if user_input.lower() == 'done':
print('The total', count, 'for the number entered is Small')
break
if user_input.isnumeric():
x = int(user_input)
else:
print('Bad Data')
continue
count = count + x
if x >= 200:
print('The total', count, 'for the number entered is Large')
break
PS. Adding the .lower() to the user_input allows them to type 'done' or 'DONE' or any combination of uppercase and lowercase and it will still exit.
I have edited your code a little bit. It might help you to understand the logic.
total = 0
while True:
userInput = input('Please enter a number to add: ')
if userInput == "done":
break
try:
x = int(userInput)
total += x
if total >= 200:
print('The total', total, 'for the number entered is Large')
elif total <= 200:
print ('The total',total,'for the number entered is Small')
except:
print("Bad Data")
A few notes. I have changed the count name to total since the logic of your problem seems to be closer to this name.
Output
Please enter a number to add: I am inputting bad data
Bad Data
Please enter a number to add: 100
The total 100 for the number entered is Small
Please enter a number to add: 0
The total 100 for the number entered is Small
Please enter a number to add: 50
The total 150 for the number entered is Small
Please enter a number to add: 30
The total 180 for the number entered is Small
Please enter a number to add: -50
The total 130 for the number entered is Small
Please enter a number to add: done
I'm trying to work out the average of numbers that the user will input. If the user inputs nothing (as in, no value at all) I want to then calculate the average of all numbers that have been input by the user upto that point. Summing those inputs and finding the average is working well, but I'm getting value errors when trying to break the loop when the user inputs nothing. For the if statement I've tried
if number == ''
First attempt that didn't work, also tried if number == int("")
if len(number) == 0
This only works for strings
if Value Error throws up same error
Full code below
sum = 0
while True :
number = int(input('Please enter the number: '))
sum += number
if number == '' :
break
print(sum//number)
Error I'm getting is
number = int(input('Please enter the number: '))
ValueError: invalid literal for int() with base 10:>
Any help much appreciated!
EDIT: Now getting closer thanks to the suggestions in that I can get past the problems of no value input but my calculation of average isn't working out.
Trying this code calculates fine but I'm adding the first input twice before I move to the next input
total = 0
amount = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
total = number + number
amount += 1
except:
break
total += number
print(total/amount)
Now I just want to figure out how I can start the addition from the second input instead of the first.
sum = 0
while True :
number = input('Please enter the number: '))
if number == '' :
break
sum += int(number)
print(sum//number)
try like this
the issue is using int() python try to convert input value to int. So, when its not integer value, python cant convert it. so it raise error. Also you can use Try catch with error and do the break.
You will always get input as a string, and if the input is not a int then you cant convert it to an int. Try:
sum = 0
while True :
number = input('Please enter the number: ')
if number == '' :
break
sum += int(number)
print(sum//number)
All of the answers dont work since the print statement referse to a string.
sum = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
except:
break
sum += number
print(sum//number)
including a user_input will use the last int as devisor.
My answer also makes sure the script does not crash when a string is entered.
The user has to always input something (enter is a character too) for it to end or you will have to give him a time limit.
You can convert character into int after you see it isn't a character or
use try & except.
sum = 0
i = 0
while True :
try:
number = int(input('Please enter the number: '))
except ValueError:
break
i += 1
sum += number
try:
print(sum/number)
except NameError:
print("User didn't input any number")
If you try to convert a character into int it will show ValueError.
So if this Error occurs you can break from the loop.
Also, you are trying to get the average value.
So if a user inputs nothing you get NameError so you can print an Error message.
This is my code below:
while True:
try:
number = int (str("Enter"))
if len(str(number)) != 7:
print('Incorrect')
if len(str(number)) == 7:
print('Okay')
multiplier = [3,1]
times = ""
total = 0
for index, digit in enumerate(list(str(number))):
total = total + int(digit)*multiplier[index%2]
times = times+str(int(digit)*multiplier[index%2])+", "
mof10 = total + (10 - total%10)
checkdigit = mof10 - total
final = str(number) + str(checkdigit)
print (times[:-1])
print(total)
print(mof10)
print(checkdigit)
print(final)
break
except ValueError:
print("Not a number")
When I run the code the except ValueError is the only thing that prints, but it does not stop printing it.
I would like to know how to make this code accept 8 digit numbers, then validate if its a multiple of 10 or not, if it is it should be valid.
Your program runs into an exception from the start.
number = int(str("Enter"))
The program is creating an integer called 'number'. However, your code is saving the text "Enter" as a string, then converting it into an integer.
What you need to do is replace 'str' with 'input'. This means the program will print 'Enter', and save the user input as an integer. What you were doing before was saving the text 'Enter' as a string, then converting to an int, which caused the exception and made Python run the 'except' code.
I've made a simple program where the users adds as many numbers as they would like then type 'exit' to stop it and print the total but sometimes it says the converting the string to int fails, and sometimes it does convert but then it has the wrong out put e.g I type 1 + 1 but it prints 1
def addition():
x = 0
y = 1
total = 0
while x < y:
total += int(input())
if input() == "exit":
x += 1
print(total)
addition()
I have tryed converting it to a float then to an int but still has inconsistency, I did start learning python today and am finding the syntax hard coming from c++ / c# / Java so please go easy on the errors
Maybe this is what you are looking for:
def addition():
total = 0
while True:
value = input()
if value == "exit":
break
else:
try:
total += int(value)
except:
print('Please enter in a valid integer')
print(total)
EDIT
There are two reasons why the code isn't working properly:
First, the reason why it is failing is because you are trying to cast the word "exit" as an integer.
Second, as user2357112 pointed out, there are two input calls. The second input call was unintentionally skipping every other number being entered in. All you needed to do was one input call and set the entered value into a variable.
You can break the while loop, without using x and y.
def addition():
total = 0
while True:
total += int(input())
if input() == "exit":
break
print(total)
addition()
These are a few ways you can improve your code:
Run the loop forever and break out of it only if the user enters "exit"
To know when the user entered "exit" check if the input has alphabets with isalpha()
Making the above changes:
def addition():
total = 0
while True:
user_input = input()
if user_input.strip().isalpha() and user_input.strip() == 'exit':
break
total += int(user_input)
print(total)
addition()
def safe_float(val):
''' always return a float '''
try:
return float(val)
except ValueError:
return 0.0
def getIntOrQuit():
resp = input("Enter a number or (q)uit:")
if resp == "Q":
return None
return safe_float(resp)
print( sum(iter(getIntOrQuit,None)) )
is another way to do what you want :P
I'm currently working on a program in Python and I need to figure out how to convert a string value to a float value.
The program will ask the user to enter a number, and uses a loop to continue asking for more numbers. The user must enter 0 to stop the loop (at which point, the program will give the user the average of all the numbers they entered).
What I want to do is allow the user to enter the word 'stop' instead of 0 to stop the loop. I've tried making a variable for stop = 0, but this causes the program to give me the following error message:
ValueError: could not convert string to float: 'stop'
So how do I make it so that 'stop' can be something the user can enter to stop the loop? Please let me know what I can do to convert the string to float. Thank you so much for your help! :)
Here is some of my code:
count = 0
total = 0
number = float(input("Enter a number (0, or the word 'stop', to stop): "))
while (number != 0):
total += number
count += 1
print("Your average so far is: " , total / count)
number = float(input("Enter a number (0, or the word 'stop', to stop): "))
if (number == 0):
if (count == 0):
print("")
print("Total: 0")
print("Count: 0")
print("Average: 0")
print("")
print("Your average is equal to 0. Cool! ")
else:
print("")
print("Total: " , "%.0f" % total)
print("Count: " , count)
print("Average: " , total / count)
Please let me know what I should do. Thanks.
I'd check the input to see if it equals stop first and if it doesn't I'd try to convert it to float.
if input == "stop":
stop()
else:
value = float(input)
Looking at your code sample I'd do something like this:
userinput = input("Enter a number (0, or the word 'stop', to stop): ")
while (userinput != "stop"):
total += float(userinput) #This is not very faulttolerant.
...
You could tell the user to enter an illegal value - like maybe your program has no use for negative numbers.
Better, would be to test if the string you've just read from sys.stdin.readline() is "stop" before converting to float.
You don't need to convert the string to a float. From what you've said it appears that entering 0 already stops the loop, so all you need to do is edit you're currently existing condition check, replacing 0 with "stop".
Note a few things: if the input is stop it will stop the loop, if it's not a valid number, it will just inform the user that the input were invalid.
while (number != 0):
total += number
count += 1
print("Your average so far is: " , total / count)
user_input = input("Enter a number (0, or the word 'stop', to stop): ")
try:
if str(user_input) == "stop":
number = 0
break
else:
number = float(user_input)
except ValueError:
print("Oops! That was no valid number. Try again...")
PS: note that keeped your code "as is" mostly, but you should be aware to not use explicit counters in python search for enumerate...