Trying to run multiple different functions based on user input - python

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()

Related

Python - Never Ending Multiple While Loops Interferring with Other Definitions

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

append object instance to a list with a if statement and print it in another branch

I create a few class about pet, the following code was part of my main() function, First, ask the user to select one thing they want to do. that is if use input '1' they will add some pet instance. At the same time, I want to append part of the pet instance's information to a list. Then if the user chooses to read this information. I want to print it in another if statement branch. that is when the user input '2'. the problem occurs when I input 2 after already generating some pet instance. the list called l_weight always be void. How could I fix it? I already try to use the global list but is not work
def main():
l_weight=[]
print("========menu=========")
print("1. to add a pet")
print("2. print current weight for all pet")
print("3. print all pets and owners")
print("4. to exist system")
a=int(input("you selection(just input the number before each function)"))
while(True):
if a==1:
a=int(input("please select what type of pet would be added: 1-- mammals 2--fish 3--amphibians"))
name = input('please enter the name of pet:')
dob = input('please enter the dob of pet:(year,month,day)')
bw = input('please enter the birth weight:')
name = input('please enter the owner name:')
address = input('please enter the onwer address:')
if a==1:
ls = input('please enter the litter size:')
hs = input('pet has claws(yes or no):')
op=mammals(name,dob,bw,name,address,ls,hs)
print(op)
l_weight.append(op.get_current_weight)
elif a==2:
sc = input('please enter the scale condition:')
sl = input('please enter the scale length:')
op =fish(name,dob,bw,name,address,sc,sl)
print(op)
l_weight.append(op.get_current_weight)
elif a==3:
iv = input('is venomous(yes or no):')
op =amphibians(name,dob,bw,name,address,iv)
print(op)
l_weight.append(op.get_current_weight)
else:
print(' input wrong vaule,please choose a number from 1,2 or 3')
return main()
elif a==2:
for i in l_weight:
print(i)
return main()
The reason l_weight() isn't appending is because in your code, you named the list l_weight and then in the rest of your code it's written as l_weigh
It should be:
def main():
l_weight=[]
print("========menu=========")
print("1. to add a pet")
print("2. print current weight for all pet")
print("3. print all pets and owners")
print("4. to exist system")
a=int(input("you selection(just input the number before each function)"))
while(True):
if a==1:
a=int(input("please select what type of pet would be added: 1-- mammals 2--fish 3--amphibians"))
name = input('please enter the name of pet:')
dob = input('please enter the dob of pet:(year,month,day)')
bw = input('please enter the birth weight:')
name = input('please enter the owner name:')
address = input('please enter the onwer address:')
if a==1:
ls = input('please enter the litter size:')
hs = input('pet has claws(yes or no):')
op=mammals(name,dob,bw,name,address,ls,hs)
print(op)
l_weight.append(op.get_current_weight)
elif a==2:
sc = input('please enter the scale condition:')
sl = input('please enter the scale length:')
op =fish(name,dob,bw,name,address,sc,sl)
print(op)
l_weight.append(op.get_current_weight)
elif a==3:
iv = input('is venomous(yes or no):')
op =amphibians(name,dob,bw,name,address,iv)
print(op)
l_weight.append(op.get_current_weight)
else:
print(' input wrong vaule,please choose a number from 1,2 or 3')
elif a==2:
for i in l_weight:
print(i)

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.

Lottery program that lets a user choose how many times they wish to play at once

