python 2.7: Count how many numbers are entered by the user.
I can't figure out how to count the raw_input... here's what I have so far:
while True:
datum = raw_input('enter a number: ')
if datum == 'done': break
count = 0
for line in datum:
if datum == int(datum):
count = count + 1
print 'count', count
You can use try and except
count=0 should be before the while
try:
count = 0
while True:
datum = raw_input('enter a number: ')
if datum == 'done': break
try:
int(datum)
count += 1
except ValueError:
pass
print 'count', count
datum = []
total = 0
count = 0
while True:
data = raw_input('enter a number: ')
if data == 'done': break
datum.append(data)
for i in datum:
try:
total = total + int(i)
count += 1
except:
pass
print 'count', count, ' total',total
count = 0
while True:
dat_num = raw_input('enter a number: ')
if dat_num == 'done':break
else:
dat_num = int(dat_num)
count += dat_num
print 'count', count
Related
I have a problem with a while loop. Basically the program should continuously ask the user to input the item price until they enter 'Done', and print the total bill. For context I'll put my code at the moment.
a = float(input('Price? '))
count = 0
while a > 0:
b = float(input('Price? '))
count += b
if a == 'Done':
print('Total is $', count)
count = 0
while True:
a = input('Price? ')
if a == 'Done':
print('Total is $', count)
break
count += float(a)
Note that this code breaks if the user inputs a string that is not either "Done" or a float literal. For that you would need to surround the count += float(a) line with a try / except block.
def adding():
total = 0
x = 0
while x != 'done':
x = int(raw_input('Number to be added: '))
total = x + total
if x == 'done':
break
print total
I cant figure out how to add numbers that a user is inputing, and then stop and print the total when they input 'done'
I'm assuming it's yelling at you with a ValueError when the user inputs "done"? That's because you're trying to cast it as an int before checking if it's a number or the sentinel. Try this instead:
def unknownAmount():
total = 0
while True:
try:
total += int(raw_input("Number to be added: "))
except ValueError:
return total
Alternatively, you can change your own code to work by doing:
def unknownAmount():
total = 0
x = 0
while x != "done":
x = raw_input("Number to be added: ")
if x == "done":
continue
else:
total += int(x)
return total
But beware that if the user enter "foobar", it will still throw a ValueError and not return your total.
EDIT: To address your additional requirement from the comments:
def unknownAmount():
total = 0
while True:
in_ = raw_input("Number to be added: ")
if in_ == "done":
return total
else:
try:
total += int(in_)
except ValueError:
print "{} is not a valid number".format(in_)
This way you check for the only valid entry that's NOT a number first ("done") then holler at the user if the cast to int fails.
There are many similar questions here, but what the hell. Simplest would be:
def adding():
total = 0
while True:
answer = raw_input("Enter an integer: ")
try:
total += int(answer)
except ValueError:
if answer.strip() == 'done':
break
print "This is not an integer, try again."
continue
return total
summed = adding()
print summed
More fancy take on problem would be:
def numbers_from_input():
while True:
answer = raw_input("Enter an integer (nothing to stop): ")
try:
yield int(answer)
except ValueError:
if not answer.strip(): # if empty string entered
break
print "This is not an integer, try again."
continue
print sum(numbers_from_input())
but here are some python features you may not know if you are begginer
How do I loop this code with a "do you want to run this again" question?
count = 1
total = 0
markslist = list()
while count <= 10:
newmark = input("Input Mark Out Of 100 (" + str(count) + ") ")
markslist.append(newmark)
if newmark > 100:
import sys
sys.exit("Error Mark is greater than 100 re-run program")
total = total + newmark
count = count + 1
average = (total / 10)
print "Average Mark = " + str(average)
Just wrap the entire code in a loop similar to this:
while True:
again = input('Go? (y/n): ')
if again != 'y':
break
# The entirety of the rest of your program would go here.
here is my current code:
total = 0.0
count = 0
data = input("Enter a number or enter to quit: ")
while data != "":
count += 1
number = float(data)
total += number
data = input("Enter a number or enter to quit: ")
average = total / count
if data > 100:
print("error in value")
elif data < 0:
print("error in value")
elif data == "":
print("These", count, "scores average as: ", average)
The only problem now is "expected an indent block"
I would do something cool like
my_list = list(iter(lambda: int(input('Enter Number?')), 999)) # Thanks JonClements!!
print sum(my_list)
print sum(my_list)/float(len(my_list))
if you wanted to do conditions, something like this would work
def getNum():
val = int(input("Enter Number"))
assert 0 < val < 100 or val == 999, "Number Out Of Range!"
return val
my_list = list(iter(getNum, 999)) # Thanks JonClements!!
print sum(my_list)
print sum(my_list)/float(len(my_list))
To calculate an average you will need to keep track of the number of elements (iterations of the while loop), and then divide the sum by that number when you are done:
total = 0.0
count = 0
data = input("Enter a number or enter 999 to quit: ")
while data != "999":
count += 1
number = float(data)
total += number
data = input("Enter a number or enter 999 to quit: ")
average = total / count
print("The average is", average)
Note that I renamed sum to total because sum is the name of a built-in function.
total = 0.0
count = 0
while True:
data = input("Enter a number or enter 999 to quit: ")
if data == "999":
break
count += 1
total += float(data)
print(total / count)
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 the number.
I have this so far but im confused on how to create a way to compare the maximum value? Im new to programming and im just asking for help. Also do I include the try and except block before the while with the try? and then error for the except?
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
if num == "done" : break
print num
print "Maximum", largest
nums = []
while True:
n = raw_input("Enter a number: ")
if n == "done":
break
try:
nums.append(int(n))
except ValueError:
print "Invalid input"
print "Min: %d" % min(nums)
print "Max: %d" % max(nums)
largest = None
smallest = None
first_number = True
while True:
num = raw_input("Enter a number: ")
if num == "done" : break
try:
num = int(num)
if first_number:
largest = num
smallest = num
first_number = False
else:
largest = max(largest, num)
smallest = min(smallest, num)
except Exception, e:
print "Not Valid Input!!!"
continue
print "Maximum", largest
print "Minimum", smallest
numbers =[]
while True:
num = raw_input("Enter a number: ")
if num == "done" :
break
else:
numbers.append(num)
print max(numbers)
print min(numbers)
So, the logic is to add the numbers to a list and use functions max and min. You can write code to handle exceptions yourself.
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
if num == "done": break
if len(num) < 1 : break
try:
num=int(num)
except:
print "Invalid input"
continue
if num is smallest:
smallest = num
if num > largest:
largest = num
print "Maximum is ", largest
print "Minimum is ", smallest
You can do this with a very small modification of your original program: just keep tabs of the smallest and largest numbers as you consider them.
largest = None
smallest = None
while True:
string = raw_input("Enter a number: ")
if string == "done":
break
try:
num = int(string)
except ValueError:
print "Not a number"
continue
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num
largest = None
smallest = None
while True:
num = raw_input('Enter a number: ')
if num == 'done':
print 'Maximum is %s' % largest
print 'Minimum is %s' % smallest
break
try:
num = int(num)
if smallest is None or num <= smallest:
smallest = num
if largest is None or num >= largest:
largest = num
except:
print 'Invalid input'
I am also a python beginning learner, this question I have noticed in 'Python for Everyone' by Charles Russell Severance. My answer is below.
prompt = 'Enter the number: '
initial_value = 0.0
while True:
thing = input(prompt)
if thing == 'done':
break
try:
num = float(thing)
except:
print('Invalid input')
continue
num = float(thing)
if num > initial_value:
max = num
min = initial_value
else:
min = num
print('Max', max)
print('Min', min)
By assigning num to a single value, you are overwriting it through every iteration of the loop. Use a list instead.
num = []
finish = "n"
while finish.lower() == "n"
try:
num.append(int(raw_input("Enter a number: ")))
except ValueError:
print "Not a number"
finish = raw_input("Would you like to add another number? (y/n): ")
print max(num)