Expected indented blockPylance - python

from tkinter import CENTER
global f
f = 0
#this t_movie function is used to select movie name
def t_movie():
global f
f = f+1
print("which movie do you want to watch?")
print("1,movie 1 ")
print("2,movie 2 ")
print("3,movie 3")
print("4,back")
movie = int(input("choose your movie: "))
if movie == 4:
# in this it goes to center function and from center it goes to movie function and it
comes back here and then go to theater
CENTER()
theater()
return 0
if f == 1:
theater()
# this theater function used to select screen
def theater():
print("which screen do you want to watch movie: ")
print("1,SCREEN 1")
print("2,SCREEN 2")
print("3,SCREEN 3")
a = int(input("choose your screen: "))
ticket = int(input("number of ticket do you want?: "))
timing(a)
# this timing function used to select timing for movie
def timing(a):
time1 = {
"1": "10.00-1.00",
"2": "1.10-4.10",
"3": "4.20-7.20",
"4": "7.30-10.30"
}
time2 = {
"1": "10.15-1.15",
"2": "1.25-4.25",
"3": "4.35-7.35",
"4": "7.45-10.45"
}
time3 = {
"1": "10.30-1.30",
"2": "1.40-4.40",
"3": "4.50-7.50",
"4": "8.00-10.45"
}
if a == 1:
print("choose your time:")
print(time1)
t = input("select your time:")
x = time1[t]
print("successful!, enjoy movie at "+x)
elif a == 2:
print("choose your time:")
print(time2)
t = input("select your time:")
x = time2[t]
print("successful!, enjoy movie at "+x)
elif a == 3:
print("choose your time:")
print(time3)
t = input("select your time:")
x = time3[t]
print("successful!, enjoy movie at "+x)
return 0
def movie(theater):
if theater == 1:
t_movie()
elif theater == 2:
t_movie()
elif theater == 3:
t_movie()
elif theater == 4:
city()
else:
print("wrong choice")
def center():
print("which theater do you wish to see movie? ")
print("1,Inox")
print("2,Icon")
print("3,pvp")
print("4,back")
a = int(input("choose your option: "))
movie(a)
return 0
# this function is used to select city
def city():
print("Hi welcome to movie ticket booking: ")
print("where you want to watch movie?:")
print("1,city 1")
print("2,city 2 ")
print("3,city 3 ")
place = int(input("choose your option: "))
if place == 1:
center()
elif place == 2:
center()
elif place == 3:
center()
else:
print("wrong choice")
city() # it calls the function city

Here is your code with the indentation fixed. At least, I think it's fixed, Your structure is confusing, so it's hard to tell.
from tkinter import CENTER
f = 0
#this t_movie function is used to select movie name
def t_movie():
global f
f = f+1
print("which movie do you want to watch?")
print("1,movie 1 ")
print("2,movie 2 ")
print("3,movie 3")
print("4,back")
movie = int(input("choose your movie: "))
if movie == 4:
# in this it goes to center function and from center it goes to movie function and it comes back here and then go to theater
CENTER()
theater()
return 0
if f == 1:
theater()
# this theater function used to select screen
def theater():
print("which screen do you want to watch movie: ")
print("1,SCREEN 1")
print("2,SCREEN 2")
print("3,SCREEN 3")
a = int(input("choose your screen: "))
ticket = int(input("number of ticket do you want?: "))
timing(a)
# this timing function used to select timing for movie
def timing(a):
time1 = {
"1": "10.00-1.00",
"2": "1.10-4.10",
"3": "4.20-7.20",
"4": "7.30-10.30"
}
time2 = {
"1": "10.15-1.15",
"2": "1.25-4.25",
"3": "4.35-7.35",
"4": "7.45-10.45"
}
time3 = {
"1": "10.30-1.30",
"2": "1.40-4.40",
"3": "4.50-7.50",
"4": "8.00-10.45"
}
if a == 1:
print("choose your time:")
print(time1)
t = input("select your time:")
x = time1[t]
print("successful!, enjoy movie at "+x)
elif a == 2:
print("choose your time:")
print(time2)
t = input("select your time:")
x = time2[t]
print("successful!, enjoy movie at "+x)
elif a == 3:
print("choose your time:")
print(time3)
t = input("select your time:")
x = time3[t]
print("successful!, enjoy movie at "+x)
return 0
def movie(theater):
if theater == 1:
t_movie()
elif theater == 2:
t_movie()
elif theater == 3:
t_movie()
elif theater == 4:
city()
else:
print("wrong choice")
def center():
print("which theater do you wish to see movie? ")
print("1,Inox")
print("2,Icon")
print("3,pvp")
print("4,back")
a = int(input("choose your option: "))
movie(a)
return 0
# this function is used to select city
def city():
print("Hi welcome to movie ticket booking: ")
print("where you want to watch movie?:")
print("1,city 1")
print("2,city 2 ")
print("3,city 3 ")
place = int(input("choose your option: "))
if place == 1:
center()
elif place == 2:
center()
elif place == 3:
center()
else:
print("wrong choice")
city() # it calls the function city