I'm trying to make a lottery program that can output results after a user inputs their numbers. But I want the option to allow the user to also be able to pick "how many weeks they play for", that being, how many times the program outputs results that are randomized. Basically use the numbers they inputted to play multiple games of lottery with the same numbers x amount of times they wish. I want to know how to make my function repeat based on how many times they wish to play.
Here's my incomplete code.
import random
NUMBER_OF_PICKS = 3
MINIMUM_SELECTION = 1
MAXIMUM_SELECTION = 36
MONEY_WON = 10000
OFFSETT = 4
USER = input("Please enter your name:")
print("Hi " + USER + " good luck ")
WEEKS_PLAYED = input("How many weeks do you want to play: ")
def verify(playerNumbers, winningNumbers):
if playerNumbers == winningNumbers:
print("Congratulations! You Win ${}!".format(MONEY_WON))
print("Your numbers: ", playerNumbers, )
print("The winning lottery numbers were: ", winningNumbers)
else:
print("Sorry, you lose...")
print("Your numbers: ", playerNumbers)
print("The winning lottery numbers were: ", winningNumbers)
# 'get_user_nums', gets user numbers and puts into a sorted list for x in WEEKS_PLAYED:
def get_user_nums():
user_nums = []
while len(user_nums) < NUMBER_OF_PICKS:
nums = input("Pick a number {} through {}: ".format(MINIMUM_SELECTION, MAXIMUM_SELECTION))
try:
nums = int(nums)
except:
print("Sorry your input must be an integer!")
continue
if MINIMUM_SELECTION <= nums <= MAXIMUM_SELECTION:
if nums not in user_nums:
user_nums.append(nums)
else:
print("Sorry, you have already inputted that number")
else:
print("Sorry, Your number was not in range")
return sorted(user_nums)
# 'get_winning_nums', creates a sorted list with random nums ranging from 0-9 with a range of 3 values
def get_winning_nums():
return sorted(random.sample(range(MINIMUM_SELECTION, MAXIMUM_SELECTION), NUMBER_OF_PICKS))
# 'menu', creates the main menu to choose game or exit program
def play_pick_n():
user_nums = get_user_nums()
winning_nums = get_winning_nums()
verify(user_nums, winning_nums)
# 'main', calls the other functions
def main():
# lottery_menu()
while True:
choice = input("\nPlay?: Yes or No: ")
if choice == 'Yes':
string = "\n[Play Pick {}]".format(NUMBER_OF_PICKS) + "selected!"
dotted = '\n' + len(string) * "-"
print(dotted, string, dotted)
play_pick_n()
break
elif choice == 'No':
print("Thanks for playing!\n")
break
print("Sorry, that is not a valid input. \nPlease enter either Yes or No")
if __name__ == '__main__':
main()
Thanks for any help.
if you ant to use the same numbers for all weeks, use:
user_nums = get_user_nums()
for week in range(0, WEEKS_PLAYED):
winning_nums = get_winning_nums()
verify(user_nums, winning_nums)
You might want to move the question for the number of weeks inside your play_pick_n function, so the player can decide per bunch of numbers who long they should run.

python contact book while loop issue

I want my code below to ask users to add contacts which i will save in a dictionary.
When user responds N to whether they want to add new contact, the loop is supposed to terminate. When Y, the loop must continue and when they enter something which is neither N nor Y, the question must keep repeating till they enter Y or N.
My code below does not return to beginning of function when i type yes
contactbook = {}
def addcontact():
name = input("Enter the name of your new contact")
number = int(input("Enter your phone contact"))
contactbook[name] = number
print("Contact book successfully updated with : ", contactbook.items())
while True:
qu = 'X'
while qu not in 'YN':
qu = input("Do you want to add a new contact? Y/N").upper()
elif qu == 'N':
break
After I reply Y to the question, I do not get the program to repeat
You can achieve that logic more cleanly by sth. like:
def addcontact():
while True: # no variable like keepadding needed
name = ...
# ...
qu = 'X'
while qu not in 'YN':
qu = input("Do you want to add a new contact? Y/N").upper()
if qu == 'N':
break
# no need to specify the 'Y' case, the outer loop just continues
This is because you are assigning to a variable named keepadding. The loop tests the value of a variable named keepreading. Because these variables are different the test will always be True and the loop will continue even if you enter N.
Update your code to initialise the variable at the top of the function and test the correct variable:
def addcontact():
keepadding = True
while keepadding:
....
Updated following OP code change:
Move the while loop to the top of the function so that the input() and contact book updates occur within the loop. Change elif to if. Here is a working version:
contactbook = {}
def addcontact():
while True:
name = input("Enter the name of your new contact")
number = int(input("Enter your phone contact"))
contactbook[name] = number
print("Contact book successfully updated with : ", contactbook.items())
qu = 'X'
while qu not in 'YN':
qu = input("Do you want to add a new contact? Y/N: ").upper()
if qu == 'N':
break
Try this:
contactbook = {}
def addcontact():
keepadding = True
while keepadding:
name = input("Enter the name of your new contact: ")
number = int(input("Enter your phone contact: "))
contactbook[name] = number
print("Contact book successfully updated with {}, {}".format(name, number))
while True:
qu = input("Do you want to add a new contact? Y/N ").upper()
if qu in 'YN':
break
print("That's not a valid input. Try again.")
keepadding = qu.upper() == 'Y'
addcontact()

Categories