While loop adding two numbers - python

I want to write a very basic code.
Add two numbers,next add another number given by user,print result,ask for another,add to previous result,print new result.
I've started with that:
a=int(raw_input('give a number'))
b=int(raw_input('give second number'))
y=True
n=False
while input('Continue? (y/n)') != 'n':
c = a + b
print c
b = int(raw_input('give another number'))
Ok I've correct code by your tips.I am appreciate but it stil doesn't work.It add two numbers,print result then ask for another add to result(right now its ok) But when you enter another it add to a and then print.
Maybe you see what is wrong?
And when I enter "n" it didn't end the program

I'd avoid using input() in lieu of raw_input() (safer, and input() was removed in Python 3). With it, you can then turn the input into a number yourself by wrapping it with int() or float(). Then you have a couple possibilities:
Loop forever, and end the loop if you get an error in conversion:
...
while True:
try:
b = int(raw_input('give another number ("x" to exit)'))
except ValueError:
break
...
Or, break if you see some sentinel value, for instance 0 (which conveniently evaluates as false).
a = 1
b = 2
while b:
a = a + b
print a
b = int(raw_input('give another number'))

In most programming languages, including Python, conditions must evaluate to true or false. In this case, the string "condition" will always evaluate to true, because only empty strings evaluate to false. In order to leave the while loop, you must first determine what condition is necessary to discontinue looping. With
while condition: pass
condition can be an if statement, or an object reducible to True or False. Most objects, such as lists, tuples, and strings, evaluate to True when not empty, and False when empty. The other common condition is a comparison between two values; such as
1 < 2
or
a is b

The simplest condition you could check for is EOF (end of file). That would be when the user does not type a number but instead just types a carriage return.
It is up to you to tell the user how to end the program. So you also have to write an instruction to them e.g.
b=input('give another number or type <enter> to end')
I'm a beginner too. I know this solution is simplistic, but it works.
a=int(raw_input('Give a number'))
while True:
print a
userIn = (raw_input('Give another number or <cr> to end)'))
if not userIn:
break
b = int(userIn)
a = a + b

Related

Python for loop won't check each string if it is empty

