How to fix printing errors in the code - python

There are a few problems with my code that I don't know how to fix.
When I am printing out the message of what game and the level they chose, at the end, it isn't printing out the level (beginner, intermediate or advanced). It only prints out the game. I have put 'num' to print it but i have also tried 'Level' and 'number' in place. The code is
print ("Play",gamelist[gametype], "at" ,num)
When asking the user what game they would like to play, if they input a number out of the range of 0-3 or a letter it breaks further down in the code when printing the message at the end. This is only when asking what game, not the level they want the game at.
Anything to help would be appreciated.
#Ask user what game they would like to play
def game () :
global gametype,gamelist
gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"]
gamecount = 0
print ("Hello",name,"the four games avaliable are:")
while gamecount < 4:
print (gamecount," ",gamelist[gamecount])
gamecount = gamecount + 1
gametype = int(input("What number game do you want? (Please choose between 0 and 3) "))
print ( "You have chosen",gamelist[gametype],)
print ("")
#Ask game level
def number():
while True:
try:
Level = int(input("What is the level you would like to play at? "))
if Level <= 25:
print ("Begginer ")
break
elif Level >=26 and Level <=75:
print ("Intermediate")
break
elif Level >=76 and Level <=100:
print ("Advanced")
break
else:
print("Out Of range(1-100): Please enter a valid number:")
except ValueError:
print("Please enter a valid number")
#Create a subroutine to print out the action message
def printmessage ():
print ("")
print ("# #")
print ("########################################################")
print ("#################### ACTION MESSAGE ####################")
print ("########################################################")
print ("# #")
print ("Play",gamelist[gametype], "at" ,num)
print ("# #")
print ("########################################################")
print ("#################### ACTION MESSAGE ####################")
print ("########################################################")
print ("# #")
#This is to let the program work
name = input("What is your name? ")
print ("")
game ()
num = number()
printmessage()

I put comment with the changes:
#Ask user what game they would like to play
def game (name) :
global gametype,gamelist
gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"]
gamecount = 0
print ("Hello "+name+" the four games avaliable are:")
while gamecount < 4:
print (gamecount," ",gamelist[gamecount])
gamecount = gamecount + 1
gametype = int(input("What number game do you want? (Please choose between 0 and 3) "))
print ( "You have chosen "+gamelist[gametype])
print ("")
#Ask game level
def number():
while True:
try:
Level = int(input("What is the level you would like to play at? "))
if Level <= 25:
print ("Begginer ")
return("Begginer ")#changed break with return so it will break and return the selected value
elif Level >=26 and Level <=75:
print ("Intermediate")
return("Intermediate ")#changed break with return so it will break and return the selected value
elif Level >=76 and Level <=100:
print ("Advanced")
return("Advanced ")#changed break with return so it will break and return the selected value
else:
print("Out Of range(1-100): Please enter a valid number:")
except ValueError:
print("Please enter a valid number")
#Create a subroutine to print out the action message
def printmessage (num):
print ("")
print ("# #")
print ("########################################################")
print ("#################### ACTION MESSAGE ####################")
print ("########################################################")
print ("# #")
print ("Play "+gamelist[gametype]+" at "+num)
print ("# #")
print ("########################################################")
print ("#################### ACTION MESSAGE ####################")
print ("########################################################")
print ("# #")
#This is to let the program work
name = raw_input("What is your name? ") # I changed input with raw_input because you are sending a string not integer
print ("")
game (name)
num = number()
printmessage(num)
This is the Output:
What is your name? Test
Hello Test the four games avaliable are:
(0, ' ', 'Mario Cart')
(1, ' ', 'Minecraft')
(2, ' ', 'Angry Birds')
(3, ' ', 'Grabd Theft Auto')
What number game do you want? (Please choose between 0 and 3) 0
You have chosen Mario Cart
What is the level you would like to play at? 1000
Out Of range(1-100): Please enter a valid number:
What is the level you would like to play at? 1
Begginer
# #
########################################################
#################### ACTION MESSAGE ####################
########################################################
# #
Play Mario Cart at Begginer
# #
########################################################
#################### ACTION MESSAGE ####################
########################################################
#

