validate Fn usining try-except in python - python

def validate(choice):
try:
if choice == 1 or choice == 2 or choice == 3 or choice == 4 or choice == 5 or choice == 6 or choice == 7 or choice == 8:
if choice==1:
extrasquare()
elif choice==2:
drawastar()
elif choice==3:
drawit()
elif choice==4:
circle()
elif choice==5:
square()
elif choice==6:
turtle.clear()
elif choice==7:
turtle.bye()
elif choice==8:
import sys #exit from program
sys.exit() #might not work in some versions of idlex
loop = 700076
except:
loop=8
print("Error")
while loop == 1:
#print options for user
print("----------------------------")
print("Hello")
print("Here's you options")
print("1- to draw a set of squares(extra picture)")
print("2-to draw 10 stars")
print("3-to draw nine rectangles")
print("4-to draw a random number of random circles")
print("5-to draw a square motion")
print("6-to Erase everything")
print("7-to exit from turtle")
print("8-to exit from python")
print(" ")
choice = int(input("What would you like to do? Please enter a number:"))
validate(choice)
I need to use try-except to validate input data but obviously I do something wrong. I need to stop loop and print error if input was >=9. Could you help me guys? I really do not know what to write else

You will find this sort of problem a lot easier using a dictionary:
def validate(choice):
options = {
1: extrasquare,
2: drawastar,
3: drawit,
4: circle,
5: square,
6: turtle.clear,
7: turtle.bye,
8: exit # Move your exit action to a separate function for simplicity
}
if choice in options:
options[choice]()
else:
print "Error: %i is not a recognized choice" % i
Your existing code won't raise an exception since you only try a lot of ifs and dont hit an exception condition.
You could do the same with a try by changing the last lines two:
try:
options[choice]()
except KeyError:
print "Error : %i is not a recognized choice" % choice
However it doesn't really enhance the code .

Related

How can I fix my code to properly display my menu?

My code has no red flags in it. It runs but it doesnt display anything?
def main():
menuInput()
def menu():
print('''
Welcome! Please make a choice from the following menu
1. Select a year and display available data
2. Review averages by year range
3. Select a date range and show highest temperature
4. Select a date range and show lowest temperature
5. Get total rainfall for a selected year range
6. blank
7. blank
8. See this menu again
9. QUIT the program
''')
def menuInput():
while True:
menu()
try:
userChoice=int(input('Please make a selection: '))
if userChoice > 9:
print('Please enter a number less or equal to 9')
elif userChoice <= 0:
print('Please enter a number greater than 0')
elif userChoice == 1:
print('Good')
elif userChoice == 2:
print('Good')
elif userChoice == 3:
print('Good')
elif userChoice == 4:
print('Good')
elif userChoice == 5:
print('Good')
elif userChoice == 6:
print('Good')
elif userChoice == 7:
print('Invalid Choice')
elif userChoice == 8:
print('Good')
elif userChoice == 9:
print('Program Exiting!')
else:
print('Invalid Choice')
continue
except ValueError:
print('Please enter a whole number instead')
continue
main()
I would like to assume it is because menu() either hasnt been called properly or has not been assigned a to a variable like displayMenu=MENU CODE. Im not sure how to properly go about adding or passing that variable without ruining it
If you have copied and pasted the code verbatim, then the issue is that your main() function is indented improperly. Unindent the line main().
When you indent main(), it becomes part of the function menuInput(), and as a result nothing is run in the actual main of Python (if __name__ == "__main__").

How do I fix my Python function so that it returns with input prompts?

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:
...

My program is not ending when I’ve told it [duplicate]

