Month: December 2014

Year 10 IF statement practice

# Import any functions we need
import random

# Initialise our variables
# Set the captain player number to 1
captain = 0
# Set the number of players to 1
players = 0
# Set the While loop value to True
playagain = True

# Define any functions we need
# The function is called ‘captainizer’. This is fed the number of players (players) when called
def captainizer (players):
# Create a random integer between 1 and the number of players.
captain = random.randint(1,players)
# Return the number of the captain using the variable name ‘captain’
return captain

# Print a welcome message to the users

print (“””
Welcome
Which sport would you like?
1 Football
2 Rugby
3 Double’s Tennis
“””)

# Begin the body of the programme. The While statement continues until False

while playagain:
# We are going to give users a choice of sports. This is in case people do not know how many should be on a team
# This can be expanded easily with more sports.
# Ask the user which sport they would like
sportchoice = input (“Choose your sport, 1,2 or 3”)
# Sport Choice Sections
# Check for sport and initialise variable with number of players, call the captainizer function and output the value to the screen
# Whilst this code could be simplified, this method makes adding new sports very quick.
# Choice 1
if sportchoice == “1”:
players = 11
captain = captainizer (players)
print (“Out of “,players,”, your Captain is player number “,captain)
#Choice 2
elif sportchoice == “2”:
players = 15
captain = captainizer (players)
print (“Out of “,players,”, your Captain is player number “,captain)
#Choice 3
elif sportchoice == “3”:
players = 2
captain = captainizer (players)
print (“Out of “,players,”, your Captain is player number “,captain)
#Trap if no valid choice is made.
else:
print (“You didn’t choose a valid sport”)

# Output the results to a file
try:
#Open a file with name “captain.txt” and place in append mode
captainfile = open(“captain.txt”, “a”)
try:
# Text String
captainfile.write(“Your Captain is player number “)
# Note that you cannot output numbers without turning them into a text string
captainfile.write(str(captain))
#T ext String
captainfile.write(” out of “)
# Note that you cannot output numbers without turning them into a text string
captainfile.write(str(players))
# Text String
captainfile.write(” players”)
# Text String
captainfile.write(“\n”)
finally:
# Close the file
captainfile.close()
except IOError:
pass

# Now we test for whether the user wants another go
# Set the while look value to True, just to be sure.
playagain = True
# Ask the user if they want to play again
playagain = input(“Do you want to choose another captain? (y/n)”)
# never assume they will do as they are told. Strip out all capitals and allow y and yes to be valid answers to play again
playagain = playagain.strip().lower() in (‘y’,’yes’)

# Now we say goodbye
print (“Thank you for playing”)
quit