Add the following line of code at the end of function def number:
return Level

Related

Using system.exit

I am trying to add a sys.exit to my code now, but I want it to display the print messages before quitting. Can I do this? Also, at the end of my code, I would like to give the user the option to quit or start again, but when they type quit after finishing the first game, it just uses quit as their name.
import random
import sys
def system_exit(exitCode):
sys.exit()
# uses randrange instead of randint for better results in Python 3.7
# randrange stops just before the upper range, use (1, 11) for 1-10
num = random.randrange(1, 11)
name = input("What is your name? Or if you would rather quit, type quit at
any time. " "\n")
i = name
while i != "quit":
print('Hello', name,'!')
while i.lower() == 'quit':
print ("Sorry, you did not select a number in the range or
selected to quit. Good bye.")
system_exit(4)
your_guess = input('Enter a number between 1 and 10.' '\n')
if (your_guess.lower() == "quit"):
print ("Sorry, you did not select a number in the range or
selected to quit. Good bye.") #this isn't showing up before closing
your_guess = int(your_guess)
# display the number guessed
print("Your number is", your_guess)
while num != your_guess:
if your_guess < num:
print("Your guess is too low.")
your_guess = int(input("Guess another number from
1 to 10: " '\n'))
elif your_guess > num:
print("Your guess is too high")
your_guess = int(input("Guess another number from
1 to 10: " '\n'))
else:
print ("Sorry, you did not select a number in the
range or selected to quit. Good bye.") #this isn't showing up before
closing
system_exit(4)
print("The correct number was", num)
print("***************************************************************")
name = input("What is your name? Or if you would rather quit, type
quit. ")
num = random.randrange(1, 11)
print("Thank you for playing!") #this isn't showing up before closing
system_exit(0)
Replace the following line of code:
your_guess = int(input('Enter a number between 1 and 10.'))
with the code below:
your_guess = input('Enter a number between 1 and 10.')
if (your_guess.lower() == 'quit'):
#print some break message
your_guess = int(your_guess)

Fixing invalid syntax errors in try and except

When I use this code, my aim is to try and make sure that any input will not break the code like letters or numbers not between 0-3. But when i use this code the whole list isn't coming up. How would i fix this?
The output should look like this
Hello Megan the four games avaliable are:
0 Mario Cart
1 Minecraft
2 Angry Birds
3 Grabd Theft Auto
What number game do you want? h
Please choose a valid number
What number game do you want? 23
Please choose a number between 0 and 3
What number game do you want? 1
You have chosen Minecraft
Instead, the output is
Hello the four games avaliable are:
0 Mario Cart
What number game do you want? 2
1 Minecraft
What number game do you want? h
Please enter a valid value
The code i am using is:
#Ask user what game they would like to play
def game () :
global gametype,gamelist
gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"]
gamecount = 0
print ("Hello the four games avaliable are:")
while gamecount < 4:
print (gamecount," ",gamelist[gamecount])
gamecount = gamecount + 1
try:
gametype = int(input("What number game do you want? "))
while gametype <0 or gametype >3:
print (" Please enter a value between 0 and 3")
except ValueError:
print ("Please enter a valid value " )
return gametype
game ()
I have also tried another way, using 'while True' before 'try' but the program says that is an invalid syntax.
SECOND TRY
I have used this new code, but again it won't let me run the code as it says I have an invalid syntax when I put While True, with True highlighted in red.
#Ask user what game they would like to play
def game () :
global gametype,gamelist
gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"]
gamecount = 0
print ("Hello the four games avaliable are:")
while gamecount < 4:
print (gamecount," ",gamelist[gamecount])
gamecount = gamecount + 1
while True:
try:
gametype = int(input("What number game do you want? "))
if 0 <= gametype <= 3 :
return game
print ("Please enter a value between 0 and 3 ")
except ValueError:
print ("Please enter whole number from 0 to 3 " )
return game
game ()
I think you want something like this:
gamelist = ["Mario Cart", "Minecraft", "Angry Birds", "Grand Theft Auto"]
def game(name):
""" Ask user what game they would like to play """
print ("Hello, {}, the four available games are:".format(name))
for gamenum, gamename in enumerate(gamelist):
print(gamenum, ":", gamename)
while True:
try:
gamenum = int(input("What number game do you want? "))
if 0 <= gamenum <= 3:
return gamenum
print("Please enter a value between 0 and 3")
except ValueError:
print ("Please enter a whole number from 0 to 3")
name = input("What's your name? ")
gamenum = game(name)
print("You chose", gamelist[gamenum])
demo output
What's your name? Megan
Hello, Megan, the four available games are:
0 : Mario Cart
1 : Minecraft
2 : Angry Birds
3 : Grand Theft Auto
What number game do you want? 4
Please enter a value between 0 and 3
What number game do you want? Minecraft
Please enter a whole number from 0 to 3
What number game do you want? 2
You chose Angry Birds
The main change I made to your code is to put the try.. except stuff inside a while True block, so we keep asking for input until we get something valid. I also used enumerate to print each game with its number. That's neater than your while gamecount < 4: loop.
If you have to print the list of games using a while loop then you can do it like this:
gamelist = ["Mario Cart", "Minecraft", "Angry Birds", "Grand Theft Auto"]
def game(name):
""" Ask user what game they would like to play """
print ("Hello, {}, the four available games are:".format(name))
gamenum = 0
while gamenum < len(gamelist):
print(gamenum, ":", gamelist[gamenum])
gamenum += 1
while True:
try:
gamenum = int(input("What number game do you want? "))
if 0 <= gamenum <= 3:
return gamenum
print("Please enter a value between 0 and 3")
except ValueError:
print ("Please enter a whole number from 0 to 3")
name = input("What's your name? ")
gamenum = game(name)
print("You chose", gamelist[gamenum])
I made gamelist a global list so we can access it outside the game function. We don't need to use the global statement in the function because we aren't changing gamelist. In general, you should avoid using the global statement.

I'm trying to make a quiz on Python but my code keeps repeating

So, I'm trying to make a basic quiz in Python and when I get to a certain point when I'm testing the program my code will repeat for reasons I can't seem to work out...
My code:
`if choice == "2": #If the user enters 2 they will be taken here.
print (" ") #Makes a break between lines.
username=input ("Please enter your username:")
print (" ") #Makes a break between lines.
password=input ("Please enter your password:")
file=open ("userinformation.txt","r")
for line in file:
if username and password in line:
print (" ") #Makes a break between lines.
print ("Thank you for logging in " + username+".")
time.sleep (3)
#file.close()
print (" ") #Makes a break between lines.
print ("Please choose a topic and a difficulty for your quiz.")
time.sleep (4)
print (" ") #Makes a break between lines.
print("a.History - Easy.")
print (" ") #Makes a break between lines.
print("b.History - Medium.")
print (" ") #Makes a break between lines.
print("c.History - Hard.")
print (" ") #Makes a break between lines.
print("d.Music - Easy.")
print (" ") #Makes a break between lines.
print("e.Music - Medium.")
print (" ") #Makes a break between lines.
print("f.Music - Hard.")
print (" ") #Makes a break between lines.
print("g.Computer Science - Easy.")
print (" ") #Makes a break between lines.
print("h.Computer Science - Medium.")
print (" ") #Makes a break between lines.
print("i.Computer Science - Hard.")
print (" ") #Makes a break between lines.
topic = input("To choose a topic please enter the corrosponding letter:")
if topic == "a":
print (" ") #Makes a break between lines.
time.sleep(2)
print ("You have selected option a, History - Easy.") #Tells the user what subject they picked (Same result but with a different topic and difficulty displayed for each one
print (" ")
print ("Rules: You have an unlimited amount of time to anwser each question. You will be anwsering 2 questions and each question anwsered correctly")
print ("will reward you with 10 points.")
time.sleep(9)
print (" ")
print ("The maximum amount of points you can get is 20.")
time.sleep(3)
print (" ")
print ("Good luck!")
print (" ")
time.sleep(2)
print ("Question 1 -")
print ("When did World War 1 begin and end?")
print ("a. 1913 - 1917") #Incorrect anwser
print (" ")
print ("b. 1914 - 1919") #Incorrect anwser
print (" ")
print ("c. 1914 - 1918") #Correct anwser
anwserq1he = input ("Please pick an anwser:")
if anwserq1he == "b":
print(" ")
print("Sorry, that's the wrong anwser...")
time.sleep(3)
print(" ")
hisready = input ("Type ok when you are ready to proceed to the next question.")
elif anwserq1he == "a":
print(" ")
print("Sorry, that's the wrong anwser...")
time.sleep(3)
print(" ")
hisready = input ("Type ok when you are ready to proceed to the next question.")
elif anwserq1he == "c":
print(" ")
print ("That's the right anwser!")
print(" ")
time.sleep(2)
print ("Adding 10 points to your score...")
score = score +10
print(" ")
time.sleep(3)
hisready = input ("Type ok when you are ready to proceed to the next question.")
if hisready == "ok":
print(" ")
time.sleep(2)
print ("Question 2-")
print ("Which historical figure is commonly known as 'The lady with the lamp'?")
print ("a. Margaret Fuller")
print (" ")
print ("b. Florence Nightingale")
print (" ")
print ("c. Rosa Luxemburg")
anwserq2he = input ("Please pick an anwser:")
if anwserq2he == "a":
print ("Sorry, that's the wrong anwser...")
results = input("Please type results to get your results")
elif anwserq2he == "c":
print ("Sorry, that's the wrong anwser...")
results = input("Please type results to get your results")
elif anwserq2he == "b":
print (" ")
time.sleep(2)
print ("That's the right anwser!")
print(" ")
time.sleep(2)
print ("Adding 10 points to your score...")
score = score + 10
results = input("Please type results to get your results.")
if results == "results":
print(" ")
time.sleep(3)
print ("Getting your results...")
if score == 20:
print ("Congratulations, you scored 20 points. That's the best score you can get!")
elif score == 10:
print ("Well done, you scored 10 points. Almost there!")
elif score == 0:
print ("You scored 0 points. Try again and you might do better!")`
When I complete the quiz everything beyond print ("Thank you for logging in " + username+".")repeats...I'd appreciate it if anyone could help me. Thank you.
Sidenote: The #file.close is intentional.
Alright, so first of all we need to improve the program layout , maybe call in some functions would be useful. Here is some tips to fix the program.
First of all use : if username.strip() and password.strip() in line: [Use the .strip() function so it will match a word.
Your program is inefficient because if you press another value as in 2 it will break the program. You want to loop it and loop it over and over again therefore use the while True statement and create a function.
Add a function called exampleFunction() (I.E) and then on the bottom of the code ad this line but obviously indent it.
while True:
exampleFunction()
You don't need to use a or r just do file=open("your file.txt")
For example,
genre=input("What is the film you would like to search?: ")
f=open("Films.txt")
for line in f:
if genre in line.strip():
print(line)
I would personally fix this myself and post a copy of the code however this is too minor to fix therefore i'm leaving it to you.
Goodluck,
Matin

Python If/Else Statement Assistance

def main_menu():
print ("Three Doors Down Figurative Language Game")
print ("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*")
print ("NOTE: TO SELECT, TYPE NUMBER OF OPTION")
print ("")
print (" 1) Begin Game")
print ("")
print (" 2) Options")
print ("")
print ("")
menu_selection()
def menu_selection():
valid_answer = ["1","2"]
user_choice = str(input("Make a choice.."))
if user_choice in valid_answer:
def check_valid(user_choice):
if user_choice == 1: #Error section V
return("You started the game.")
else:
user_choice != 1
return("Credits to ____, created by ____")
check_valid(user_choice) #Error Section ^
else:
print("Please use an actual entry!")
menu_selection()
def enterText():
print("ENTER ANSWER!")
print (main_menu())
Okay, so the error should be labeled. That specific if/else statment shows up as "None" and I have tried every method to fix it. One method worked for the if/else statement on the outside, but not this one.
You're taking input as a string str(input()). Then, you're checking if user_input == 1; testing to see if it is an integer, even though it is a string. Instead, try converting to an integer using int(input()). Also, the line user_input != 1 is unnecessary, it's just the equivalent of writing True in your code. Furthermore, you define a function in your if statement, which shouldn't be there:
def main_menu():
print ("Three Doors Down Figurative Language Game")
print ("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*")
print ("NOTE: TO SELECT, TYPE NUMBER OF OPTION")
print ("")
print (" 1) Begin Game")
print ("")
print (" 2) Options")
print ("")
print ("")
menu_selection()
def menu_selection():
valid_answer = ["1","2"]
user_choice = int(input("Make a choice.."))
if user_choice in valid_answer:
if user_choice == 1:
return("You started the game.")
else:
return("Credits to ____, created by ____")
check_valid(user_choice)
else:
print("Please use an actual entry!")
menu_selection()
def enterText():
print("ENTER ANSWER!")
print (main_menu())

How do I get a function inside of a while loop in a function to work properly?

I have looked and looked for an answer, but I am new to python and the answers I find seem to be over my head or not quite what I need. I am trying to take my code and turn it into multiple functions to complete the simple task of receiving some grades from the user and displaying the input back to the user as they want it. Hopefully this will be more clear when you see my code.
import sys
gradeList = []
def validate_input():
try:
gradeList.append(int(grades))
except:
return False
else:
return True
def average(count, total):
ave = total / count
return ave
def exit(gradeList):
if gradeList == []:
print "You must enter at least one grade for this program to work. Good Bye."
sys.exit()
#def get_info():
while True:
grades = raw_input("Please input your grades.(or Enter once you have entered all of your grades): ")
if not grades:
break
elif validate_input() == True:
continue
else:
print "Please enter a number."
continue
def give_answers(gradeList):
while True:
print "\n",
print "Please select what you would like to do with your grades."
print "Press 1 for the Highest grade."
print "Press 2 for the Lowest grade."
print "Press 3 for the Average of the grades you entered."
print "\n",
print "Or you can press 'q' to quit."
choice = raw_input("> ")
if choice == 'q':
break
elif choice == '1':
print "\n",
print "The highest grade that you entered was %d.\n" % highest,
elif choice == '2':
print "\n",
print "The lowest grade that you entered was %d.\n" % lowest,
elif choice == '3':
print "\n",
print "Your average grade was %d.\n" % average,
else:
print "Please enter 1, 2, 3 or 'q'."
#get_info()
exit(gradeList)
gradeList.sort()
highest = gradeList[-1]
lowest = gradeList[0]
count = len(gradeList)
total = sum(gradeList)
average = average( count, total)
give_answers(gradeList)
Everything works correctly as I have pasted the code, but when I try to define get_info the nested validate_input() function stops working. It no longer populates the list so exit() catches and ends the program. The loop seems to just pass over the validate_input()function altogether because the else statement trips after each time through. My question is how do I get the validate_input() function to work properly while continuing to accept input until the user presses enter?
Pass grade to your function validate_input so it could add the grade to list like:
def validate_input(grades):

Categories

Resources