Python continuous input - python

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.

Related

While & Sentinel Values

I am learning Python and am trying to edit the code which has the following error:
If you enter a negative number, it will be added to the total and count. Modify the code so that negative numbers give an error message instead (but don’t end the loop) Hint: elif is your friend.
def checkout():
total = 0
count = 0
moreItems = True
while moreItems:
price = float(input('Enter price of item (0 when done): '))
if price != 0:
count = count + 1
total = total + price
print('Subtotal: $', total)
# This `elif` block is the code I edited
elif price<0:
print('Error')
price= False
else:
moreItems = False
average = total / count
print('Total items:', count)
print('Total $', total)
print('Average price per item: $', average)
checkout()
How can I fix my code so it prints the "Error" message when a negative price is entered?
When the user submits a negative value to the price input, your code then runs if price != 0:.
To figure out what's going on more easily, I ran this code in the python shell:
>>> total = 0
>>> count = 0
>>> moreItems = True
>>> price = float(input('Enter price of item (0 when done): '))
Enter price of item (0 when done): -5
>>> price != 0
True
What you probably want instead is:
if price > 0:
...
elif price < 0:
print("Error")
You have to change this line:
if price != 0:
to this one:
if price > 0:
In if else or if elif statements, the code inside else or elif is only executed if the condition of if fails.
Ex:
if cond1:
code1
elif cond2:
code2
else:
code3
if cond1 is true then only code1 will run. If not cond2 will be checked, If True then only code2 will tun, hence the word "else" (elif is the same as else if)
In you question:
Modify the code so that negative numbers give an error message instead
(but don’t end the loop) Hint: elif is your friend.
In your code, If price is negative then price != 0 is True.
So because using elif, only this will run:
count = count + 1
total = total + price
print('Subtotal: $', total)
Code fix:
def checkout():
total = 0
count = 0
moreItems = True
while moreItems:
price = float(input('Enter price of item (0 when done): '))
**if price > 0:
count = count + 1
total = total + price
print('Subtotal: $', total)
elif price < 0:
print('Error')
price= False**
else:
moreItems = False
average = total / count
print('Total items:', count)
print('Total $', total)
print('Average price per item: $', average)
checkout()
Is this what you expected..? I have only done a few minor changes.
def checkout():
total = 0
count = 0
moreItems = True
while moreItems:
price = float(input('Enter price of item (0 when done): '))
if price > 0:
count += 1
total += price
print(f'Subtotal: $ {total}')
elif price < 0:
print('**Error**, Please enter a positive value')
else:
moreItems = False
average = total / count
print(f'Total items: {count}')
print(f'Total $ {total}')
print(f'Average price per item: $ {average}')
checkout()

How to give a warning and ask for raw_input again - while inside a loop

