Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
So I am creating a new simple game to practice my python programming, it is a point/score system that I wanted to implement. I also wanted to make it so it's intelligent by asking the user if it wants to play. So I have three problems at the moment, when I ask the user if it wants to play I wasn't sure what to do if they said no or "n" if they didn't want to play, instead what happens is that it just continues playing then crashes saying "n" is not defined. The second problem that I have is when the user puts the right answer for the random function I put print("You guessed it right!") but it just prints a bunch of them. My third and final problem is the point system, I wasn't sure if it executed after the million printed statements, but I'll see after I fix it.
Here is my game
import random
total_tries = 4
score = 0
print("Welcome to Guess the number game!")
answer = input("Would you like to play? y/n: ")
if answer == "y":
n = (random.randrange(1, 10))
guess = int(input("I am thinking of a number between 1 and 20: "))
while n!= guess:
if guess < n:
total_tries - 1
print("That is too low!")
guess = int(input("Enter a number again: "))
elif guess > n:
print("That is too high")
total_tries - 1
guess = int(input("Enter a number again: "))
else:
break
while n == guess:
score = +1
print("You guessed it right!")
if total_tries == 0:
print("Thank you for playing, you got", score, "questions correct.")
mark = (score/total_tries) * 100
print("Mark:", str(mark) + ""%"")
print("Goodbye")
Error when putting no for playing:
while n!= guess:
NameError: name 'n' is not defined
For question 1 you want the system to exit when the user says no. I would do this by using sys.exit to kill the code.
import sys
...
answer = input("Would you like to play? y/n: ")
if answer == "y":
n = (random.randrange(1, 10))**strong text**
else:
sys.exit('User does not want to play, exiting')
For problem 2 you are getting your print statement a million times because you're failing to exit. In the code below n is always equal to guess because you never change n. You don't need a while statement here because you already know you only left the above section when n started to equal guess. Another issue to think about. How will you make it stop when the number of turns runs out?
while n == guess:
score = +1
print("You guessed it right!")
For the third question, think about what will happen here if the number of turns reaches 0.
if total_tries == 0:
print("Thank you for playing, you got", score, "questions correct.")
mark = (score/total_tries) * 100
In particular, what would happen when you try to calculate mark?
This condition will only trigger when answer is "y"
if answer == "y":
n = (random.randrange(1, 10))
Remove this and the code will run or modify it as such
if answer == "y":
n = (random.randrange(1, 10))
elif answer == "n"
# set n to some other value
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am trying to create a simple guessing game. Everything works absolutely fine, as it should. But, it can't seem to exit the first while loop which checks if the variable 'guessflag' is less than 15 or not. I also checked whether it is being updated or not by adding some print statements. Please help.
It even exits when it meets the condition which says to exit the program when the user guesses correctly. When I consulted some other queries regarding the same problem at stackoverflow, I tried to make sure that those mistakes don't happen to me. Also, I have to add some more finishing touches to reduce time taken by the program to run, but currently this works absolutely fine.
import random
point = 101
randomint = random.randint(0,100)
hintflag = 0
hintmessage = "To claim a hint, enter 102 in the input below. ***THE HINT WILL COME AT A COST OF 20 POINTS***"
guessflag = 0
while guessflag <=15:
def init(param):
global guess, point, guessflag
if(param == 1):
global point,guessflag
point = point - 1
guessflag = guessflag + 1
print(hintmessage)
guess = int(input("Enter your guess. It should be between 1 and 100... "))
proceed()
def proceed():
global hintflag
global point
if (guess < 1 or (guess > 100 and guess != 102)):
print('')
print("Please enter a number between 1 and 100... ")
init(2)
elif ((guess == 102)and(hintflag < 2 and hintflag >= 0)):
if(hintflag == 0):
checkrandeven()
if(hintflag == 1):
checkrandmultiple3()
else:
match()
def checkrandmultiple3():
if (randomint % 3 == 0):
global israndmultiple3, point, hintmessage, hintflag
hintflag = hintflag + 1
israndmultiple3 = True
point = point-20
hintmessage = 'You have exhausted all your hints'
print("The number to be guessed is a multiple of 3.")
print("Points: "+str(point))
init(2)
else:
hintflag = hintflag+1
israndmultiple3 = False
point = point-20
hintmessage = 'You have exhausted all your hints'
print("The number to be guessed is not a multiple of 3.")
print("Points: "+str(point))
init(2)
def checkrandeven():
if (randomint % 2 == 0):
global israndeven, point, hintmessage, hintflag
hintflag = hintflag+1
israndeven = True
point = point-20
hintmessage = 'To claim your ***LAST*** hint, enter 102 in the input below. ***THE HINT WILL COME AT A COST OF 20 POINTS***'
print('')
print("Your hint is...")
print("The number to be guessed is even.")
print("***YOU HAVE SPENT 20 POINTS***")
print("Points: "+str(point))
init(2)
else:
israndeven = False
hintflag = hintflag+1
point = point-20
hintmessage = 'To claim your ***LAST*** hint, enter 102 in the input below. ***THE HINT WILL COME AT A COST OF 20 POINTS***'
print("The number to be guessed is odd.")
print("Points: "+str(point))
init(2)
def match():
global randomint, guess, point, guessflag, hintflag
if(randomint != guess):
if(randomint < guess):
print("Try Again! Your number was too high; Try a number lower than "+str(guess))
init(1)
if(randomint > guess):
print("Try Again! Your number was too low; Try a number higher than "+str(guess))
init(1)
if(randomint == guess):
print ("CONGRATULATIONS! You won!")
print ("It took you "+ str(guessflag) + " tries, "+ str(hintflag)+" hints to beat the game!")
print("The number of points you finished with are... "+ str(point))
exit()
init(1)
The 'init(1)' call in your while loop is only actually called once, and your 4 functions call each other recursively. In other words, you never actually finish the first iteration of your while loop, you just go further and further down a chain of:
init -> proceed -> checkrandeven (or checkrandmultiple3) -> init -> proceed -> checkrandeven -> init -> proceed ...
Basically you need to think about restructuring your code to avoid the recursion. Try returning outputs within the main loop and then calling subsequent functions from there.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I made a simple number guessing Game and it works perfectly fine, but I want to add something that says "The Number you have entered is too high/ low", because when I type in 100 as my upper bound it is much too difficult to guess the number.
import random
while True:
flag = True
while flag:
num = input('Enter an upper bound: ')
if num.isdigit():
print("Let's Play!")
num = int(num)
flag = False
else:
print('Invalid input! Try again!')
secret = random.randint(1,num)
guess = None
count = 1
while guess != secret:
guess = input('Please enter a number between 1 and ' + str(num) + ": " )
if guess.isdigit():
guess = int(guess)
if guess == secret:
print('Right! You have won!')
else:
print('Try again!')
count += 1
print('You needed', count, 'guess(es) ')
Alright, I'm not gonna solve it for you, but I'll give you a hint. This seems like a homework problem, so it would be unethical of me to provide you with a solution.
else:
print('Try again!')
count += 1
Look at this else statement here. What is the purpose of this else statement? To tell the user they got the guess wrong.
Think about how you can put an if/else condition inside this else condition, to tell the user if their input is too high, or too low.
I'm new to Python and I wanted to practice doing loops because I’ve been having the most trouble with them. I decided to make a game where the user will pick a number from 0-100 to see if they can win against the computer.
What I have going right now is only the beginning. The code isn’t finished. But trying out the code I got a Syntax error where the arrow pointed at the colon on the elif function.
How do I fix this? What can I do?
I accept any other additional comments on my code to make it better.
Here’s my code:
import random
min = 0
max = 100
roll_again = "yes"
quit = "no"
players_choice = input()
computer = random.randint
while roll_again == "yes":
print("Pick a number between 1-100: ")
print(players_choice)
if players_choice >= 0:
print("Your number of choice was: ")
print(players_choice)
print("Your number is high.")
if computer >= 0:
print("Computers number is: ")
print(computer)
print("Computers number is high.")
if computer >= players_choice:
print("Computer wins.")
print("You lose.")
print("Would you like to play again? ", +roll_again)
elif:
print(quit)
end
Goal:
Fix computer-player game while learning more about python. Providing additional documentation on where to start would be helpful.
The reason you are getting an error pointing to elif is because elif needs a condition to check. You need to use if elif and else like this:
if a == b:
print('A equals B!')
elif a == c:
print('A equals C!')
else:
print('A equals nothing...')
Also, Python relies on indentation to determine what belongs to what, so make sure you are paying attention to your indents (there is no end).
Your code has more errors after you fix the if statements and indentation, but you should be able to look up help to fix those.
There are a lot of problems with your code. Here is a working version, hope it helps you understand some of the concepts.
If not, feel free to ask
import random
# min and max are names for functions in python. It is better to avoid using
# them for variables
min_value = 0
max_value = 100
# This will loop forever uless something 'breaks' the loop
while True:
# input will print the question, wait for an anwer and put it in the
# 'player' variable (as a string, not a number)
player = input("Pick a number between 1-100: ")
# convert input to a number so we can compare it to the computer's value
player = int(player)
# randint is a function (it needs parentheses to work)
computer = random.randint(min_value, max_value)
# print what player and computer chose
print("Your choice: ", player)
print("Computer's choice: ", computer)
# display the results
if computer >= player:
print("Computer wins. You loose")
else:
print("you win.")
# Determine if user wants to continue playing
choice = raw_input("Would you like to play again? (yes/No) ")
if choice != 'yes':
# if not
break
There are a lot of indentiation issues and the if and elif statements are used incorrectly. Also take a look at how while loops work.
Based on the code you provided here is a working solution, but there are many other ways to implement this.
Here is some helpful tutorials for you on if/else statements as well as other beginner topics:
Python IF...ELIF...ELSE Statements
import random
minval = 0
maxval = 100
roll_again = "yes"
quit_string = "no"
while True:
players_choice = int(input("Pick a number between 1-100:\n"))
computer = random.randint(minval,maxval)
#checks if players choice is between 0 and 100
if players_choice >= 0 and players_choice <= 100:
print("Your number of choice was: ")
print(players_choice)
#otherwise it is out of range
else:
print("Number out of range")
#check if computers random number is in range from 0 to 100
if computer >= 0 and computer <= 100:
print("Computers number is: ")
print(computer)
# if computer's number is greater than players number, computer wins
if computer > players_choice:
print("Computer wins.")
print("You lose.")
#otherwise if players number is higher than computers, you win
elif computer < players_choice:
print("You won.")
#if neither condition is true, it is a tie game
else:
print("Tied game")
#ask user if they want to continue
play_choice = input("Would you like to play again? Type yes or no\n")
#checks text for yes or no use lower method to make sure if they type uppercase it matches string from roll_again or quit_string
if play_choice.lower() == roll_again:
#restarts loop
continue
elif play_choice.lower() == quit_string:
#breaks out of loop-game over
break
I am making a custom version of hangman for a college assignment using python, but currently I'm having an issue with two parts to my code, its a game of hangman.
I have included the entire code below so that if anyone can answer they have the full information from the code.
The issues I'm having are that this part of the code is not ignoring the input before so it still lets you guess multiple letters.
if len(guess) > 1:
print("Ye can't be cheatin' now, ye be using up ya guesses.")
failed += 1
The second issue I have is that once you win the game it doesn't ask if you want to play again properly (I have tried multiple methods to try to fix this including another while loop inside the if statement.
if failed == 0:
print("Ye be living for now")
print("The word was: " + myword)
print
...
while True:
...
if failed == 0:
print("Ye be living for now")
print("The word was: " + myword)
# Current Bug: Play again here, cannot use same line as end.
print
guess = input("guess a letter: ").lower()
if len(guess) > 1:
print("Ye can't be cheatin' now, ye be using up ya guesses.")
failed += 1
# Current Bug: still takes input into consideration when it shouldn't
guesses += guess
...
play_again = input("If you'd like to play again, please type 'yes' or 'y': ").lower()
if play_again == "yes" or play_again == "y":
continue
else:
play_again != "yes" or play_again != "y"
break
This should solve your problem of taking multiple letters as input
if len(guess) > 1:
print("Ye can't be cheatin' now, ye be using up ya guesses.")
failed += 1
# Current Bug: still takes input into consideration when it shouldn't
else:
guesses += guess
This will only add the input to guesses if its length is less than 1.
And if you want to ask the game to play again, after winning put your code in a while loop. Something like this:
play_again = 'y'
while(play_again == 'y' or play_again='yes'):
win = False
while(!win):
<your code for game, set win = True after winning>
play_again = input("Want to play again y or n: ").lower()
Edit: You can add failed along with win in the while loop as well.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
My problem here is when I ask if the player wants to play again, if they say no, I have it to where it's supposed to quit the script. but it doesn't seem to be working. Here's the full code:
def choose_level():
print("Please choose a level:\n"
"\n"
"(Level 1) - Easy\n"
"(Level 2) - Medium\n"
"(Level 3) - Hard\n")
lvl_1={"Level 1","level 1","1"}
lvl_2={"Level 2","level 2","2"}
lvl_3={"Level 3","level 3","3"}
choice=input("")
if choice in lvl_1:
level_1()
elif choice in lvl_2:
level_2()
else:
print ("[!] UNKNOWN LEVEL [!]\n")
choose_level()
def level_1():
import random #imports the module 'random'
yes={"Yes","Y","yes","y"} #set 'yes' to these 4 strings
no={"No","N","no","n"} #set 'no' to these 4 strings
name=input("What's your name?\n") #asks for a name
secret=int(random.random()*10)+1 #randomly generate a number
trynum=0 #sets the number of tries to 0
print ("---------------------------------------------------------------------\n"
"---- Welcome,",name+"! To Level 1!\n"
"---- I am thinking of a number between 1 and 10.\n"
"---- Lets see how many times it will take you to guess the number.\n"
"---------------------------------------------------------------------\n")
while True: #starts a loop
trynum=trynum+1 #sets number of tries to itself + 1
guess=int(input("What is guess #"+str(trynum)+"?\n")) #asks for a guess
if guess<secret: #if guess is too low/less than(<)
print ("Too Low. Try again!")
elif guess>secret: #if guess is too high/greater than(>)
print ("Oops!! Too high, better luck next try!")
else:
if trynum==1: #if number of tries is only 1
print ("-------------------------------------------------\n"
"----",name+"! You got it in",trynum,"guess!\n"
"-------------------------------------------------\n")
else: #if number of tries is anything else
print ("-------------------------------------------------\n"
"----",name+"! You got it in",trynum,"guesses!\n"
"-------------------------------------------------\n")
if trynum<3: #if guessed in less than 3 tries
print ("Bravo!")
elif trynum<5: #if guessed in less than 5 tries
print ("Hmmmmpf... Better try again")
elif trynum<7: #if guessed in less than 7 tries
print ("Better find something else to do!")
else: #if guessed in more than 7 tries
print ("You should be embarssed! My dog could pick better.")
choice=input("""Would you like to play again? ("yes" or "no")\n""") #asks if you want to play again
if choice in yes: #if yes, then run game again
choose_level()
if choice in no: #if no, then quit the game
print ("Okay.. Goodbye :(")
quit
break
def level_2():
import random
yes={"Yes","yes","Y","y"}
no={"No","no","N","n"}
name=input("What's your name?\n")
secret=int(random.random()*8)+1
trynum=0
print ("--------------------------------------------------------------------------\n"
"---- Welcome,",name+"! to Level 2!\n"
"---- I am thinking of a number between 1 and 8.\n"
"---- You have 20 guesses, and the number changes after every 4th guess\n"
"--------------------------------------------------------------------------\n")
while True:
trynum=trynum+1
guess=int(input("What is guess #"+str(trynum)+"?\n"))
if trynum==4:
secret=int(random.random()*8)+1
print ("The number has changed!!")
elif trynum==8:
secret=int(random.random()*8)+1
print ("The number has changed!!")
elif trynum==12:
secret=int(random.random()*8)+1
print ("The number has changed!!")
elif trynum==16:
secret=int(random.random()*8)+1
print ("The number has changed!!")
elif trynum==20:
print ("-------------------------------------------------\n"
"----",name+", you lost! :(\n"
"-------------------------------------------------\n")
choice=input("""Would you like to play again? ("yes" or "no")\n""") #asks if you want to play again
if choice in yes: #if yes, then run game again
choose_level()
elif choice in no: #if no, then quit the game
print ("Okay.. Goodbye :(")
quit
if guess<secret:
print ("Too low, try again!")
elif guess>secret:
print ("Too high, try again!")
else:
if trynum==1: #if number of tries is only 1
print ("-------------------------------------------------\n"
"----",name+"! You got it in",trynum,"guess!\n"
"-------------------------------------------------\n")
else: #if number of tries is anything else
print ("-------------------------------------------------\n"
"----",name+"! You got it in",trynum,"guesses!\n"
"-------------------------------------------------\n")
if trynum<3: #if guessed in less than 3 tries
print ("Bravo!")
elif trynum<5: #if guessed in less than 5 tries
print ("Hmmmmpf... Better try again")
elif trynum<7: #if guessed in less than 7 tries
print ("Better find something else to do!")
else: #if guessed in more than 7 tries
print ("You should be embarssed! My dog could pick better.")
choice=input("""Would you like to play again? ("yes" or "no")\n""") #asks if you want to play again
if choice in yes: #if yes, then run game again
choose_level()
if choice in no: #if no, then quit the game
print ("Okay.. Goodbye :(")
quit
break
choose_level()
level_1()
level_2()
The problem I'm having is here:
choice=input("""Would you like to play again? ("yes" or "no")\n""") #asks if you want to play again
if choice in yes: #if yes, then run game again
choose_level()
if choice in no: #if no, then quit the game
print ("Okay.. Goodbye :(")
quit
break
When I run the program and I get to that point, and type 'no' it just puts me back on the first level. I'm stuck and not sure where to go from here. Any and all help is appreciated.
You are missing the pair of brackets that come after the quit command. The quit command is calling a function just like choose_level does, so you need to tell Python what parameters you want to pass in. Every function call needs a pair of brackets telling Python what arguments you want. The quit function is no different. In this case, there will be no parameters so you would just type quit().
sys.exit() , exit() , quit() , and os._exit(0) kill the Python interpreter
You should use quit() , not quit