Related

Can't calculate the total cost in my restaurant menu program

So I am making a restaurant menu in Python, I got everything to work besides the program keeping track of the total cost. I've tried a few different things but no luck so far. It's probably something super simple but I can't figure it out. P.S. I'm a Python beginner so I'm still trying to get used to and learn this language lmao.
print("1. Cheeseburger: $3.50")
print("2. Gyro: $6.00")
print("3. Chicken Sandwich: $2.50")
print("4. Burrito: $7.00")
print("5. Fries: $1.50")
print("6. Exit")
while True:
choice = input("Enter a choice from 1-6\n")
totalPrice = 0
if choice == "1":
price = 3.00
totalPrice += price
elif choice == "2":
price = 6.00
totalPrice += price
elif choice == "3":
price = 2.50
totalPrice += price
elif choice == "4":
price = 7.00
totalPrice += price
elif choice == "5":
price = 1.50
totalPrice += price
elif choice == "6":
print("Exiting...")
print(totalPrice)
break
else:
print("Enter a valid choice!")
Only a litle mistake: the variable totalPrice must be initialized outside of the loop.
See the code below:
print("1. Cheeseburger: $3.50")
print("2. Gyro: $6.00")
print("3. Chicken Sandwich: $2.50")
print("4. Burrito: $7.00")
print("5. Fries: $1.50")
print("6. Exit")
totalPrice = 0 # <--- here is the right position for init totalPrice
while True:
choice = input("Enter a choice from 1-6\n")
if choice == "1":
price = 3.00
totalPrice += price
elif choice == "2":
price = 6.00
totalPrice += price
elif choice == "3":
price = 2.50
totalPrice += price
elif choice == "4":
price = 7.00
totalPrice += price
elif choice == "5":
price = 1.50
totalPrice += price
elif choice == "6":
print("Exiting...")
print(totalPrice)
break
else:
print("Enter a valid choice!")

How to Show scores/ save Game/ load game Python?

I am struggling with this code, I have my menu working to make the game run and to collect scores up to 18 for each player. But I think I have gotten lost in my code and I am frustrated beyond belief.
I need to have the Player scores loaded to a list that can be saved (save game), displayed(show scores) and list current winner, and then load (load game)
Player_1 = []
Player_2 = []
def main():
choice = 0
while choice != 6 :
print("1: New Game")
print("2: Play Round")
print("3: Show Scores")
print("4: Save Game")
print("5: Load Game")
print("6: Exit Game")
choice = input ("Option Select: ")
if choice == "1":
print("New Game // Reset Game")
ResetGame()
elif choice == "2":
print("Play Play Round")
PlayRound()
elif choice == "3":
print("Show Scores")
ShowScores()
elif choice == "4":
print("Save Game")
SaveGame()
elif choice == "5":
print("Load Game")
LoadGame()
elif choice == "6":
print("Thanks for playing!")
else:
print("I don't understand your choice.")
def PlayRound():
holes = 0
index = 0
endRound = 0
while holes <= 18 and endRound != 1:
Player_1Score = int(input("Player 1 Stroke: "))
Player_2Score = int(input("Player 2 Stroke: "))
endRound = int(input("Would you like to Continue 0= YES 1= NO"))
if Player_1Score > 5:
Player_1Score = 5
if Player_2Score > 5:
Player_2Score = 5
Player_1.insert (index,Player_1Score)
Player_2.insert (index,Player_2Score)
holes += 1
index += 1
print (Player_1)
print (Player_2)
def ShowScores():
total1 = sum(Player_1)
total2 = sum(Player_2)
if total1 < total2:
print("The Current Winner is Player 1")
elif total1 > total2:
print("The Current Winner is Player 2")
elif total1 == total2:
print("The Players are Tied")
def SaveGame():
with open("score1.txt","w") as P1:
for S1 in Player_1:
P1.writelines(str(S1)+' ')
with open("score2.txt", "w") as P2:
for S2 in Player_2:
P2.writelines(str(S2)+ ' ')
print('Your Scores have been saved.')
def LoadGame():
with open("score1.txt", "r") as P1:
for S1 in Player_1:
P1.split(' ')
print(P1)
with open("score2.txt", "r") as P2:
for S2 in Player_2:
P2.split(' ')
print(P2)
print('Game Loaded')
def ResetGame():
Player_1.clear()
Player_2.clear()
print('Scores():', Player_1, Player_2)
main()