I have written the Python code below (actually it's my solution for an exercise from page 80 of "Teach yourself Python in 24 hours").
The idea is: there are 4 seats around the table, the waiter knows for how much each seat ordered, enters those 4 amounts and gets a total.
If the raw_input provided is not a number (but a string) my code kicks the person out. The goal, however, is to give an error message ("this entry is not valid") and ask for the input again - until it's numeric. However, I can't figure out how to ask the user for the raw input again - because I am already inside a loop.
Thanks a lot for your advice!
def is_numeric(value):
try:
input = float(value)
except ValueError:
return False
else:
return True
total = 0
for seat in range(1,5):
print 'Note the amount for seat', seat, 'and'
myinput = raw_input("enter it here ['q' to quit]: ")
if myinput == 'q':
break
elif is_numeric(myinput):
floatinput = float(myinput)
total = total + floatinput
else:
print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(myinput)
break
if myinput == 'q':
print "Goodbye!"
else:
total = round(total, 2)
print "*****\nTotal: ${}".format(total)
print "Goodbye!"
Generally, when you don't know how many times you want to run your loop the solution is a while loop.
for seat in range(1,5):
my_input = raw_input("Enter: ")
while not(my_input == 'q' or isnumeric(my_input)):
my_input = raw_imput("Please re-enter value")
if my_input == 'q':
break
else:
total += float(my_input)
As Patrick Haugh and SilentLupin suggested, a while loop is probably the best way. Another way is recursion- ie, calling the same function over and over until you get a valid input:
def is_numeric(value):
try:
input = float(value)
except ValueError:
return False
else:
return True
def is_q(value):
return value == 'q'
def is_valid(value, validators):
return any(validator(input) for validator in validators)
def get_valid_input(msg, validators):
value = raw_input(msg)
if not is_valid(value, validators):
print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(value)
value = get_valid_input(msg, validators)
return value
total = 0
for seat in range(1,5):
print 'Note the amount for seat', seat, 'and'
myinput = get_valid_input("enter it here ['q' to quit]: ", [is_q, is_numeric])
if myinput == 'q':
break
elif is_numeric(myinput):
floatinput = float(myinput)
total = total + floatinput
if myinput == 'q':
print "Goodbye!"
else:
total = round(total, 2)
print "*****\nTotal: ${}".format(total)
print "Goodbye!"
In the above code, get_valid_input calls itself over and over again until one of the supplied validators produces something truthy.
total = 0
for seat in range(1,5):
incorrectInput = True
while(incorrectInput):
print 'Note the amount for seat', seat, 'and'
myinput = raw_input("enter it here ['q' to quit]: ")
if myinput == 'q':
print 'Goodbye'
quit()
elif is_numeric(myinput):
floatinput = float(myinput)
total = total + floatinput
incorrectInput = False
else:
print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(myinput)
total = round(total, 2)
print "*****\nTotal: ${}".format(total)
print "Goodbye!"

Python How to add numbers as much as user likes

I'm learning python for 2 weeks.
So my question is let's say I created a calculator.
How can I add number as much as user likes?
os.system("del *.pyc")
print "Hello %s!" % ad
print "---------------------------------------"
print " *Add"
print " *x Add (Dunno english)"
print " *Multiply"
print " *x Multiply (Look up)"
print " *Multiply by itself"
print " *math.sqrt"
print "---------------------------------------"
print "What u want? :)"
choice = raw_input("Secimim= ")
print "So you choose %s :)" % choice
print ""
print "redirecting..."
time.sleep(3)
os.system("cls")
if secim.lower()=="add":
first=input("First number= ")
second=input("Second= ")
print "Result= " + str(add(first,second))
os.system("pause")
Rest of them is same
Let's make this part english
print "Let's have your choice :)"
secim = raw_input("Secimim= ")
adsiz = (ad,secim)
print "So you selected this :)" % adsiz
print ""
print "Redirecting..."
time.sleep(3)
os.system("cls")
if secim.lower()=="add":
ilksayi=input("IFirst= ")
ikincisayi=input("Second= ")
print "Result= " + str(toplama(ilksayi,ikincisayi))
os.system("pause")
def toplama(x,y):
return x+y
This part
if secim.lower()=="add":
firstnumber=input("IFirst= ")
secondnumber=input("Second= ")
print "Result= " + str(add(ilksayi,ikincisayi))
os.system("pause")
I want to make it like a loop that it says:
Number=10
Number = 26
Number = 62
...
And when you type
Number= (Blank)
It print the result.
Just like the phone's calculators.
I tried making it with loop that breaks when user types quit.
But I can't declare that much variable.
How to make auto making variables?
I think you are looking for something like this.
Python 2
num = '0'
total = 0
while True: #run loop until user enters something that is not a number
if not num.isdigit():
break #at this point break out of the loop
total += int(num) #else add the number to the total (could be / * - +)
num = raw_input('Number:\t')
print total #finally print the total
Or you could use an approach with Lists
nums = []
while True:
num = raw_input('Number: ')
if num.isdigit(): nums.append(int(num))
else: break;
print sum(nums)
Do you mean something like...
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
number = 0
input = raw_input('Number: ')
while input != None and input != "":
if not is_number(input):
print "NaN"
continue
number += float(input)
input = raw_input('Number: ')
print "Number = %s" % (number, )
I typed it blind so there might be errors in the code but you get the drift hopefully
Try this:
#! python3
# coding=utf-8
"""Add a lot of numbers."""
def add_everything():
""" """
numbers = []
while True:
print("Sum:", sum(numbers) )
s = input("Enter number(s) or just hit Return to quit:")
if not s:
break
for n in s.split():
try:
number = float(n)
except ValueError:
print("That wasn't a number. Try again!")
else:
numbers.append( number )
print("added {} to {}".format( number, sum(numbers[:-1]) ) )
finally:
pass
print("That was fun!")
print("I remembered all your {} numbers:".format(len(numbers)) )
for n in numbers:
print(" {:4.2f}".format(n) )
print("--------")
print(" {:4.2f}".format( sum(numbers) ) )
if __name__ == '__main__':
add_everything()
Example:
Sum: 0
Enter number(s) or just hit Return to quit:123 45.6
added 123.0 to 0
added 45.6 to 123.0
Sum: 168.6
Enter number(s) or just hit Return to quit:hello
That wasn't a number. Try again!
Sum: 168.6
Enter number(s) or just hit Return to quit:-0.99
added -0.99 to 168.6
Sum: 167.60999999999999
Enter number(s) or just hit Return to quit:
That was fun!
I remembered all your 3 numbers:
123.00
45.60
-0.99
--------
167.61

How do I add numbers together using loops?

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

figuring out how to find the average of entered numbers

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)

Categories

Resources