Python - Never Ending Multiple While Loops Interferring with Other Definitions - python

I'm currently making a scoring system where a user can join the event as a team or by themselves and in order to do this I was using while loops as a form of simple validation. I used while loop to prevent user entering the event without their name. The problem I am having is that I have different definitions if they want to join the event as a team or by themselves and the while loops inside this defintions keeps interferring with each other and by interfering I mean that even after I asked the user for their name the other defintion comes up and asks for the user for their name again
def team_menu():
global teamS
team_player = ""
while team_player:
team_player = input("What is your name:")
print("""\n Available Teams \n
1) Team Ahab
2) Team Ishmael
\n3) Go back to Main Menu\n""")
team_choice = ""
team_choice_option = ["1","2","3"] # all valid choices on team menu
while team_choice not in team_choice_option:
team_choice = input("Enter your choice here:")
teamS["Crew "+team_choice]["Team "+team_choice]
print(teamS["Crew "+team_choice])
print("Thank you for Joining Team "+ team_choice)
Here's my second def that keeps interfering its while loops with the first one
def individual():
global solo_player
solo_name=""
while solo_name == "":
solo_name = input("What is your name:")
print(""" \nIndividual Menu and Available Spots\n
1) Player 1
2) Player 2""")
solo_menu_options = ["1","2"]
while solo_menu not in solo_menu_options:
solo_menu = input("Please enter your choice here:")
solo_player["Contestant "+solo_menu]["Player "+solo_menu].append(solo_name)
print(solo_player["Contestant "+solo_menu])
print("Thank you for taking the spot of Player "+solo_menu)
My ideal output would be that the definition would just stop as soon I entered all the necessary user inputs

Related

Trying to run multiple different functions based on user input

tnames = []
inames = []
def teamEnter():
for x in range (4):
tnames.append(input("Please enter a team name:"))
print(tnames)
tevent1()
tevent2()
#This loops 4 times and asks you to enter 4 team names
def individualEnter():
for x in range (20):
inames.append(input("Please enter an individuals name:"))
print(inames)
ievent1()
#This loops 20 times and asks you to enter 20 individual names
def intro():
inp = input("Would you like to hold a tournament for teams or individuals: ")
# Asks the user to enter as a team or individual
print (' ')
TeamOrIndividual = str(inp)
if inp == "Individuals":
individualEnter()
elif inp =="Teams":
teamEnter()
#This is the initial home page where you choose between teams or individuals
intro()
def tevent1():
print("This is the relay race event")
def tevent2():
print("This is the football event")
def ievent1():
print("This is the tug of war event")
def ievent2():
print("This is the dodgeball event")
I want to be able to run the tevent1 and tevent2 when the user inputs 'Teams' when the code is run and the ievent1 and ievent2 when the user inputs 'Individuals' when the code is run.
How do i do this?
I tried IF statements to see if that worked by it didnt
Is this what you are trying to do?
tnames = []
inames = []
def teamEnter():
for _ in range(4):
tnames.append(input("Please enter a team name:"))
print(tnames)
tevent1()
tevent2()
#This loops 4 times and asks you to enter 4 team names
def individualEnter():
for _ in range(20):
inames.append(input("Please enter an individuals name:"))
print(inames)
ievent1()
ievent2()
#This loops 20 times and asks you to enter 20 individual names
def tevent1():
print("This is the relay race event")
def tevent2():
print("This is the football event")
def ievent1():
print("This is the tug of war event")
def ievent2():
print("This is the dodgeball event")
inp = input("Would you like to hold a tournament for teams or individuals: ").lower()
# Asks the user to enter as a team or individual
print()
if inp == "individuals":
individualEnter()
elif inp =="teams":
teamEnter()

Python - While Loops Not Appearing in Console When the code is run

