How do you clear user inputs? - python

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

Related

Guess the number, play again

I'm making a guess the number game. My code is almost complete but I need to make it so that the program asks the player if they want to play again and then restarts. Could someone help me with how I should go about that? I tried making a new function ex. def game_play_again and then call the game_play() function but it's not reseting the attempts which leads to it not looping correctly.
This is my code right now
import random
MIN = 1
MAX = 100
attempts = 5
win = False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
#print game instructions
def game_start():
print(f"Im thinking of a number between {MIN} and {MAX}. Can you guess it within
{attempts} attempts? ")
input("Press enter to start the game ")
#process user input
def game_play():
global number, attempts, last_hint, win
while attempts > 0:
print()
print(f"You have {attempts} {'attempts' if attempts > 1 else 'attempt'} left.")
if attempts == 1:
print(f"This is your last chance. So i'll give you one more hint. Its's an {last_hint} number.")
while True:
try:
guess = int(input("Try a lucky number: "))
if guess in range(MIN, MAX+1):
break
else:
print(f"Please enter numbers between {MIN} and {MAX} only!")
except ValueError:
print("Plese enter numbers only!")
if guess == number:
win = True
break
if attempts == 1:
break
if guess > number:
if guess-number > 5:
print("Your guess is too high. Try something lower.")
else:
print("Come on you are very close. Just a bit lower.")
else:
if number-guess > 5:
print("Your guess is too low. Try something higher.")
else:
print("Come on you are very close. Just a bit higher.")
attempts -= 1
#print game results
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
game_start()
game_play()
game_finish(win)
You can simply reset your variables to initial values and then call game_play()
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
want_play_again = int(input("Want play again? [1-Yes / 2-No]"))
if want_play_again == 1:
game_play_again()
else:
print("Bye")
/
def game_play_again():
attempts = 0
win = False
game_play()
Within a while(True) loop, write a menu driven statement asking the user if they want to repeat. If they do, initialise values and call game methods. If they do not, break the loop.
pseudocode:
while(True):
choice = input('play again? y/n)
if choice=='y':
attempts, win = 5, False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
game_start()
game_play()
game_finish()
elif choice=='n':
break
else:
print('invalid input')
The above code should be in main, with all methods within its scope.
Better yet, in place of all the initializations, add an init() method declaring them and call them when necessary.
The indentation in the code you have submitted is faulty, so I'm not sure if a related error is involved.

Python is ignoring fleeing_attempted variable

I am making a fighting system for a text-based game I am working on, and one option is to flee.
however, I want to make it so that you can only attempt to flee once. I made it so that after 1 failed attempt, the variable fleeing_attempted is set from false to true. However, python is ignoring this and letting me attempt to flee as many times as I want.
edit: I made fixes, but the result hasn't changed. here are the modifications.
fleeing_attempted = False #the first time the variable is defined
def battle():
print("What will you do?")
print("1. attack")
print("2. flee")
action = input()
if action == "1":
print("test")
elif action == "2":
fleeing = randint(1, 100)
if fleeing in range(1, 50):
print("You got away!")
elif fleeing in range(51,100):
callable(fleeing_attempted)
print("The enemy caught up!")
battle()
elif action == 2 and fleeing_attempted:
print("You already tried that!")
battle()
Take a look at the following two lines of code:
fleeing_attempted = False
if fleeing_attempted == True:
There is no chance for fleeing_attempted to ever be True at that if statement, since it is being set to False on the line above.
Without seeing the rest of your code, it is hard to tell where the fleeing_attempted=False should go but it should probably be somewhere in initialization.
elif action == "2":
fleeing = randint(1, 100)
fleeing_attempted = False < --- Your problem is here.
if fleeing_attempted == True:
You set it to False before you do the if check, so it will never be True.
You can also do:
if fleeing_attempted:
to test if it's true.
You can also clean up your code with and
elif action == "2" and fleeing_attempted :
# rest of code
Cleaned Code:
def have_battle():
action = input("What will you do?")
print("1. Attack")
print("2.Flee")
if action == "1":
print("You choose to attack")
elif action == "2":
# do your random check
fleeing = random.randint(0, 100)
print("fleeing variable: {0}", fleeing)
if fleeing in range (1,50):
print("You choose to flee")
You had some major problems, but I cleaned up some it and you should be able to work off it.

"shopping cart" list won't append within online shopping program, what am I missing?

My assignment involves building an online shopping program. I have code that works, except that it won't append a single item to my shopping cart. Nearly identical code works for appending two shirts. Why won't it append for one?
Interestingly, it will not print the "Cart Updated" message I have after each append situation.
A lot of the following code is meeting the scenario/rules of the assignment; the append code is located in times the user wants to order 1 or 2 shirts.
cart = list()
def shop():
# some code for shopping categories and displaying items
pass
def shirtorder():
while True:
shirtitem = input('Please type in the name of the shirt you would like to purchase.''\n')
numbershirt = input('How many would you like to purchase?''\n')
numbershirt = int(numbershirt)
if numbershirt > 2:
print('We are sorry, but there are only 2', shirtitem, 'in stock.')
while True:
yesornoshirt = input('Would you like to order fewer of that shirt? Please answer "yes" or "no."''\n')
if yesornoshirt == "yes" or yesornoshirt== "y" or yesornoshirt == "Y" or yesornoshirt == "Yes":
numbershirt = input('How many would you like to purchase?''\n')
numbershirt = int(numbershirt)
if numbershirt == 2:
while len(cart) >= 0:
cart.append(shirtitem)
cart.append(shirtitem)
print('Cart updated.')
shop()
break
break
if numbershirt == 1:
while len(cart) >= 0:
cart.append(shirtitem)
print('Cart updated.')
shop()
break
break
if numbershirt == 0:
shop()
break
if numbershirt < 0:
print('Invalid number of shirts. Please try again.')
continue
if yesornoshirt == "n" or yesornoshirt == "no" or yesornoshirt == "No" or yesornoshirt == "N":
print('None have been added to your cart.')
shop()
break
try:
yesornoshirt = float(yesornoshirt)
yesornoshirt = int(yesornoshirt)
except:
print('Please answer only "yes" or "no."')
continue
if numbershirt == 2:
while len(cart) >= 0:
cart.append(shirtitem)
cart.append(shirtitem)
print('Cart updated.')
shop()
break
break
break
if numbershirt == 1:
while len(cart) >= 0:
cart.append(shirtitem)
print('Cart updated.')
shop()
break
break
break
if numbershirt == 0:
shop()
break
if numbershirt < 0:
print('Invalid number of shirts. Please try again.')
continue
shirtorder()
print(cart)
IMMEDIATE PROBLEM
Your logic flow is faulty:
if numbershirt == 2:
while len(cart) >= 0:
cart.append(shirtitem)
cart.append(shirtitem)
print('Cart updated. 2Y')
shop()
break # problem 3
break # problem 2
break # problem 1
if numbershirt == 1:
print ("TRACE A1: cart", cart, len(cart))
while len(cart) >= 0:
...
problem 1: Do you know what break does? In this case, it exits the while loop. You can never reach the following statement, so there's no way to register a single shirt -- or no shirts, or negative shirts.
problem 2: What do you expect this to do? You're breaking out of an if statement, which is not an iterative process.
problem 3: This must exit your while on the first execution, which says that you shouldn't be using a while at all.
ANALYSIS
Very briefly, you tried to program far beyond your capabilities in one sitting. You've written over 70 lines of code without testing the pieces; you now have several mistakes in multiple places. You're not comfortable with writing some combinations of control flow ... yet.
Fortunately, that's fixable. Welcome to the learning process.
WHAT TO DO
Use incremental programming. Write a few lines of code. Test them, fix them, and keep testing until you're sure those lines are solid. Then add a few more lines. This will keep you from reusing code with errors in it.
For instance, start with a forced case of a particular shirt. Something like this (using your current set-up):
shirtitem = "Generic white tee"
numbershirt = 2
if numbershirt == 2
cart.append(shirtitem)
cart.append(shirtitem)
print('Cart updated;', numbershirt, shirtitem)
print('Cart:', cart)
Notice the simple changes: tracing output to show the results; I removed the useless while.
Now, what would this look like if you could take up to 10 shirts? Can you make it general enough to handle any quantity? You'll need a loop for the append operations.
Now you're ready to try user input. Don't repeat yet: the shopper gets one choice of shirt and quantity; then you kick them out of the store, because your trainee's brain is full.
Once that works well, you can loop for more shirts. This program works pretty well constructing from the inside out. Have fun. Write lots of print statements; comment them out when you don't need them, but don't delete them until the whole program is working for, say, a week.

Python coding for online Game - Pizzeria chose story Game.

I am stayed in getting the right coding. If you happen to run this code, please correct what you see fit. I have searched and there continues to be bugs here and there. Here is the game coding. There may be some issues in the definition terms and I'm still learning the Python vocabulary to defined new items and am not finding right answers. Here is the code that you can run and try. Thank you:
import random
import time
def displayIntro():
print("You are in a city. In front of you,")
print("you see two restraunts. In one pizzeria, the service is friendly")
print("and will share thier free pizza with you. The other pizzeria")
print("is very unpredictable and will hire you to wash the dishes in the back quick.!")
print()
def choosePizzeria():
pizzeria=""
while((pizzeria != "1") and (pizzeria != "2")):
print("Which pizzeria will you go into? (1 or 2) ")
pizzeria = input()
return pizzeria
def checkPizzeria(level,(pizzeria != "1") or (pizzeria != "2")):
print("You approach the pizzeria and see people hustling in and out quickly...")
time.sleep(2)
print("It really crowded with people waiting in line, playing arcade games and just having a good time dancing...")
time.sleep(2)
print("A little manager with a suit steps in in front of you! He quickly slips his arm behind his back...")
print()
time.sleep(2)
friendlypizzeria = random.randint(1, 3)
overworkPizzeria = friendlypizzeria + 1
if overworkPizzeria > 3:
overworkPizzeria -= 3
if chosenPizzeria == str(friendlyPizzeria):
print("Hand you a slip of paper for two free pizzas!")
elif chosenPizzeria == str(overworkPizzeria):
print("He hands you a slip of paper telling you to watch the dishes in the back for a while since you stared at him too long!")
else:
level += 1
if level < 3:
print("You quickly hid behind some customes and head out to 3 more pizzerias")
else:
print("Congratulations you win two free pizzas and")
print("you get to go to the manager's weekend party!!!! ")
return level
playAgain = "yes"
while playAgain == "yes" or playAgain == "y":
displayIntro()
level = 0
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
if level == 1:
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
if level == 2:
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
print('Do you want to play again? (yes or no)')
playAgain = input()
Thank you.
Mostly Syntax errors, I would suggest reading some Python documentation. Especially in regards to Types, and Comparison Operators. But below will run;
import random
import time
def displayIntro():
print("You are in a city. In front of you,")
print("you see two restraunts. In one pizzeria, the service is friendly")
print("and will share thier free pizza with you. The other pizzeria")
print("is very unpredictable and will hire you to wash the dishes in the back quick.!")
print()
def choosePizzeria():
pizzeria=""
while((pizzeria != 1) and (pizzeria != 2)):
print("Which pizzeria will you go into? (1 or 2) ")
pizzeria = input()
return pizzeria
def checkPizzeria(level, pizzariaNumber):
print("You approach the pizzeria and see people hustling in and out quickly...")
time.sleep(2)
print("It really crowded with people waiting in line, playing arcade games and just having a good time dancing...")
time.sleep(2)
print("A little manager with a suit steps in in front of you! He quickly slips his arm behind his back...")
print()
time.sleep(2)
chosenPizzeria = pizzariaNumber
friendlypizzeria = random.randint(1, 3)
overworkPizzeria = friendlypizzeria + 1
if overworkPizzeria > 3:
overworkPizzeria -= 3
if chosenPizzeria == friendlypizzeria:
print("Hand you a slip of paper for two free pizzas!")
elif chosenPizzeria == overworkPizzeria:
print("He hands you a slip of paper telling you to watch the dishes in the back for a while since you stared at him too long!")
else:
level += 1
if level < 3:
print("You quickly hid behind some customes and head out to 3 more pizzerias")
else:
print("Congratulations you win two free pizzas and")
print("you get to go to the manager's weekend party!!!! ")
return level
playAgain = "yes"
while playAgain == "yes" or playAgain == "y":
displayIntro()
level = 0
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
if level == 1:
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
if level == 2:
pizzeriaNumber = choosePizzeria()
level = checkPizzeria(level,pizzeriaNumber)
print('Do you want to play again? (yes or no)')
playAgain = raw_input()

validate Fn usining try-except in 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 .

Categories

Resources