I'm created simple bank programme where i create four methods for the transaction. below is my code. the problem is it shows an error that "break outside the loop".
kindly help, I'm new to python.
bal=0
def deposit():
global bal
amount=input('Enter Deposit Amount: ')
bal=bal+amount
def withdraw():
global bal
amount=input('Enter Withdraw Amount: ')
bal=bal-amount
def checkbal():
global bal
print bal
def conti():
c=raw_input('Do You Wana Continue y/n....')
if c=='y':
main()
else:
break
def main():
print '---Welcome To ABC Bank---'
print 'Enter 1 For Deposit:'
print 'Enter 2 For Withdraw:'
print 'Enter 3 For Balance Check:'
print 'Enter 4 For Exit:'
choice= input('Enter Your Choice :')
if(choice==1):
deposit()
elif(choice==2):
withdraw()
elif(choice==3):
checkbal()
else:
print 'Invalid Entry'
conti()
main()
break outside the loop
it means you use break not inside a loop. break is only used inside a loop when you want to stop the iteration.
So, in this code:
def conti():
c=raw_input('Do You Wana Continue y/n....')
if c=='y':
main()
else:
break # should be exit()
If you want to exit from program if user choose not to continue, then break should be exit()
or return if you just want to exit from conti() function. (But it means you still go to main() function)
def conti():
c=raw_input('Do You Wana Continue y/n....')
if c=='y':
main()
else:
break
You can use return statement in place of break because break will come outside the loop whereas return will return you to main function else if you want to come out of program you can simply use exit()
Related
I've provided the code below.
What is want to do is run the first input box where it will check the condition if true it will go for next input(), but if not it will run the code again. The problem is first input() is running fine, but second one is not getting out of the loop where I'm checking if the input is integer or not
class AC ():
def __init__(self):
self.owner=input("Enter The Name: ")
while True:
if self.owner.isalpha():
self.balance=(input("Enter The Amount: "))
def lol():
while True:
if self.balance.isdigit():
break
else:
print("Enter The Amount: ")
lol()
break
else:
AC()
break
The problem is that your lol() function is never being called for, so it will stay in the first while-loop indefinitely.
lol() function is never being called as Tim said
input() function return string value you can change str to float
try this:
`
def __init__(self):
self.owner = input("Enter The Name: ")
while True:
if self.owner.isalpha():
self.balance = input("Enter The Amount: ")
def lol():
while True:
try:
self.balance = float(self.balance)
except ValueError:
break
if self.balance.isdigit():
break
else:
lol()
else:
AC()
break
I have written a piece of code with a while loop, that I want to run until the user enters the string exit. However, I don't want the loop to be stopped for a repeat prompt after every loop cycle. How can I achieve this?
Currently the code loops correctly, however it does not respond to exit once in the while loop.
if __name__ == '__main__':
prog_question = input("Enter exit to quit the heat tracker after a cycle.")
while name == True:
if prog_question == "exit":
name = False
break
else:
temperature_info = measure_temp()
if temperature_info[1] == "No error":
if int(temperature_info[0]) < int(check_temp):
heater("on",check_period*60)
else:
heater("off",check_period*60)
else:
measure_temp()
You are trying to let the user interrupt an infinite loop.
Your idea using input has the disadvantage that the user needs to actually input something on each iteration.
It might be more interesting to use try/except for that:
from time import sleep
try:
print("Hit Ctrl-C to stop the program")
while True:
print("still running")
sleep(1)
except KeyboardInterrupt:
print("this is the end")
Or you could also have a look at the module signal.
Just move the prompt to inside of the loop.
name = True
while name:
prog_question = input("Enter exit to quit the heat tracker after a cycle.")
if prog_question == "exit":
name = False
break
else:
...
I'm trying to develop a program wherein at the finish of the game the user will input "Yes" to make the game restart, while if the user inputed "Not" the game will end. For my tries, I can't seem to figure out how to make the program work. I'm quite unsure if a double while True is possible. Also, it seems like when I enter an integer the game suddenly doesn't work but when I input an invalidoutpit the message "Error, the inputed value is invalid, try again" seems to work fine. In need of help, Thank You!!
import random
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
while True:
while True:
try:
P1=="O" or P2=="O" or P3=="O" or P4=="O"
print("Here is your Clue :) :", P1,P2,P3,P4)
guess=int(input("\nTry and Guess the Numbers :). "))
except ValueError:
print("Error, the inputed value is invalid, try again")
continue
else:
guess1=int(guess[0])
guess2=int(guess[1])
guess3=int(guess[2])
guess4=int(guess[3])
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
else:
print("Well Done! You Won MASTERMIND! :D")
answer=input("Would you like to play again? (Yes or No) ")
if answer==Yes:
print ('Yay')
continue
else:
print ('Goodbye!')
break
Wrap your game in a function eg:
import sys
def game():
#game code goes here#
Then at the end, call the function to restart the game.
if answer=='Yes': # You forgot to add single/double inverted comma's around Yes
print ('Yay')
game() # calls function game(), hence restarts the game
else:
print ('Goodbye!')
sys.exit(0) # end game
try this
import random
def game():
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
gueses=[]
while len(gueses)<=3:
try:
P1=="O" or P2=="O" or P3=="O" or P4=="O"
print("Here is your Clue :) :", P1,P2,P3,P4)
guess=int(input("\nTry and Guess the Numbers :). "))
gueses.append(guess)
except ValueError:
print("Error, the inputed value is invalid, try again")
continue
guess1=gueses[0]
guess2=gueses[1]
guess3=gueses[2]
guess4=gueses[3]
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
if P1=="x" and P2=="x" and P3=="x" and P4=="x":
print("you won")
else:
print("YOUE LOSE")
print("TRUE ANSWERS", A1,A2,A3,A4)
print("YOUR ANSWER", gueses)
game()
answer=input("Would you like to play again? (Yes or No) ")
if answer=="Yes":
print ('Yay')
game()
else:
print ('Goodbye!')
The previous answers are good starts, but lacking some other important issues. I would, as the others stated, start by wrapping your game code in a function and having it called recursively. There are other issues in the guess=int(input("\nTry and Guess the Numbers :). ")). This takes one integer as the input, not an array of integers. The simplest solution is to turn this into 4 separate prompts, one for each guess. I would also narrow the scope of your error test. I've included working code, but I would read through it and make sure you understand the logic and call flow.
import random
def game():
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
while True:
if P1=="O" or P2=="O" or P3=="O" or P4=="O":
print("Here is your Clue :) :")
print(P1,P2,P3,P4)
try:
guess1=int(input("\nGuess 1 :). "))
guess2=int(input("\nGuess 2 :). "))
guess3=int(input("\nGuess 3 :). "))
guess4=int(input("\nGuess 4 :). "))
except ValueError:
print("Invalid Input")
continue
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
else:
print("Well Done! You Won MASTERMIND! :D")
break
answer=input("Would you like to play again? (Yes or No) ")
if answer=="Yes":
print('Yay')
game()
else:
print('Goodbye!')
game()
Here I want to exit the if block, but I don't want to use sys.exit() as it will terminate the program. I have a few lines to be executed at the end, hence I want to exit the if block only.
I can't use break as it flags an error "break outside loop".
In this I want the program to exit the block at "if (retry == 3)", line 55 and print the lines at the end. However, it’s not happening until it is using sys.exit(), where it’s completely exiting the program.
import random
import sys
loop = ''
retry = 0
loop = input('Do you want to play lottery? yes/no: ')
if loop != 'yes':
print('Thank you!! Visit again.')
sys.exit()
fireball = input('Do you want to play fireball? yes/no: ')
lotto_numbers = sorted(random.sample(range(0, 4), 3))
fireball_number = random.randint(0, 3)
while loop == 'yes':
user_input1 = int(input('Please enter the first number: '))
user_input2 = int(input('Please enter the second number: '))
user_input3 = int(input('Please enter the third number: '))
print('Your numbers are: ', user_input1, user_input2, user_input3)
def check():
if lotto_numbers != [user_input1, user_input2, user_input3]:
return False
else:
return True
def fbcheck():
if lotto_numbers == [user_input1, user_input2, fireball_number]:
return True
elif lotto_numbers == [fireball_number, user_input2, user_input3]:
return True
elif lotto_numbers == [user_input1, fireball_number, user_input3]:
return True
else:
return False
retry += 1
result = check()
if (result == True):
print("Congratulations!! You won!!")
else:
print("Oops!! You lost.")
if (fireball == 'yes'):
fb_result = fbcheck()
if (fb_result == True):
print("Congratulations, you won a fireball!!")
else:
print("Sorry, you lost the fireball.")
print('No of retries remaining: ', (3 - retry))
if (retry == 3):
sys.exit()
loop = input('Do you want to try again? yes/no: ')
continue
else:
pass
print("Winning combination: ", lotto_numbers)
if (fireball == 'yes'):
print('fireball no: ', fireball_number)
print('Thank you!! Visit again.')
You don't need anything at all. Code inside the if block will execute and the script will run code after the if block.
if is not a loop, so it doesn't repeat. To proceed to further code, just remember to stop the indent; that's all.
I.e.:
if some_condition:
# Do stuff
# Stop indent and do some more stuff
I think I gotcha your willing.
You want to execute something after the if condition is executed? So, create a subtask, and call it!
def finish_program():
print("something")
a = "foo"
print("finish program")
loop = input('Do u want to play lottery ? yes/no : ')
if loop!='yes':
print('Thank you!! visit again.')
finish_program()
Im still very new when it comes to python so be easy on me. Whenever I test this code it comes back with "None" instead of the input entered. Any idea why it could be happening?
def inputLandValue():
while(1):
try:
value=int(input('Please enter the value of the property '))
break
except:
print('Please enter a whole number (10000)')
return value
def main():
while(1):
landValue = inputLandValue()
print(landValue)
doMoreStuff = input('Do you want to continue? y/n ')
if(doMoreStuff.lower() != 'y'):
break
main()
input()
You indented your return value line too far. It is part of the except: handler, so it is only executed when you have no value! It should be outside the while loop:
def inputLandValue():
while(1):
try:
value=int(input('Please enter the value of the property '))
break
except:
print('Please enter a whole number (10000)')
return value
or replace the break with return value:
def inputLandValue():
while(1):
try:
value=int(input('Please enter the value of the property '))
return value
except:
print('Please enter a whole number (10000)')
You should really only catch ValueError however; this isn't Pokemon, don't try to catch'm all:
except ValueError:
You can fix your problem by just putting 'return value' in place of the break in main().