I'm learning Python and trying to build code where the for loop checks if a string is empty or non-numeric before it proceeds to add everything. How do I prevent it from going there and instead instruct it to loop through b to e?
There are several mistakes in your code:
Have you realized that a, b, c, d, e do not exist inside your function? you're working with a list now, not with the individual variables that only exist outside your function! Accumulate the result of the sum in a variable instead, and print it outside the loop.
To compare a value against None use is, not ==.
The validation for checking if there are duplicates should be done outside the loop.
You must not return on each condition! wait until the loop is over before returning.
if i == None: - this condition will not work if variable == ''
I replaced it with if not all(tuple(map(bool, chocolate))) - it is going to make all empty elements in list bool type. If element is empty it will be False else True. all() function checks if all the elements in list are True - it will return True.
Also i replaced this elif i.isnumeric() == False:, with this not all(tuple(map(str.isdigit, chocolate))), this code will use for each element method isdigit, works like previous one.
So then i think this elif len(chocolate) != len(set(chocolate)): part of your code is quite ok
Instead of this long code billday = int(a) + int(b) + int(c) + int(d) + int(e), you can use sum() function: billday = int(a) + int(b) + int(c) + int(d) + int(e)
And the last one i replaced code in else with f string: f"Your bill for today is {billday}. The total bill for this week is, {5 * billday}."
This is the final code:
b = input("Please input the price of the 2nd chocolate:")
c = input("Please input the price of the 3rd chocolate:")
d = input("Please input the price of the 4th chocolate:")
e = input("Please input the price of the 5th chocolate:")
chocolate = [a, b, c, d, e]
def chocolatebill(chocolate):
if not all(tuple(map(bool, chocolate))) or not all(tuple(map(str.isdigit, chocolate))):
return "You missed a price. Go back and input each price again."
elif len(chocolate) != len(set(chocolate)):
return "Double check your input. The price of each chocolate must be different."
else:
billday = sum(map(int, chocolate))
return f"Your bill for today is {billday}. The total bill for this week is, {5 * billday}."
print(chocolatebill(chocolate))```
You should check your inputs and then compute the result. These are two separate concerns your code has to handle. Do not do these different operations simultaneously. In your case you try return the sum after having checked only the first element of chocolate. Of course this fails if your second element already is e.g. None.
You should also take care about your variable naming. In Python, everything you define outside the function is also known inside the function scope:
x = 1
def f(y):
print(x) # x is known here, will print 1
print(y) # will print 2
f(y=2)
Hence
chocolate = [...]
def f(chocolate): # overwrites the `chocolate` variable defined previously
print(chocolate) # will print 1 instead of the list
f(chocolate=1)
Anyhow, to address your example, you should to something like the following:
A = input("Please input the price of the first chocolate:")
...
E = input("Please input the price of the 5th chocolate:")
CHOCOLATE = [A, B, C, D, E]
# naming convention: global variables, i.e. such declared outside a function/class scope
# should be capitalized
def chocolatebill(chocolates):
_validate_input(chocolates)
bill_day = sum(map(int, chocolates))
bill_week = 5 * bill_day
return f"Your bill for today is {bill_day}. The total bill for this week is {bill_week}."
def _validate_input(chocolates):
if len(chocolates) != len(set(chocolates)):
# this does not need to be checked every time in the for loop
raise Exception("Double check your input. The price of each chocolate must be different.")
for i in chocolates:
if not i: # checks if the input is an empty string (evaluates to True if empty)
raise Exception("You missed a price. Go back and input each price again.")
elif not i.isnumeric(): # instead of `... == False`
raise Exception("You missed a price. Go back and input each price again.")
print(chocolatebill(CHOCOLATE))
A few points here:
No input via the input method always results in an empty string (''), never in None
Instead of returning stuff in the validation, raise an Exception. Ideally you even want dedicated exceptions, e.g. InvalidPriceError like
class InvalidPriceError(Exception):
pass
raise InvalidPriceError("You missed a price. Go back and input each price again.")
This makes your code much more expressive.
sum(map(int, chocolates)) is valid for an arbitrary number of chocolate prices. Here sum returns the sum of elements in a a list-like element. map(int, chocolates) here maps the int method onto the chocolates list, i.e. trys to apply it to each element and returns a list of the result (i.e. a generator to be precise).
I used an underscore before the _validate_input function because it is supposed to be a "private" method. I.e. it is supposed to be only used inside the scope of the chocolatebill function. This is a Python naming. convention.
There is even a lot more to mention here, but I don't want to stress you with too much information. I think this is already enough.

python checking user input for number in a while loop

I have a function below which is part of my big main function, what I want this function to do is that whenever called, I want the function to check if the user input is
a number or not. If it is a number it will return the number and break.
But if it is not a number I want it to loop again and again.when I try to
run it, it gives me unexpected an error:
unexpected eof while parsing
can any body help me what I am missing or how I should rearrange my code? thank you!
def getnumber():
keepgoing==True
while keepgoing:
number = input("input number: ")
result1 = number.isdigit()
if result1 == 1:
return number
break
elif keepgoing==True:
A neater and clearer what to do what you are already doing:
def getnumber():
while True:
number = input("Input number: ")
if number.isdigit():
return number
That's all you need, the extra variables are superfluous and the elif at the end makes no sense. You don't need to check booleans with == True or == 1, you just do if condition:. And nothing happens after return, your break will never be reached.
You don't need the last line:
elif keepgoing==True:
It's waiting for the rest of the file after the :.
Side note, it should be a single = in the first part, and can just be written simpler as well.
def getnumber():
while True:
number = input("input number: ")
result1 = number.isdigit()
if result1:
return number
Since you're inside the while loop, it'll keep executing. Using return will end the while loop, as will breaking and exiting the program. It will wait for input as well each time, though.
While assigning you have used keepgoing == True, I think it should be keepgoing=True
The following solution works on my machine, although I am running Python 2.7
def get_num():
while True: #Loop forever
number_str = raw_input("> Input a number: ") #Get the user input
if number_str.isdigit(): #They entered a number!
return int(number_str) #Cast the string to an integer and return it
I used raw_input rather than input, because raw_input gives you the exact string the user entered, rather than trying to evaluate the text, like input does. (If you pass the 12 to input, you'll get the number 12, but if you pass "12", you'll get the string '12'. And, if you pass my_var, you'll get whatever value was in my_var).
Anyway, you should also know that isdigit() returns whether or not the string has only digits in it and at least one character - that is not the same thing as isNumber(). For instance, "123".isdigit() is True, but "123.0".isdigit() is False. I also simplified your loop logic a bit.

python string and integer comparison

I want to print all the numbers until the given user input using while loop. Example:Enter:5 ==> 1 2 3 4 5 But the below program loops for ever.
user = str(input("Enter : "))
i = 1
while i < user:
print(i)
i = i + 1
ummm while i < int(user):?
Try this instead:
try:
user = int(raw_input('Enter: ')) # Cannot compare a string with an integer.
except ValueError:
print('Input should be an integer!')
i = 1
while True:
i += 1
if i > user:
break
print(i)
Note: In your code, even if we were to explicitly declare the input as an integer it would still not quite work the way you want it to. This is because in your code the while loop stops once i is equal to user (as the condition is while less than... and will thus not print out the final value, user. I therefore modified it so it breaks at the point where i is greater than user, meaning that the last printed value will be equal to user.
Example previous output where user = 5:
1
2
3
4
And with the new code:
1
2
3
4
5
It is however better to use a for loop here, if you are not set on using a while loop:
for i in range(1, user+1):
print(i)
input in Python 2.x will try to evaluate what the user enters, it is equivalent to
user = eval(raw_input(...))
In this case, you are explicitly converting whatever is supplied to a string (with str()). In Python 2.x, strings always compare larger than numbers, so i < user is always True.
It is wiser to use raw_input and convert to int. You can also simplify your code with a for loop:
user = int(raw_input("Enter : "))
for i in range(user):
print(i)
You are comparing an int to a str and that is why you are getting an infinite loop. You should compare the same type of variables
user = int(input("Enter: "))
should work

error while passing the value in python when user enter the value [duplicate]

This question already has answers here:
error while passing the value in python
(2 answers)
Closed 8 years ago.
def row_minimum(x,L):
L=L
if x=='1':
row_minimum1=min(L[0],L[1],L[2],L[3],L[4])
return row_minimum1
elif x=='2':
row_minimum2=min(L[5],L[6],L[7],L[8],L[9])
return row_minimum2
elif x=='3':
row_minimum3=min(L[10],L[11],L[12],L[13],L[14])
return row_minimum3
table(L)
def user_input(y):
if y in ['1','2','3','A','B','C','D','E']:
condition = False
elif y !=['1','2','3','A','B','C','D','E']:
condition = True
while condition == True:
z=input("Enter a row (as a number) or a column (as and uppercase letter):")
if z in ['1','2','3','A','B','C','D','E']:
condition = False
return z
def menu(a,L):
if a==1:
display_table(L)
elif a==2:
x=input("Enter a row (as a number) or a column (as and uppercase letter):")
user_input(x)
print (user_input(x))
if user_input(x) in ['1','2','3']:
mini = row_minimum(x,l)
print ("2")
print("Minimum is:",row_minimum(x,L))
i am getting the value of user_input(x) to none instead i want it to take the value from the user and compare in the if statement and do the minimum.
You have a nested definition for user_input and the first one doesn't return anything, resulting in None being returned. Take out the first or second def.
Note that this is far from the only thing wrong with this program.
Looks like you have a logic issue in user_input() function. If I understood it right, you are trying to check if y is one of the row/column names and set condition to False in this case. Otherwise (if it is not in your list of allowed characters), you want to set the condition to True and re-prompt the user for correct input until she gives you the value you want.
If it is so, you better be checking y if it is NOT in the list. Your code, though, checks if y is not the LIST itself: y !=['1','2','3','A','B','C','D','E']. Even if the user gives you a good value, say 'B' it is still not equal to the list of strings ['1','2','3','A','B','C','D','E'], it is IN this list (thats what you should be checking for). I think, itll help if you rewrite the function to make it something like:
def user_input(y):
if y in ['1','2','3','A','B','C','D','E']:
condition = False
else:
condition = True
while condition == True:
z=input("Enter a row (as a number) or a column (as and uppercase letter):")
if z in ['1','2','3','A','B','C','D','E']:
condition = False
return z
You may also want to experiment with Python style guide and make this code look nicer ;)
Your user_input() function seems like a bad idea. As far as I can tell it is meant to check for bad input, and keeps asking for input until it gets good input. The problem is, it only returns if the initial input was bad, if the initial input was good, then the function does not return.
You can just get rid of this function altogether, since you end up checking the input anyway. you can just do:
def menu(a,L):
if a==1:
display_table(L)
elif a==2:
while True:
x=input("Enter a row (as a number) or a column (as and uppercase letter):")
print x
if x in ['1','2','3']:
mini = row_minimum(x,l)
print ("2")
print("Minimum is:",row_minimum(x,L))
break
elif x in ['A','B','C','D','E']:
whatever you want to do here
break

Extract element from a shuffled list (based off of user's input)

I have something like this:
s=[7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
random.shuffle(s)
ans=input('Press a number from 0 to 9')
I want to associate the input number ans with the s[ans] element. I can do it with 10 if loops, is this the only chance? //SOLVED this
Done that, I want to repeat the random extraction until user digits something like "stop" (here I am) and then sum all the value extracted until "stop" string. How can I do this last point?
Thanks all!
from random import choice
elem = choice (some_list)
If you are only trying to select a random number (and asking for input is only a means to achieve that goal), then you should really look into random.choice. It does exactly what you need, and you won't have to spend time shuffling your list
You can directly access values of an array like so:
s[ans]
But first you may have to convert ans to an integer (and handle cases where a user sends something that's not a number!)
try:
i = int(s)
except ValueError:
i = 0
You've edited your question to declare the original version "solved" and then added a second one. In the future, don't do that; accept the answer that solved the problem for you, then create a new question. (And you should still accept the answer that solved your original problem!) But this time only, here's a second answer:
Done that, I want to repeat the random extraction until user digits something like "stop" (here I am) and then sum all the value extracted until "stop" string. How can I do this last point?
I'm assuming you're on Python 2, and using the input function so the user can just type 2 and you get the number 2 instead of the string "2". (If you're using Python 3, input works like Python 2's raw_input, so see the second version.)
So:
s=[7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
random.shuffle(s)
values = []
while True:
ans=input('Press a number from 0 to 9')
if ans == 'stop':
break
values.append(s[ans])
print sum(values)
Note that the user will have to type "stop" with the quotes this way. If the user instead types stop (or 10, for that matter), the program will quit with an exception. It would be much better to use raw_input instead, and do something like this:
s=[7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
random.shuffle(s)
values = []
while True:
ans=raw_input('Press a number from 0 to 9, or stop when done')
if ans == 'stop':
break
try:
index = int(ans)
values.append(s[ans])
except ValueError:
print '{} is not a number or the word stop'.format(ans)
except IndexError:
print '{} is not between 0 and 9.'.format(ans)
print sum(values)
You may recognize that this values = [], while, values.append pattern is exactly what list comprehensions and iterators are for. And you can easily factor out all the user input into a generator function that just yields each s[ans], and then just print sum(userChoices()), without having to build up a list at all. But I'll leave that as an exercise for the reader.
ans = 0
s = [7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
ans_sums = []
while ans != 'stop': # while the input is not 'stop'
random.shuffle(s)
ans = raw_input('Press a number from 0 to 9: ') # this returns the input as a string
if ans == 'stop':
break
else:
ans_sums.append(int(s[ans])) # adds s[ans] to ans_sums.
# it must be converted to an integer first because raw_input returns it as a string
return sum(s[ans])
Alternatively, you can do something like:
ans = 0
s = [7777,5454,75000,4545,787,16000,1000,9888,7854,12223]
ans_sums = 0
while ans != 'stop': # while the input is not 'stop'
random.shuffle(s)
ans = input('Press a number from 0 to 9: ')
if ans == 'stop':
break
else:
ans_sums += s[ans] # adds s[ans] to ans_sums
return ans_sums
This avoids creating a list and accomplishes the same job: finds the sum of all the input.

Categories