I'm currently trying to make a scoring system where a user can enter an event as a team and I used while loops and defs to make this possible but I'm having trouble using them.
def team_menu():
global teamS
team_player = ""
while team_player:
team_player = input("What is your name:")
print("""\n Available Teams \n
1) Team Ahab
2) Team Ishmael
\n 3) Go back to Main Menu\n""")
team_choice = ""
team_choice_option = ["1","2","3"] # all valid choices on team menu
while team_choice not in team_choice_option:
team_choice = input("Enter your choice here:")
if team_choice == "1":
teamS["Team 1"]["Team Ahab"].append(team_player)
print(teamS["Team 1"])
print("Thank You for Joining Team Ahab")
team_choice = True
elif team_choice == "2":
teamS["Team "+ 2]["Team Miller"].append(team_player)
print(teamS["Team 2"])
print("\nThank You for Joining Team Miller\n")
team_choice = True
elif team_choice == "3":
menu()
team_choice = True
else:
print("Enter a value between 1-3")
team_choice = False
When I try to run this code it imidiently asks me for what to team to join even though it didn't even ask of the name of the user before. How do I fix this? My ideal output would be to ask for the name of the user first then let them pick what team they want to join
The loops within the function seem unnecessary since you're only prompting for one player.
from typing import Dict, List, NamedTuple
class Team(NamedTuple):
name: str
players: List[str]
def team_menu(team_dict: Dict[str, Team]) -> None:
player = input("What is your name: ")
print(
"""
Available Teams
1) Team Ahab
2) Team Ishmael
3) Go back to Main Menu
"""
)
choice = ""
while choice not in ["1", "2", "3"]:
choice = input("Enter your choice here:")
if choice == "3":
return # back to main menu
team_dict[choice].players.append(player)
print(f"Thank you for joining {team_dict[choice].name}")
team_dict = {
"1": Team("Team Ahab", []),
"2": Team("Team Ishmael", []),
}
team_menu(team_dict)
# menu()
You need to change 7th line:
while team_player == "":
You are using complex two-state branching based on team_player and team_choice values, it could be facilitated with one current state of team menu aka state machine:
from collections import namedtuple
def team_menu():
# Code smells, it could be passed here by param, i.e. team_menu(teamS)
global teamS
states = namedtuple("States", ("CHOOSE_PLAYER", "CHOOSE_TEAM", "END"))
# Starts from player.
state = states.CHOOSE_PLAYER
while state != states.END:
if state == states.CHOOSE_PLAYER:
team_player = input("What is your name:")
# If player name selected then continue with team.
if team_player:
state = states.CHOOSE_TEAM
elif state == states.CHOOSE_TEAM:
print(
"""
Available Teams
1) Team Ahab
2) Team Ishmael
3) Go back to Main Menu
"""
)
team_choice = input("Enter your choice here:")
# all valid choices on team menu
team_choice_option = ["1", "2", "3"]
# If team selected, add this player and continue with another player.
if team_choice in team_choice_option:
state = states.CHOOSE_PLAYER
if team_choice == "1":
teamS["Team 1"]["Team Ahab"].append(team_player)
print(teamS["Team 1"])
print("Thank You for Joining Team Ahab")
elif team_choice == "2":
teamS["Team 2"]["Team Miller"].append(team_player)
print(teamS["Team 2"])
print("Thank You for Joining Team Miller")
elif team_choice == "3":
# You don't need to call menu() but if you do, then
# be prepared to get sometimes "RecursionError: maximum
# recursion depth exceeded".
state = states.END
else:
print("Enter a value between 1-3")
# There is the end of team_menu() it could return `teamS` here
# to main `menu()` to avoid using global.
return None

Progressing to next menu option in python

