I don't understand why I cannot go out from simple loop.
Here is the code:
a = 1
#tip checking loop
while a != 0:
# tip value question - not defined as integer to be able to get empty value
b = input("Give me the tip quantinty which you gave to Johnnemy 'hundred' Collins :")
# loop checking if value has been given
if b:
#if b is given - checking how much it is
if int(b) >= 100:
print("\nJohnny says : SUPER!")
elif int(b) < 100:
print("\nJohnny says : Next time I spit in your soup")
elif b == '0':
a = 0
else:
print("You need to tell how much you tipped")
print("\n\nZERO ? this is the end of this conversation")
Thanks for your help.
This should solve your problem:
a = 1
#tip checking loop
while a != 0:
# tip value question - not defined as integer to be able to get empty value
b = input("Give me the tip quantinty which you gave to Johnnemy 'hundred' Collins :")
# loop checking if value has been given
if b:
#if b is given - checking how much it is
if int(b) >= 100:
print("\nJohnny says : SUPER!")
elif int(b) < 100:
print("\nJohnny says : Next time I spit in your soup")
if b == '0':
a = 0
else:
print("You need to tell how much you tipped")
print("\n\nZERO ? this is the end of this conversation")
the following condition
if b == '0':
a = 0
should be in the same scope as the if b: condition.
You cant break out of the loop because. actually, there is nobreak. You need to putbreak` command at the end of every loop branch where you would like to stop looping in order to break out of the loop.
Also, you could break out assigning a = 0 instead of the break.
Related
the code just doesn't work, I can not understand what is wrong with the +=
taken = 1
first = int(input(" "))
while taken <= 6:
print(1)
print(taken+=1)
the syntax error just pops up and the + is highlighted red, I have tried looking however the only question I found was where it did not work because of the global the person put before the thing they were += onto.
This is because variable += val is shorthand for
variable = variable + val
As this is an assignment expression, and doesn't return anything, that's why this is considered to be a syntax error.
Note 1: This has nothing to do with while loop, it's universally unaccepted
Note 2: Python doesn't support ++ / -- operators as of now
So, do this instead:
taken = 1
first = int(input(" "))
while taken <= 6:
taken+=1
print(f"1\n{taken}")
Try to write taken += 1 in the row above and than print taken.
taken = 1
first = int(input(" "))
while taken <= 6:
print(1)
taken += 1
print(taken)
you simply cannot do that.
you can do this instead :
taken = 1
first = int(input(" "))
while taken <= 6:
print(1)
taken += 1
print(taken)
So after finishing the code, I would like to have an option where the user would like to try again by typing Y/n or N/n. How do I make it?
a=int(input('enter value of n: '))
i = 1
sum=0
while a < 1 or a > 300:
print(a, 'is not in the range 1-300')
exit()
for a in range(1,a+1):
print (a, end = ' ')
while i<=a:
if i%3==0 or i%5==0:
sum=sum+i
i=i+1
print('\nsum of all multiples of 3 and 5 is:',sum)
repeat=str(input('Would you like to try again? Y/N?'))
Here's a simple way to do it (keeping your code structure) without any functions or jargon (for beginners :]):
from sys import exit # Just something to exit your code
repeat = 'y' # So it starts the first time
while repeat.lower() == 'y': # repeat.lower() -> convert the string 'repeat' to lowercase, incase user inputs 'Y'. you could also use the or keyword here though
n = int(input("Enter value of n:\n>>> "))
if n < 1 or n > 300:
print("'n' must be between 1 - 300, not " + n) # You could use f-strings, check them out!
exit()
sum_of_multiples = 0
# I'm combining your for and while loop as shown below
for i in range(1, n + 1): # Don't name your 'i' and 'n' variables the same -> you did so with 'a'
print(i, end=', ') # There are cleaner ways to do this but I'm assuming this is what you want
if i % 3 == 0 or i % 5 == 0:
sum_of_multiples += i
# Printing output
print(f"\nSum of all multiples of 3 and 5 is: {sum_of_multiples}") # This is called an f-string
repeat = input("\nDo you want to go again?\n>>> ") # If you don't input Y/y, the outer while loop will break and terminate
print("Thank you for running me!") # Prints after the program finishes running
Note that you don't need the exit() when checking if n is within 1 - 300, you could also just use break.
EDIT (WITH BREAK)
Program without from sys import exit below:
repeat = 'y' # So it starts the first time
while repeat.lower() == 'y': # repeat.lower() -> convert the string 'repeat' to lowercase, incase user inputs 'Y'. you could also use the or keyword here though
n = int(input("Enter value of n:\n>>> "))
if n < 1 or n > 300:
print("'n' must be between 1 - 300, not " + n) # You could use f-strings, check them out!
break # This will mean that "Thank you for running me!" gets printed even if your input is wrong
sum_of_multiples = 0
# I'm combining your for and while loop as shown below
for i in range(1, n + 1): # Don't name your 'i' and 'n' variables the same -> you did so with 'a'
print(i, end=', ') # There are cleaner ways to do this but I'm assuming this is what you want
if i % 3 == 0 or i % 5 == 0:
sum_of_multiples += i
# Printing output
print(f"\nSum of all multiples of 3 and 5 is: {sum_of_multiples}") # This is called an f-string
repeat = input("\nDo you want to go again?\n>>> ") # If you don't input Y/y, the outer while loop will break and terminate
print("Thank you for running me!") # Prints after the program finishes running
Hope this helped!
gone = []
turn = 0
def play(XO,player):
while 0 == 0:
num = input("\n"+player+" enter an available number where you want to put an '"+XO+"'.\n > ")
while ((str(num).isdigit() == False) or ((int(num) <= 9 and int(num) >= 1) == False)) or (num in gone):
num = input("\nValue was not an available number.\n"+player+" enter an available number where you want to put an '"+XO+"'.\n > ")
So, in the second while loop I'm having a problem. You see the (num in gone) part? I'm trying to make it so if num is found in the gone list then it will be true, but it isn't working. Instead it passes through it.
I've tested to see if (not num in gone) applies the opposite effect, and it does!
If you need to see my entire code I can post it... btw this is for a Tic-Tac-Toe program I am making.
You're putting too much logic in one condition. Splitting it up will help you a lot.
Try something like this:
gone = []
turn = 0
def play(XO, player):
while True:
num = input(
f"\n{player} enter an available number "
f"where you want to put an '{XO}'.\n > "
)
try:
num = int(num)
except ValueError:
print("Not a valid number, try again")
continue
if num < 1 or num > 9:
print("Number not in correct range, try again")
continue
if num in gone:
print("Number already gone, try again")
continue
gone.append(num)
turn += 1
My code seems to be stuck in this while loop forever:
array = []
b = 1
while b != 0:
b = int(input("please enter whole numbers "))
array += [b]
print (array)
The meaning of the code is to put user inputs into an array and stop when user enter 0. I don't know why the loop manages to continue the code even though the condition is false. I thought as long as condition is false, python will stop right there!
I keep getting 0 as an element in the array when I don't want it to be in.
I have modified magamongo's answer a little in order to not use break, but you could also use it as in quamrana's answer:
array = []
b = 1
while b != 0:
b = int(input("please enter whole numbers "))
array += [b]
array = array[:-1]
print(array)
I think you could use your own exit condition and not rely on the while statement itself stopping:
array = []
while True: # never exit here
b = int(input("please enter whole numbers "))
if b == 0:
break # exit the loop here
array += [b]
print (array)
"break" helps you to do that.
array=[1]
while array[-1] != 0:
b = int(input("please enter a whole number"))
array += [b]
if array[-1] == 0:
print(array[1:-1])
break
Hope this helps :)
I am trying to solve a simple exercise to identify if the parentheses used in an equation are correct, but when I try input an equation like this a+(b*c)-2-a ,
I have to press enter twice. This only happens inside the EOF block.
What could be wrong? Thank you very much!
while True:
try:
x = input()
z = []
for y in x:
if y == '(':
z.append(y)
elif y == ')':
z.append(y)
q = ''.join(z)
d = 0
while d == 0:
if q.count('()') != 0:
q = q.replace('()', '')
else:
if q.count('(') >= 1 or q.count(')') >= 1:
print('incorrect')
else:
print('correct')
d = 1
except:
break
You have two while True loops. On the first time around, you enter while d == 0: with a valid balance of parentheses meaning that if q.count('()') != 0: is True. That while loop then breaks, because d is incremented by 1. But the print statements require if q.count('()') != 0: to be False. Therefore, you start the whole loop again due to the very first while True:, press enter (which is effectively an invalid input for your algorithm) which allows you to get to:
else:
if q.count('(') >= 1 or q.count(')') >= 1:
print('incorrect')
else:
print('correct')