Checking If a File Exists and Loading its Contents

In my programming class we are to make a Rock, Paper, Scissors Game that can load previous saves of the game, display the statistics of the game, and allow the user to continue playing if desired. I have a good chunk of the program created, I just need help with the loading of the file as I just get an endless loop of "What is your name?". My code is below and any help would be appreciated!
#Rock, Paper, Scissors Program
#A menu-based RPS program that keeps stats of wins, losses, and
ties
#12/2/18
import sys, os, random, pickle
#Functions
def print_menu():
print("\n1. Start New Game")
print("2. Load Game")
print("3. Quit")
def print_roundmenu():
print("What would you like to do?")
print("\n1. Play Again")
print("2. View Statistics")
print("3. Quit")
def start_game(username, playing):
print("Hello", username + ".", "let's play!")
playAgain = play_game()
if playAgain == True:
playing = True
elif playAgain == False:
playing = False
return playing
def play_game():
roundNo = 1
wins = 0
losses = 0
ties = 0
playing_round = True
while playing_round:
print("Round number", roundNo)
print("1. Rock")
print("2. Paper")
print("3. Scissors")
roundNo += 1
choices = ["Rock", "Paper", "Scissors"]
play = get_choice()
comp_idx = random.randrange(0,2)
comp_play = choices[comp_idx]
print("You chose", play, "the computer chose",
comp_play+".")
if (play == comp_play):
print("It's a tie!")
ties += 1
print_roundmenu()
gameFile.write(str(ties))
elif (play == "Rock" and comp_play == "Scissors" or play == "Paper" and comp_play == "Rock" or play == "Scissors" and comp_play == "Paper"):
print("You win!")
wins += 1
print_roundmenu()
gameFile.write(str(wins))
elif (play == "Scissors" and comp_play == "Rock" or play == "Rock" and comp_play == "Paper" or play == "Paper" and comp_play == "Scissors"):
print("You lose!")
losses += 1
print_roundmenu()
gameFile.write(str(losses))
response = ""
while response != 1 and response != 2 and response != 3:
try:
response = int(input("\nEnter choice: "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if response == 1:
continue
elif response == 2:
print(username, ", here are your game play statistics...")
print("Wins: ", wins)
print("Losses: ", losses)
print("Ties: ", ties)
print("Win/Loss Ratio: ", wins, "-", losses)
return False
elif response == 3:
return False
def get_choice():
play = ""
while play != 1 and play != 2 and play != 3:
try:
play = int(input("What will it be? "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if play == 1:
play = "Rock"
if play == 2:
play = "Paper"
if play == 3:
play = "Scissors"
return play
playing = True
print("Welcome to the Rock Paper Scissors Simulator")
print_menu()
response = ""
while playing:
while response != 1 and response != 2 and response != 3:
try:
response = int(input("Enter choice: "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if response == 1:
username = input("What is your name? ")
gameFile = open(username + ".rps", "w+")
playing = start_game(username, playing)
elif response == 2:
while response == 2:
username = input("What is your name? ")
try:
gameFile = open("username.rps", "wb+")
pickle.dump(username, gameFile)
except IOError:
print(username + ", your game could not be found.")
elif response ==3:
playing = False
This code block:
while response == 2:
username = input("What is your name? ")
try:
gameFile = open("username.rps", "wb+")
pickle.dump(username, gameFile)
except IOError:
print(username + ", your game could not be found.")
will repeat infinitely unless you set response to something other than 2. Notice here that all you're doing in this block is (1) asking for username, (2) opening the file, and (3) dumping the file contents with pickle. You're not actually starting the game, like you are in the if response == 1 block. So the same prompt keeps repeating infinitely.
A good thing to do in these situations is to manually step through your code by hand - "what did I do to get here, and what is happening as a result of that?"

Menu and submenu python

How can I return from a sub menu to a main menu?
Also I want to keep the data generated in the submenu.
Main menu:
1. Load data
2. Filter data
3. Display statistics
4. Generate plots
5. Quit
On option 2 I have a submenu:
1. S. enterica
2. B. cereus
3. Listeria
4. B. thermosphacta
5. Quit
def mainMenu():
menuItems = np.array(["Load data", "Filter data", "Display statistics", "Generate plots", "Quit"])
while True:
choice = displayMenu(menuItems)
if choice == 1:
filename = input("Please enter filename: ")
data = dataLoad(filename)
elif choice == 2:
menuItems = np.array(["S. enterica", "B. cereus", "Listeria", "B. thermosphacta", "Quit"])
while True:
choice = displayMenu(menuItems)
if choice == 1:
data = data[data[:,2] == 1] # 1 - S. enterica
elif choice == 2:
data = data[data[:,2] == 2] # 2 - B. cereus
elif choice == 3:
data = data[data[:,2] == 3] # 3 - Listeria
elif choice == 4:
data = data[data[:,2] == 4] # 4 - B. thermosphacta
elif choice == 5:
return data
continue
if choice == 3:
statistic = input("Please enter statistic: ")
print (dataStatistics(data, statistic))
elif choice == 4:
dataPlot(data)
elif choice == 5:
break
I implemented the break statement in the submenu and placed the menuItems inside the loops. This worked and data created in the submenu (subchoice) can be used in the mainMenu options 3 & 4.
import numpy as np
from displayMenu import *
from dataLoad import *
from dataStatistics import *
from dataPlot import *
from bFilter import *
def mainMenu():
while True:
menuItems = np.array(["Load data", "Filter data", "Display statistics",
"Generate plots", "Quit"])
choice = displayMenu(menuItems)
if choice == 1:
filename = input("Please enter filename: ")
data = dataLoad(filename)
elif choice == 2:
while True:
menuItems = np.array(["S. enterica", "B. cereus", "Listeria",
"B. thermosphacta", "Back to main menu"])
subchoice = displayMenu(menuItems)
if subchoice in (1, 2, 3, 4):
data = data[data[:,2] == subchoice]
if subchoice == 5:
break
continue
elif choice == 3:
statistic = input("Please enter statistic: ")
print (dataStatistics(data, statistic))
elif choice == 4:
dataPlot(data)
elif choice == 5:
break
Replace your code with this:
def mainMenu():
mainMenuItems = np.array(["Load data", "Filter data", "Display statistics",
"Generate plots", "Quit"])
subMenuItems = np.array(["S. enterica", "B. cereus", "Listeria",
"B. thermosphacta"])
while True:
choice = displayMenu(mainMenuItems)
if choice == 1:
filename = input("Please enter filename: ")
data = dataLoad(filename)
elif choice == 2:
while True:
subchoice = displayMenu(subMenuItems)
if subchoice in (1, 2, 3, 4):
data = data[data[:,2] == subchoice]
break
# The answer is not a correct one
continue
elif choice == 3: # instead of if
statistic = input("Please enter statistic: ")
print (dataStatistics(data, statistic))
elif choice == 4:
dataPlot(data)
elif choice == 5:
break
You donĀ“t need a "Quit" option in your submenu - you want to repeat the nested loop (the submenu) only in the case of wrong answer (other as 1, 2, 3 or 4).
No action is needed to save the contents of your data variable as all action you perform are inside of your mainMenu() function. But if you need it outside of your function, use the return data statement as the very last in your function, outside of any loop.

Rock paper scissors menu error

Here is code I have so far whenever the menu appears and I press 1 for start a new game it says wrong choice try again.
import random
import pickle
class GameStatus():
def __init__(self, name):
self.tie = 0
self.playerWon = 0
self.pcWon = 0
self.name = name
def get_round(self):
return self.tie + self.playerWon + self.pcWon + 1
# Displays program information, starts main play loop
def main():
print("Welcome to a game of Rock, Paper, Scissors!")
print("What would you like to choose?")
print("")
game_status = welcomemenu()
while True:
play(game_status)
endGameSelect(game_status)
def welcomemenu():
while True:
print("[1]: Start New Game")
print("[2]: Load Game")
print("[3]: Quit")
print("")
menuselect = input("Enter your choice: ")
if menuselect in [1, 2, 3]:
break
else:
print("Wrong choice. select again.")
if menuselect == 1:
name = input("What is your name?: ")
print("Hello %s.") % name
print("Let's play!")
game_status = GameStatus(name)
elif menuselect == 2:
while True:
name = input("What is your name?: ")
try:
player_file = open('%s.rsp' % name, 'r')
except IOError:
print("Sorry there is no game found with name %s") % name
continue
break
print("Welcome back %s.") % name
print("Let's play!")
game_status = pickle.load(player_file)
displayScoreBoard(game_status)
player_file.close()
elif menuselect == 3:
print("Bye!!!")
exit()
return
return game_status
def play(game_status):
playerChoice = int(playerMenu())
pcChoice = pcGenerate()
outcome = evaluateGame(playerChoice, pcChoice)
updateScoreBoard(outcome, game_status)
def playerMenu():
print("Select a choice: \n [1]: Rock \n [2]: Paper \n [3]: Scissors\n")
menuSelect = input("What will it be? ")
while not validateInput(menuSelect):
invalidChoice(menuSelect)
menuSelect = input("Enter a correct value: ")
return menuSelect
def validateInput(menuSelection):
if menuSelection in [1, 2, 3]:
return True
else:
return False
def pcGenerate():
pcChoice = random.randint(1,3)
return pcChoice
# Calculate ties,wins,lose
def evaluateGame(playerChoice, pcChoice):
rsp = ['rock', 'paper', 'scissors']
win_statement = ['Rock breaks scissors', 'Paper covers rock', 'Scissors cut paper']
win_status = (playerChoice - pcChoice) % 3
print("You have chosen %s") % rsp[playerChoice - 1]
what_to_say =("Computer has chose %s") % rsp[pcChoice - 1]
if win_status == 0:
what_to_say +=(" as Well. TIE!")
elif win_status == 1:
what_to_say +=(". %s. You WIN!") % win_statement[playerChoice - 1]
else:
what_to_say +=(". %s. You LOSE!") % win_statement[pcChoice - 1]
print("what_to_say")
return win_status
# Update track of ties, player wins, and computer wins
def updateScoreBoard(outcome, game_status):
if outcome == 0:
game_status.tie += 1
elif outcome == 1:
game_status.playerWon += 1
else:
game_status.pcWon += 1
# If user input is invalid, let them know.
def invalidChoice(menuSelect):
print(menuSelect,("is not a valid option. Please select 1-3"))
# Print the scores before terminating the program.
def displayScoreBoard(game_status):
print("")
print("Statistics:")
print(("Ties: %d") % game_status.tie)
print(("Player Wins: %d") % game_status.playerWon)
print(("Computer Wins: %d") % game_status.pcWon)
if game_status.pcWon > 0:
print("Win/Loss Ratio: %f") % (float(game_status.playerWon) / game_status.pcWon)
else:
print("Win/Loss Ratio: Always Win.")
print("Rounds: %d") % game_status.get_round()
def endGameSelect(game_status):
print("")
print("[1]: Play again")
print("[2]: Show Statistics")
print("[3]: Save Game")
print("[4]: Quit")
print("")
while True:
menuselect = input("Enter your choice: ")
if menuselect in [1, 2, 3, 4]:
break
else:
print("Wrong input.")
if menuselect == 2:
displayScoreBoard(game_status)
endGameSelect(game_status)
elif menuselect == 3:
f = open("%s.rsp" % game_status.name, 'w')
pickle.dump(game_status, f)
f.close()
print("Your game is saved successfully.")
endGameSelect(game_status)
elif menuselect == 4:
print("Bye!!!")
exit()
main()
When you use input(), you get a string rather than an int.
You should change:
menuselect = input("Enter your choice: ")
to this:
menuselect = int(input("Enter your choice: "))
To get it as an integer, that way it will work with the rest of your script.

Categories