This question already has answers here:
While loop won't stop in python
(3 answers)
Closed 3 years ago.
I am fairly new to coding.
So i am in the process of making a program and i have not quite finished it. But i have added an option where the program starts again if the user selects yes, if the user selects no the program should say good bye and stop. But when no is selected it says goodbye but starts the program again. Could someone tell me if im doing something wrong
When no is selected is starts the program again.
restart = True
while restart == True:
while True:
print(' Welcome to My Program')
print('Please Choose an Option')
print('Option 1: Enter RLE')
print('Option 2: Display ASCII Art')
print('Option 3: Convert to ASCII Art')
print('Option 4: Convert to RLE')
print('Option 5: Quit')
option = int(input('Choose an Option: '))
if option ==1:
Split=(list(input("Enter string: ")))
Split.append("")
a = 0
for i in range(len(Split)):
try:
if (Split[i] in Split) >0:
a = a + 1
if Split[i] != Split[i+1]:
print(Split[i],a)
a = 0
except IndexError:
print()
elif option == 2:
print("Hello")
elif option == 3:
print("Hello")
elif option == 4:
print("Hello")
elif option == 5:
print ('Ending Program')
exit()
else:
print('Invalid Input')
while True:
answer = str(input('Would You Like to Run The Program Again? (y/n): '))
if answer in ('y', 'n'):
break
print ("Invalid input.")
if answer == 'y':
restart == True
else:
print ('Goodbye')
restart == False
break
When no is selected is starts the program again.
The first while True: after while restart == True: has created an infinite loop. Try getting rid of that and just putting your program inside the first while loop.

How do you clear user inputs?

