So I'm trying to use a break in my code for a choice to quit the program, but when I run it, I get "break outside Loop". Is there a way to fix it? I've tried the return command or other commands from other questions similar to this one, but I had no luck with them. Here's the piece of code I'm referring to:
v1 = []
v2 = []
while True:
print('Welcome to vector arithmetic! Below is a list of available operations.')
print('1. Enter values for your vectors')
print('2. Print vectors')
print('3. Vector dimensionality')
print('4. Add vectors')
print('5. Compute dot product of vectors')
print('6. Compute magnitude of vectors')
print('7. Quit')
choice = int(input('Enter the number corresponding to your choice: '))
if choice == 7:
break
elif choice == 1:
pass
elif choice == 2:
pass
elif choice == 3:
pass
elif choice == 4:
pass
elif choice == 5:
pass
elif choice == 6:
pass
else:
print('Invalid choice, try again')
In python, the indentation and white space matters. As the comment above mentions, I just moved that whole block below your while statement into the correct indentation and works as you expect.
v1 = []
v2 = []
while True:
print('Welcome to vector arithmetic! Below is a list of available operations.')
print('1. Enter values for your vectors')
print('2. Print vectors')
print('3. Vector dimensionality')
print('4. Add vectors')
print('5. Compute dot product of vectors')
print('6. Compute magnitude of vectors')
print('7. Quit')
choice = int(input('Enter the number corresponding to your choice: '))
if choice == 7:
break
elif choice == 1:
pass
elif choice == 2:
pass
elif choice == 3:
pass
elif choice == 4:
pass
elif choice == 5:
pass
elif choice == 6:
pass
else:
print('Invalid choice, try again')
Your code is not properly indented:
v1 = []
v2 = []
while True:
print('Welcome to vector arithmetic! Below is a list of available operations.')
print('1. Enter values for your vectors')
print('2. Print vectors')
print('3. Vector dimensionality')
print('4. Add vectors')
print('5. Compute dot product of vectors')
print('6. Compute magnitude of vectors')
print('7. Quit')
choice = int(input('Enter the number corresponding to your choice: '))
if choice == 7:
break
elif choice == 1:
pass
elif choice == 2:
pass
elif choice == 3:
pass
elif choice == 4:
pass
elif choice == 5:
pass
elif choice == 6:
pass
else:
print('Invalid choice, try again')
As you can see, indentation in python is very important.
Seems to me that you are having an indentation error, in that case you need to make sure that while you enter anything in a loop, function, or class that it is properly indented.
v1 = []
v2 = []
while True:
print('Welcome to vector arithmetic! Below is a list of available operations.')
print('1. Enter values for your vectors')
print('2. Print vectors')
print('3. Vector dimensionality')
print('4. Add vectors')
print('5. Compute dot product of vectors')
print('6. Compute magnitude of vectors')
print('7. Quit')
choice = int(input('Enter the number corresponding to your choice: '))
if choice == 7:
break
elif choice == 1:
pass
elif choice == 2:
pass
elif choice == 3:
pass
elif choice == 4:
pass
elif choice == 5:
pass
elif choice == 6:
pass
else:
print('Invalid choice, try again')
Also, I do not recommend that you use break in loops as they can be problematic if they are not implemented properly. Instead, try using quit
Related
I've been attempting to code this program for the past half a month or so but I'm stumped and I need to make substantial progress soon to meet my deadline, any help/advice would be appreciated. Apologies for the bad formatting, thanks for any help you can provide.
def main():
choice = printMenu()
print(choice)
def menu():
print("NRAS Eligibility Calculator")
print("[1] Display Household Income Limits")
print("[2] Calculate Total Income")
print("[3] Calculate Eligibility")
print("[4]: Exit")
def choice = int(input("Enter your choice: "))
while choice !=0:
elif choice== 1:
print("$52,324")
elif choice== 2:
def add_num(a,b):
sum=a+b;
return sum;
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
print("Your total income is",add_num(num1,num2))
elif choice== 3:
def add_num(a,b):
sum=a+b;
return sum;
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
if sum <= "52,324"
print("You're eligible for NRAS!")
else
print ("Sadly, you're not eligible.")
elif choice== 4:
quit()
else:
print("Invalid option.")
print("Thank you for using this calculator.")
I have corrected most of the mistakes and the code works fine. I have also added comments to highlight the changes I made.
But there a lot of questionable things that were going on in this code. I suggest you to look into python syntax properly.
def add_num(a,b):
sum = a+b
return sum
def menu():
print("NRAS Eligibility Calculator")
print("[1] Display Household Income Limits")
print("[2] Calculate Total Income")
print("[3] Calculate Eligibility")
print("[4] Exit")
ch = int(input('Enter your choice : ')) # added a variable to read the choice.
return ch # then return this choice when this function is called.
def choice(choice):
while choice != 0:
if choice== 1: # changed the elif to if.
print("$52,324")
break # added a break due to infinite loop
elif choice == 2:
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
print("Your total income is",add_num(num1,num2))
elif choice == 3:
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
SUM = add_num(num1, num2) # calling the add_num function here.
if SUM <= 52324: # changed this to int type instead of a string.
print("You're eligible for NRAS!")
else:
print ("Sadly, you're not eligible.")
elif choice == 4:
quit()
else:
print("Invalid option.")
print("Thank you for using this calculator.")
def main():
ch = menu()
choice(ch)
if __name__ == "__main__": # this is how you call a main() in python.
main()
When I attempt to call the menu function in each choice after the conversion is run, it will take me back to the menu but will only convert in the original selection. If I choose option 1 first after the convertCelsius function is ran and it takes me back to the menu function, any choice will still only convert to celsius. How do I get call the menu function so I can run each choice again.
def menu():
print("1. Celsius to Fahrenheit")
print('2. Fahrenheit to Celsius')
print('3. Exit')
pick = int(input('Enter a choice: '))
return pick
def convertCelsius():
temperature = float(input('Write temp to convert from Celsius to Fahrenheit: '))
fahrenheitTemperature = ((temperature * 1.8) + 32)
print('Fahrenheit temperature is: ',fahrenheitTemperature)
def convertFahrenheit():
temperature = float(input('Write tempt to convert from Fahrenheit to Celsius: '))
celsiusTemperature = ((temperature - 32)* 5/9)
print("Celsius temperature is: ", celsiusTemperature)
def main():
choice = menu()
while choice != 3:
if choice == 1:
convertCelsius()
menu()
elif choice == 2:
convertFahrenheit()
menu()
elif choice==3:
choice = menu()
main()
I think you meant to do choice = menu() every time:
def main():
choice = menu()
while choice != 3:
if choice == 1:
convertCelsius()
elif choice == 2:
convertFahrenheit()
choice = menu()
I have a menu function and choice function that both worked. There are 3 menu choices. 1 and 3 worked properly at one point. 2 never has. I don't know what I did to mess it up, but when I run the module to test through IDLE, it doesn't ever work past the first prompting to enter my menu choice number. It should complete an if statement, then restart.
I don't know what else to try. I wish I knew what I changed to mess it up.
tribbles = 1
modulus = 2
closer= 3
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
menu()
def choice():
choice = int(input('\n Enter the number of your menu choice: ')
if choice == tribbles:
bars = int(input('\n How many bars of gold-pressed latinum do you have? '))
print('\n You can buy ',bars * 5000 / 1000,' Tribbles.')
menu()
choice()
elif choice == modulus:
num = int(input('\n Enter any number:'))
o_e = num % 2
if num == 0:
print(num,' is an even number')
elif num == 1:
print(num,' is an odd number')
menu()
choice()
elif choice == closer:
print('\n Thanks for playing!')
exit()
else:
print('Invalid entry. Please try again...')
menu()
choice()
print(' ')
choice = int(input('\n Enter the number of your menu choice: '))
I expect it to return with the string plus all formula results, then asking again, unless option 3 was selected and exit() is performed. However it returns with "Enter the number of your menu choice: " after the first input, then it returns blank after choosing any other choice on the second prompt.f
First things first!
It's good practice to define all functions at the top of the file, and call those functions at the bottom! Second your indenting is incorrect, i'm going to assume that happened after you pasted it here. Finally, you never actually call the function choice() you instead overwrite it with the result of a prompt.
Below i'm going to correct these issues.
tribbles = 1
modulus = 2
closer= 3
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
choice() #added call to choice here because you always call choice after menu
def choice():
my_choice = int(raw_input('\nEnter the number of your menu choice: ')) #you were missing a ) here! and you were overwriting the function choice again
#changed choice var to my_choice everywhere
if my_choice == tribbles:
bars = int(raw_input('\nHow many bars of gold-pressed latinum do you have? '))
print('\n You can buy ',bars * 5000 / 1000,' Tribbles.')
menu()
elif my_choice == modulus:
num = int(raw_input('\n Enter any number:'))
o_e = num % 2
if num == 0:
print(num,' is an even number')
elif num == 1:
print(num,' is an odd number')
menu()
elif choice == closer:
print('\n Thanks for playing!')
exit()
else:
print('Invalid entry. Please try again...')
menu()
print(' ')
if __name__ == "__main__": #standard way to begin. This makes sure this is being called from this file and not when being imported. And it looks pretty!
menu()
Before you check the value of choice, the variable choice is not declared. You have to catch your input before the line: if choice == tribbles:. Your are only defining a function which even don't return the value of your choice or set a global variable.
Try this:
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
menu()
choice = int(input('\n Enter the number of your menu choice: '))
if choice == tribbles:
...
I'm am writing a simple program that look something like this:
while True:
choice = float(input("options: "))
if choice == 1:
# Do something
elif choice == 2:
# Do something
elif choice == 3: # <--- seems redudant
while choice == 3:
choice_return = input("do you want to return?: ")
if choice_return == "yes":
choice = None
else:
pass
elif choice == 4:
break
As noted in the the code, the "elif statment" seems redundant because it has the same conditions as the "while loop" below. You can of course simply write the code as follows:
while True:
choice = float(input("options: "))
if choice == 1:
# Do something
elif choice == 2:
# Do something
elif choice == 4:
break
while choice == 3: <--- three after four, no!!!
choice_return = input("do you want to return?: ")
if choice_return == "yes":
choice = None
else:
pass
which don't look to bad in this example, but in the actual code, it kinda ruins the structuring (and my OCD don't allow for that). Is there a way I can remove the redundancy while maintaining order?
NB. assume the "choice number" is fixed.
You can stick to the if/elif structure and clean up things by wrapping the logic of elif choice == 3 in a function and using a while True recipe in the function:
def myfunc()
while True:
choice_return = input("do you want to return?: ")
if choice_return == "yes":
return None # None here is redundant
while True:
choice = float(input("options: "))
if choice == 1:
...
elif choice == 3:
choice = myfunc()
...
There doesn't seem to be any reason to use choice as the condition in the while loop. Restructure it so it uses break to stop the loop when appropriate.
elif choice == 3: # <--- seems redudant
while True:
choice_return = input("do you want to return?: ")
if choice_return == "yes":
break
Put the inner while loop into a function, the code will then be much cleaner. You will still have both tests, but integer comparisons are fast - so why are you using float?
Better yet, if you could but every "case" into a function you could use a list of functions.
# Functions return True to break out of the loop, otherwise False
def case1():
# Do something
def case2():
# Do something
def case3():
# Do something
def case4():
# Do something
cases = [case1, case2, case3, case4]
while True:
choice = int(input("options: "))
if choice < len(cases) and choice >= 0:
if cases[choice]():
break
else:
print("Invalid option", choice)
I was given a task to write a program in a pretty basic python style. The program is supposed to ask the user whether they want to 1. Flip a coin, or 2. Pick a card.
Then uses an IF to check what the user picked. If it was one, it's supposed to randomly generate heads or tails and print what it got.
If the choice was 2, it asks the user to choose a suit, then generates a number between 1 and 13 (ace to king) and prints 'You picked [value] of [suit]'
import random
print('1. Flip a coin')
print('2. Pick a card')
choice = int(input('Enter a coice :'))
if choice == 1:
Hort = ''
HorT == random.randint(0,1)
if HorT == "0":
print('You got Heads')
elif HorT == "1":
print('You got Tails')
elif choice == 2:
print()
print('1. Hearts')
print('2. Clubs')
print('3. Diamonds')
print('4. Spades')
print()
suitno = ''
suitno ==int(input('Choose a suit'))
if suitno == "1":
suit == "Hearts"
elif suitno == '2':
suit == 'Clubs'
elif suitno == '3':
suit == 'Diamonds'
elif suitno == '4':
suit == 'Spades'
value = ''
value == random.randint(1,13)
print()
print('You picked', value, 'of', suit)
as you can see, it's basic but I was asked to follow the pseudo-code as closely as I could. It stops right at the beginning. I enter then number for the choice, and it just ends.
EDIT: I have amended the code to show what I have changed.
You have 2 problems:
choice = int(input('Enter a coice :'))
if choice == '1':
Here you are comparing integer choice and string '1' values.
And the second problem that you have a lot of constructions that looks like:
if a == '1':
some_statement
elif a == '2:
some statement
...
Such switch can be formed in python with dictionaries:
import random
coin_sides = {
'1': 'Heads',
'2': 'Tails'
}
card_suits = {
'1': 'Hearts',
'2': 'Clubs',
'3': 'Diamonds',
'4': 'Spades'
}
print('1. Flip a coin')
print('2. Pick a card')
choice = input('Enter a coice :')
if choice == '1':
side = random.randint(0,1)
print 'You got {0}'.format(coin_sides.get(side))
elif choice == '2':
print()
print('1. Hearts')
print('2. Clubs')
print('3. Diamonds')
print('4. Spades')
print()
suitno = input('Choose a suit')
suit = card_suits.get(suitno)
value = random.randint(1,13)
print()
print('You picked', value, 'of', suit)
Since other answers quite adequately critique your card-picking design, I'll only post the bit I had about your coin flip.
Flip a Coin
The outcome of this program is a statment:
You got {heads|tails}.
Thus, we are only interested in the strings 'heads' or 'tails'. Since explicit is better than implicit:
outcomes = ('heads', 'tails')
print('You got {}.'.format(random.choice(outcomes)))
is all you need.
Common mistakes:
== used for comparison and not for assignment e.g 4 == 4 is True
variable of int type will never be equal to string e.g 4 == '4' is False. This is the reason why your if statements didn't execute.
There's no need in variable initialization before getting input().
It usually better to have else if you have elif.
Dirty, but complete fix:
import random
print('1. Flip a coin')
print('2. Pick a card')
choice = int(input('Enter a coice: '))
if choice == 1:
HorT = random.randint(0,1)
if HorT == 0:
print('You got Heads')
else:
print('You got Tails')
elif choice == 2:
print()
print('1. Hearts')
print('2. Clubs')
print('3. Diamonds')
print('4. Spades')
print()
suitno = int(input('Choose a suit: '))
if suitno == 1:
suit = "Hearts"
elif suitno == 2:
suit = 'Clubs'
elif suitno == 3:
suit = 'Diamonds'
else:
suit = 'Spades'
value = random.randint(1, 13)
print()
print('You picked', value, 'of', suit)
It could be written more concisely, but it is pretty basic python style program :)
#Two-Bit Alchemist - #vaultah version:
import random
print('1. Flip a coin')
print('2. Pick a card')
choice = int(input('Enter a choice: '))
if choice == 1:
outcomes = ('heads', 'tails')
print('You got {}.'.format(random.choice(outcomes)))
else:
suits = ('Hearts', 'Clubs', 'Diamonds', 'Spades')
print()
for index, element in enumerate(suits, start=1):
print('{}. {}'.format(index, element))
suitno = int(input('Choose a suit: '))
value = random.randint(1, 13)
print('\nYou picked', value, 'of', suits[suitno-1])
Here's another restructured version:
from random import choice
COINS = ["Heads", "Tails"]
FACES = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
SUITS = ["Hearts", "Clubs", "Diamonds", "Spades"]
def get_int(prompt, lo=None, hi=None):
while True:
try:
value = int(input(prompt))
if (lo is None or lo <= value) and (hi is None or value <= hi):
return value
except ValueError:
pass
def do_menu(prompt, options):
print("")
for i,option in enumerate(options, 1):
print("{:>3}. {}".format(i, option))
return get_int(prompt, 1, len(options)) - 1
def main():
while True:
option = do_menu("> ", ["Flip a coin", "Pick a card", "Quit"])
if option == 0:
print("\nYou flipped {}.".format(choice(COINS)))
elif option == 1:
suit = SUITS[do_menu("Pick a suit: ", SUITS)]
print("\nYou picked {} of {}".format(choice(FACES), suit))
else:
print("\nGoodbye!")
break
if __name__=="__main__":
main()