HW Help on loops and error expections and 'done' - python

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

Related

Input variable box is not appearing and asking for input value and loop is not working

write a program that repeatedly read numbers until the user enters "done". Once "done" is entered, print out the total, count, and average numbers. if the user enters anything other than number, detect their mistake using try and except and print an error message and skip to the next number.
Enter a number: 4 Enter a number: 5 Enter a number: bad data Invalid input Enter a number: 7 Enter a number: done
""" """Approach1 """
Number = input(Enter a number: )
count = 0
total = 0
average = 0
try:
number = float(Number)
except ValueError:
print('Invalid input')
quit()
while True: # Stays in loop until break
number = input('Enter a number: ')
if number == 'done':
break # Exits the while loop
number = check_for_float(input_number)
for a number in Number:
count = count + 1
total = total + 1
average = number / count
print("Total:", total , "Count:", count, "Average: ", average)
After running this program, I was expecting an input box to pop and ask for input value which is not happening. Please advise.

How to Input numbers in python until certain string is entered

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

Python: How to check if a signed number is positive or negative or none?

Simply, I am entering a value, I want to determine whether the value is alpha or not. If it is not alpha, I want to check if it is a number or not. If it is a number I want to check if it is positive or negative.
I read a lot about checking a signed number like -50. There are two ways, we can use something like this:
try:
val = int(x)
except ValueError:
print("That's not an int!")
Which I think I do not need it here and I do not know where to put it in my code.
The other way is to use .lstrip("-+"), but it is not working.
amount = 0
while True:
amount = input("Enter your amount ===> ")
if amount.isalpha() or amount.isspace() or amount == "":
print("Please enter only a number without spaces")
elif amount.lstrip("-+").isdigit():
if int(amount) < 0:
print("You entered a negative number")
elif int(amount) > 6:
print("You entered a very large number")
else:
print(" Why I am always being printed ?? ")
else:
print("Do not enter alnum data")
What am I doing wrong ?
This is how you would integrate a try/except block:
amount = 0
while True:
amount = input("Hit me with your best num!")
try:
amount = int(amount)
if amount < 0:
print("That number is too tiny!")
elif amount > 6:
print("That number is yuge!")
else:
print("what a boring number, but I'll take it")
break # How you exit this loop
except ValueError:
print("Wow dude, that's like not even a number")
It does all the heavy lifting for you, as int() can process numbers with +/- automatically.
>>> amount = '-6'
>>> '-' in amount
True
>>> amount = amount.strip('-')
>>> amount.isdigit()
True
Check if the number is less than 0 or greater than 0 with < >

While loop is not running properly

I am trying to run a while loop in python. I can get most of it to function correctly but parts of the code are not working correctly and I have been trying different methods to solve it but I can't get it to do exactly what I want.
I am trying to write a program that which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number
Here is my code:
total=0
number=None
count=0
while True:
num=raw_input('Enter a number: ')
print 'Enter a number',num
for intervar in num:
count=count+1
if num=='done':
break
else:
try:
number=int(num)
if number is int:
continue
except:
print 'bad data'
total=total+number
print 'Enter a number:',number
print 'Total is',total
print 'Count is',count
When I enter 3,4,5 The output from this code is:
Enter a number 3
Enter a number 4
Enter a number 5
Enter a number nine
bad data
Enter a number done
Enter a number: 5
Total is 5
Count is 12
The code should read
Enter a number 3
Enter a number 4
Enter a number 5
Enter a number bad data
Enter a number done
Total is 12
Count is 3
Here is your code rearranged a bit:
total=0
count=0
while True:
num=raw_input('Enter a whole number: ')
try:
# just try to convert it
number=int(num)
# success -> accumulate
total += number
count += 1
except ValueError:
# if it isn't an integer, maybe they're done
if num.lower() == 'done':
break
else:
print 'bad data'
print 'Total is',total
print 'Count is',count
And here is an alternative
# keep all the numbers in a list for use later
numbers = list()
while True:
num=raw_input('Enter a whole number: ')
try:
# just try to convert it
numbers.append(int(num))
except ValueError:
# if it isn't an integer, maybe they're done
if num.lower() == 'done':
break
else:
print 'bad data'
print 'Total is', sum(numbers)
print 'Count is', len(numbers)
You've got at least three remaining problems, here
Problem 1
for intervar in num:
count=count+1
At this point num is a string and you are iterating over the characters in that string, incrementing count. The for loop is essentially equal to
count += len(num)
Do you want to count all inputs or only the correctly entered numbers?
Problem 2
The indentation of
total=total+number
is wrong. It must be inside the while loop. Also, use += when adding to a variable.
Problem 3
The is operator compares the object identities of two objects. In this case, the comparison is true, iff number is the class int
if number is int:
continue
What you want is:
if isinstance(number, int):
[...]
However, that is redundant, since after number = int(num) number is always an int.
Use a list to track the numbers, perform calculations at the end of the input session.
numbers = []
while True:
input = raw_input('Enter a whole number: ')
try:
numbers.append(int(input))
except ValueError:
if input is not None and input.lower() == 'done':
break
else:
print 'Invalid input.'
length = len(numbers)
total = sum(numbers)
average = total/count
print 'Total is', total
print 'Count is', length
print 'Average is', average
what you want to do is fix your increment for the total count
total=0
number=None
count=0
while True:
input = raw_input('Enter a whole number: ')
try:
number=int(input)
total += number
except:
if input.lower() == 'done':
break
else:
print 'bad data'
continue
count += 1
print 'Total is',total
print 'Count is',count
print 'Average is', total/count
notice I changed your variable name from num to input since its not always a number... also your check for the type of number was incorrect so I changed that too.. you only want to increment when its a number so I put that in the try... also your count i changed to not loop over all of the characters inputted but rather just count 1 for each time they enter something
an even better way would be to write a number check function
total=0
number=None
count=0
def check_int(str):
if str[0] in ('-', '+'):
return str[1:].isdigit()
return str.isdigit()
while True:
input = raw_input('Enter a whole number: ')
if check_int(input):
total += int(input)
count += 1
elif input.lower() == 'done':
break
else:
print 'bad data'
continue
print 'Total is',total
print 'Count is',count
print 'Average is', total/count
the benefit of this drops the need for a try/except which has considerable overhead
here is the code that prints your expected output.
you had an indentation error and too many prints.
total = 0
number = None
count = 0
while True:
num = raw_input('Enter a number: ')
if num == 'done':
break
else:
try:
number = int(num)
if number is int:
continue
except:
print 'bad data'
count += 1
total += number
print 'Total is',total
average = float(total)/float(count)
print 'average for %s is %s'%(count, average)

Loop that uses try/except for input and loops until 'done' is entered

I'm kind of new to coding in Python and I'm trying to write a loop that asks for numerical input and reads it until the user inputs "done", where it will then exit the loop and print the variables: number, count and average. (not trying to store anything in a list)
I also want it to print "invalid input" and continue the loop if the user enters anything that isn't an integer, unless its "done".
Unfortunately it returns "invalid input" and keeps looping even when I enter "done". What am I doing wrong? Could anyone point me in the right direction?
number = 0
count = 0
avg = 0
inp = 0
while True:
try:
inp = int(raw_input('Enter a number: '))
if inp is 'done':
number = number + inp
count = count + 1
avg = float(number/count)
break
except:
print 'Invalid input'
print number
print count
print float(avg)
sum = 0.0
count = 0
while True:
inp = raw_input('Enter a number: ')
if inp == 'done':
break
try:
sum += int(inp)
count += 1
except ValueError:
print 'Invalid input'
print sum
print count
if count != 0: # Avoid division by zero
print sum / count

Categories

Resources