So Im making the trade system on Monopoly using numbers. For example, if I want to add something, I input the number 1, if I want to remove something, I input the number 2, etc. My problem is, if I exit out the while loop, basically the code "break", that previous input to break also activates the main menu's if commands as well. If your confused what I am trying to say, I don't know if I'm allowed to post links on this website, but the link is:
https://repl.it/#BrentTersol/Monopoly-Official
if Action == 2 :
while True:
replit.clear()
print("What would you like to give?\n1: Add\n2: Remove\n3: Clear\n4: Offer Trade\n5: Cancel\n6: Switch")
Action = int(input(">>> "))
if Action == 1:
while True:
replit.clear()
print("What would you like to add?\n1: Money\n2: Property\n3: Jail Free Card\n4: Back")
Action = int(input(">>> "))
if Action == 1:
if Turn == 1:
while True:
replit.clear()
print("How much money do you want to give for the trade?\nMoney:",str(Player1Money))
Action = int(input(">>> "))
if Action >= 0 and Action <= (Player1Money):
TMoney1 = (Action)
print("You added $"+str(TMoney1),"to the trade")
time.sleep(2)
break
else:
print("You do not have enough money")
break
if Turn == 2:
while True:
replit.clear()
print("How much money do you want to give for the trade?\nMoney:",str(Player2Money))
Action = int(input(">>> "))
if Action >= 0 and Action <= (Player2Money):
TMoney2 = (Action)
print("You added $"+str(TMoney2),"to the trade")
time.sleep(2)
break
if Action == "back":
break
else:
print("You do not have enough money")
break
if Action == 2:
while True:
replit.clear()
if Turn == 1:
print(Inventory1)
if Turn == 2:
print(Inventory2)
print("What property do you want to give?")
Action = int(input(">>> "))
if Turn == 1:
if (Action) in (Inventory1):
TProperty1.append((Action))
print("Added",(Action),"to the trade")
time.sleep(2)
break
else:
print("Item not found in your properties")
time.sleep(2)
break
if Turn == 2:
if (Action) in (Inventory2):
TProperty2 = (Action)
print("Added",(Action),"to the trade")
time.sleep(2)
break
else:
print("Item not found in your properties")
time.sleep(2)
break
if Action == 3:
if Turn == 1:
if JailCard1 == 1:
TCard1 = 1
print("Added Jail Free Card to the trade.")
time.sleep(2)
else:
print("You do not own a Jail Free Card")
time.sleep(2)
if Turn == 2:
if JailCard2 == 1:
TCard1 = 1
print("Added Jail Free Card to the trade.")
time.sleep(2)
else:
print("You do not own a Jail Free Card")
time.sleep(2)
if Action == 4:
break
if Action == 2:
while True:
replit.clear()
print("What would you like to remove?\n1: Money\n2: Property\n3: Jail Free Card\n4: Back")
Action = int(input(">>> "))
if Action == 1:
while True:
replit.clear()
if Turn == 1:
if TMoney1 == 0:
print("There wasn't any money to remove")
time.sleep(2)
else:
TMoney1 = 0
print("Removed Cash from offer")
time.sleep(2)
break
if Action == 2:
while True:
replit.clear()
print(TProperty1)
print("What property would you like to remove")
Action = input(">>> ")
Action = Action.lower()
if Turn == 1:
if Action == "back":
break
if (Action) in (TProperty1):
TProperty1.remove((Action))
print("Removed",(TProperty1),"from trade")
time.sleep(2)
break
else:
print("That item did not exist")
time.sleep(2)
if Turn == 2:
if (Action) in (TProperty2):
TProperty2.remove((Action))
print("Removed",(TProperty2),"from trade")
time.sleep(2)
else:
print("That item did not exist")
time.sleep(2)
if Action == 3:
if Turn == 1:
if JailCard1 == 1:
print("Removed Jail Free Card from trade")
TCard1 = 0
break
else:
print("Card does not exist in trade")
if Turn == 2:
if JailCard2 == 1:
print("Removed Jail Free Card from trade")
TCard2 = 0
break
else:
print("Card does not exist in trade")
if Action == 4:
break
if Action == 3:
TMoney1 = 0
TMoney2 = 0
TProperty1.clear()
TProperty2.clear()
TCard1 = 0
TCard2 = 0
if Action == 4:
if Turn == 1:
while True:
print("This is what",(Name1),"offers:\n--------------------")
time.sleep(2)
print("You get:\nMoney:",(TMoney1),"\nProperty:",(TProperty1),"\nGet out of Jail Free Card:",(TCard1),"\n")
time.sleep(2)
print("You give",(Name1)+":\nMoney:",(TMoney2),"\nProperty:",(TProperty2),"\nGet out of Jail Free Card:",(TCard2),"\n")
time.sleep(2)
print("Do you accept this Offer? (Y/N):")
Action = input(">>> ")
Action = Action.lower()
if Action == "y":
print("This is beyond what I can do at this point. Very sorry you took a long time not knowing that it wouldnt work. But this will soon be fixed as soon as I know how to do this")
time.sleep(5)
else:
print("Trade has been rejected")
time.sleep(2)
break
if Action == 5:
if Turn == 1:
Turn = 2
else:
Turn = 1
if Action == 6:
print("This is beyond what I can do. Please wait until I learn how to do this. Thank you.")
You should implement a single While True loop and that will reset the user input each loop (so long as you overwrite it inside the loop)! I would also advise you recreate your code into functions instead of several nested logic statements. An example of code that gets user input each loop (in the terms of your question clears user input):
while True:
big_prompt = """What would you like to do?
1) say hi
2) say bye
3) pay taxes
4) ???
5) profit
6) Exit D:"""
action = input(big_prompt) # reset user input each loop
if action not in ["1", "2", "3", "4", "5", "6"]:
print("Sorry I didn't understand that")
continue # get a new user input
# at this point we know user input fits our criteria
if action == "1":
print("Hi!")
elif action == "2":
print("Bye!")
# ... you should be putting function calls in these for more complex tasks
elif action == "6":
break # this only exits one loop, I think you are trying to use it to
With sample output:
What would you like to do?
1) say hi
2) say bye
3) pay taxes
4) ???
5) profit
6) Exit D:
>>>1
Hi!
What would you like to do?
1) say hi
2) say bye
3) pay taxes
4) ???
5) profit
6) Exit D:
>>>6
Process finished with exit code 0
It also might be a good idea to review The Zen of Python by opening an interactive terminal and running import this:
>>>import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Where of special note we find a couple things that apply here:
Flat is better than nested.
Readability counts.
Maintaining a single while loop greatly helps both of these. At one point in your code you get trapped inside 3 while True: loops and then try to break multiple with a single break, but will always stay trapped at least 2 levels deep...