I have a question regarding menus and how to make a "progress to Option __ " option (please note, I am very new to Python, so this may be a very easy fix and I just haven't searched for the right thing). In my current code, I have the ability for users to choose one of 4 options with activities in them. A part of options C and D use data from option B (but are able to be visible to the user without doing Option B, just as an information hub of sorts, rather than calculating). I have made up some code to show what I am talking about below:
def printMenu ():
print("Activity List")
print("A: Standalone Activity - What is the weather like")
print("B: Events")
print("C: Times")
print("D: Olympic Standards")
print("X: Exit")
return input("Please choose a selection: ").upper()
def main():
choice = printMenu()
choice
def program(selection):
if selection == "A":
print("The weather is not important, as I am a computer")
elif selection == "B":
eventInfo = input("What is your best event and distance: ")
def sportMenu():
print("1. Return to Main Menu")
print("2. Choose another sport")
print("3. Continue to Part C: Countries")
print("ENTER. Close application")
sportMenu()
sportsMenu = input("Please select an option: ")
if sportsMenu == "1":
main()
elif sportsMenu == "2":
sports()
elif sportsMenu == "3":
times()
else:
exit()
elif selection == "C":
# information for users who selected option C originally
print("Talking about World Record times in certain events")
# if they selected B and chose an event, this is where they would be sent to
print("You have selected the event: ", eventInfo)
timeInfo = input("Please enter your best time (MM:SS.ss): ")
# same menu as above, sending to main, section B to choose a different event, section D for comparison, or exit program
...
elif section == "D":
# information for users who selected option C originally
print("Talking about top competitor's times in certain events and how younger athletes aspire to reach them, and the benefits of comparing times")
# if they selected B and chose an event, and input a time at C this is where they would be sent to
print("Your time of", timeInfo, "for", eventInfo, "has been compared to the World Record time of ____")
# an external file of all World Record times is then referred to, and compared to the user's input in timeInfo
# menus as above, main, going back to B, or C for different events or times respectively, or exit program
elif selection == "X":
exit()
else:
print("Try again, please ensure the letter is shown in the menu")
selection = printMenu()
while selection != 'X':
program(selection)
print()
selection = printMenu()
I am wondering if there is a way for users to input answers in option B, and skip directly to the section of code saying # if they selected B and chose an event, this is where they would be sent to, with information they input in section B (stored in eventInfo I would imagine)? I assume it would be the same process from C to D, and I am almost there, but obviously without those options being defined prior to wanting to jump to them, I get the error. Any help will be greatly appreciated! Thanks

python code output is once but put into function and output duplicates itself

I have this code that works fine and the output is correct.
game_type = input("ongoing competition or single play? ")
if game_type == 'single play':
users = (input("how many players? "))
while not users.isdigit():
users = (input("how many players? "))
users = int(users)
players = {}
for person in range(users):
name = input("player's name? ")
players[name] = []
----output----
ongoing competition or single play? single play
how many players? 2
player's name? bob
player's name? red
But when I try to put the code into functions it asks me "how many players" twice in the output. I'm not sure why it's doing this.
def people():
users = (input("how many players? "))
while not users.isdigit():
users = (input("how many players? "))
return int(users)
users = people()
players = {}
def player_name():
for person in range(users):
name = input("player's name? ")
players[name] = []
---------------------------------------------------------
game_type = input("ongoing competition or single play? ")
from func import *
if game_type == 'single play':
people()
player_name()
----output----
ongoing competition or single play? single play
how many players? 2
how many players? 2
player's name? red
player's name? bob
You call people() twice. You assign the return value of it in the global scope to the variable "users" and then call it in an if statement. If you need the same variables in different scopes then you may want to create a class and do some configuration in your constructor.

Same conditional branch keeps being executed regardless of user input

I'm trying to write the basic code for a random name generator in Python. This will soon become a fully working web application with an easy-to-use GUI but for some reason the program doesn't work.
When I run the program, it asks the user to specify either "console" or "game". When I enter "game" it still carries on with the if route instead of the else route.
import string
#This is a Name Generato
print("Welcome To the first version of my name generator at the moment there is only 20 names but in the final version there will be 200 names with over 25 different tags")
print("First of all what do you need a Console or a game Name?")
console = input()
if (console):
print("is it a,PS4,PS3,XBOX 360,XBOX ONE or PC")
print("NOTE:Wii,PSP and DS are not supported")
consolename = input()
print("The,",consolename)
print("Is good")
print ("now give me one or two key words that you would like in your name out of...")
print("happy,sad,depressed,fox,cow,cat,dog,wolf,lion,lil,lazy,forgetful,gaming,xxx,orthodox,apex,toXic")
firstname1=input()
secondname=input()
print(firstname1)
print(secondname)
print("Good Choice")
else:
print("What game is it?")
print("Minecraft,Black ops 1//2/3,COD,Halo1/2/3/4/5/CE/Reach,Terraria,World of warcraft,League Of Legends")
print("NOTE:Type the Game As you see it!")
game1 = input()
print("Ah good choice eh")
You are getting a string input and you are checking if its True which is always true if its not empty. You need to compare your console variable to a string. Something like this will do the job.
import string
#This is a Name Generato
print("Welcome To the first version of my name generator at the moment there is only 20 names but in the final version there will be 200 names with over 25 different tags")
print("First of all what do you need a Console or a game Name?")
console = input()
if (console=="console" or console=="Console"):
print("is it a,PS4,PS3,XBOX 360,XBOX ONE or PC")
print("NOTE:Wii,PSP and DS are not supported")
consolename = input()
print("The,",consolename)
print("Is good")
print ("now give me one or two key words that you would like in your name out of...")
print("happy,sad,depressed,fox,cow,cat,dog,wolf,lion,lil,lazy,forgetful,gaming,xxx,orthodox,apex,toXic")
firstname1=input()
secondname=input()
print(firstname1)
print(secondname)
print("Good Choice")
else:
print("What game is it?")
print("Minecraft,Black ops 1//2/3,COD,Halo1/2/3/4/5/CE/Reach,Terraria,World of warcraft,League Of Legends")
print("NOTE:Type the Game As you see it!")
game1 = input()
print("Ah good choice eh")

Categories