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
Related
The programm is check if input value is valid in list.
below is my code. could you please help?thanks
while True:
try:
count = 0
Day_list = []
days = int(input("Enter number : "))
except ValueError:
print("Please input the integer")
else:
for i in range(days):
Day_list.append(float(input("Enter the day "+str(i+1)+ ": " )))
if( 0<= Day_list[i] <=10):
print('good' )
else:
print('Amount cant be negative, try again')
break
i would like check the value one by one
eg.
Enter the day 1 : -1
then output : Amount cant be negative, try again
return Enter the day 1 : 1
Enter the day 2 :
but i dont have idea where is mistake,thanks
here you are:
while True:
try:
count = 0
Day_list = []
days = int(input("Enter number : "))
except ValueError:
print("Please input the integer")
else:
if days >= 0:
for i in range(days):
valid = False
while not valid:
try:
Day_list.append(float(input("Enter the day "+str(i+1)+ ": " )))
if( Day_list[i] >= 0 and Day_list[i] <=10):
print('good' )
valid = True
except ValueError:
print ('input is not valid')
break
else:
print('Amount cant be negative, try again')
I am trying to control the user's input using exception handling. I need them to only input a positive number, and then I have to return and print out that number.
I have to send a message if the user puts in non-number and I have to send a message if the user puts in a number less than 1. Here is what I have:
def input_validation(prompt):
boolChoice = True
while boolChoice == True:
try:
l = input(prompt)
x = int(l)
boolChoice = False
except ValueError:
print("Not a valid input")
if l.isalpha() == True:
print("Your input is not a number")
elif l.isalnum() == True:
print ("Your input is not completely a positive number")
elif l < 0:
print("Your number is not positive")
print("Try again")
return x
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()
My program works fine until a negative integer gets inputted. It doesn't print the message and then goes through the loop again, it just returns and prints back the negative number, which I don't want. How can I fix this? Thank you.
You can use try...except to check if its an integer or letters
def input_validation(prompt):
while True:
try:
l = int(input(prompt))
if l<0: #=== If value of l is < 0 like -1,-2
print("Not a positive number.")
else:
break
except ValueError:
print("Your input is invalid.")
print("Try again")
return l
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()
try
def input_validation(prompt):
boolChoice = True
while boolChoice == True:
try:
l = input(prompt)
x = int(l)
if x < 0:
print ("Your input is a negative number\n Please enter a postive number")
elif x == 0:
print("Your input is zero\n Please enter a postive number ")
else:
boolChoice = False
except Exception as e:
print("Not a valid input")
if l.isalpha() == True:
print("Your input is not a number")
elif l.isalnum() == True:
print ("Your input is not completely a positive number")
else:
print(f"Failed to accept input due to {e}")
print("Try again")
continue
return x
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()
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!"
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
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)