Trying to use list function to limit input in while loop in my guessing game

def random():
x_val = randint(1,100)
limit = []
limit2 = len(limit)
while True:
try:
roll = int(raw_input("Please pick a number: "))
except ValueError:
print "Please input numbers only"
continue
if limit2 <= 5:
if roll > 100 or roll < 1:
print "Exceed Limited Guess"
continue
elif roll < x_val:
limit.append(1)
sleep(1)
print "Your guess is lower!"
continue
elif roll > x_val:
limit.append(1)
sleep(1)
print "Your guess is higher!"
continue
elif roll == x_val:
print limit2
return "You guessed correct! You win!"
break
else:
print "Incorrect Input"
continue
elif limit2 > 5:
return "You guessed over 5 times. You lose, sucker..."
break
elif limit2 == 4:
print "Last guess!"
continue
print "Welcome to my world! You will have to pick a correct number from 1 to 100!
If you can do it within 5 times you win! Otherwise you suck!"
while True:
try:
start = raw_input("Start Rolling? Yes or No: ").lower()
except ValueError:
print "Answer Yes or no"
continue
if start == "y" or start == "yes" or start == "ye":
user2 = random()
print user2
elif start == "n" or start == "no" or start == "noo":
print "Ready when you are"
continue
else:
print "Answer Yes or No"
continue
Hi, I am working on a guessing game from 1-100 that I built from ground up by myself and doing research, my original code is not even close to this.
Now, I am stuck on the last part I cannot use the list to limit the input in while loop. I want to stop the game after 5 guesses. However every time it always keep going and once it win it printed out "0" for limit2 variable.
Thank you
The main problem with your code is that you never update the "counter" of the attempted tries made by the user. You initialize it at the beginning (through limit2 = len(limit)), but you never update that value, therefore causing an endless loop.
You simply need to perform the check on len(limit) instead of on limit2.
Working solution can be found below. I took the liberty of commenting limit2 (as it is not needed anymore), improving the indentation, adding two imports, replacing sleep with time.sleep, and fixing the number of checks to perform (if you are aiming at 5 maximum tries, len(limit) needs to be less than 5).
from random import randint
import time
def random():
x_val = randint(1,100)
limit = []
# limit2 = len(limit)
while True:
try:
roll = int(raw_input("Please pick a number: "))
except ValueError:
print "Please input numbers only"
continue
if len(limit) < 5:
if roll > 100 or roll < 1:
print "Exceed Limited Guess"
continue
elif roll < x_val:
limit.append(1)
time.sleep(1)
print "Your guess is lower!"
continue
elif roll > x_val:
limit.append(1)
time.sleep(1)
print "Your guess is higher!"
continue
elif roll == x_val:
print len(limit)
return "You guessed correct! You win!"
break
else:
print "Incorrect Input"
continue
elif len(limit) >= 5:
return "You guessed over 5 times. You lose, sucker..."
break
print "Welcome to my world! You will have to pick a correct number from 1 to 100! If you can do it within 5 times you win! Otherwise you suck!"
while True:
try:
start = raw_input("Start Rolling? Yes or No: ").lower()
except ValueError:
print "Answer Yes or no"
continue
if start == "y" or start == "yes" or start == "ye":
user2 = random()
print user2
elif start == "n" or start == "no" or start == "noo":
print "Ready when you are"
continue
else:
print "Answer Yes or No"
continue
Worthy of note is that -- among several other things that should be fixed in your code -- you should avoid calling a function random, since it is already a name used by a very common module.

Categories

Resources