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 4 years ago.
Improve this question
I am currently self teaching myself Python , and this is my first program. I am doing some simple projects so i can improve. Would like to hear feedback on this one.
import random
print("There is a number between 1 and 100 guess it and you will win a price : ")
def guess():
# A simple guess game.
random_number = random.randint(1, 5)
flag = True
user_guess = []
while flag:
user_number = input("Enter the number : ")
user_guess.append(user_number)
if int(user_number) < random_number:
print("You have to go higher")
elif int(user_number) > random_number:
print("You have to go lower ")
else:
flag = False
print("Congrats you win !!! \nThe numbers of guesses before you won : ")
print(len(user_guess))
guess()
while True:
play_again = input("Do you like to play again ? : (y/n): ")
if play_again == 'y':
guess()
else:
print("Thank you for playing have a nice day!!! ")
break
Your program will throw an exception if the user enters an invalid (nondigit) character. Use isdigit to avoid such cases.
Converting user_number to integer every time you want to compare it with some other integer is costly, and frivolous. Convert it once and reassign it to user_number.
flag is not necessary. Use while True, and break when needed.
Keeping an entire list object just to count user input is a bit overkill. Have a single integer (count in my example) and use it.
You print "between 1 and 100" but your program creates a random integer between 1 and 5. I am not sure about your intentions with doing that (perhaps a debugging aid), but I presume it's a small mistake.
A minor suggestion, move the print("There is a number between 1 and 100 guess it and you will win a price : ") to the guess function since it makes more sense for the function to declare its own purpose.
Here's how I would make those changes to the guess function:
def guess():
print("There is a number between 1 and 100 guess it and you will win a price : ")
# A simple guess game.
random_number = random.randint(1, 100)
# flag = True obsolete
count = 0
while True:
user_number = input("Enter the number : ")
if (user_number.isdigit()):
user_number = int(user_number)
else:
print("Invalid:")
continue
count += 1
if user_number < random_number:
print("You have to go higher")
elif user_number > random_number:
print("You have to go lower ")
else:
print("Congrats you win !!! \nThe numbers of guesses before you won : ")
print(count)
break
Related
I need help changing the range and showing the user what the range is so they know if they are closer or not. I have given the description I have been given. On what I need to do . I have given the code that I have come up wit so far. Let me know if you need anything else from me.
Step 6 – Guiding the user with the range of values to select between
Add functionality so that when displaying the guess prompt it will display the current range
to guess between based on the user’s guesses accounting for values that are too high and too
low. It will start out by stating What is your guess between 1 and 100, inclusive?, but as
the user guesses the range will become smaller and smaller based on the value being higher
or lower than what the user guessed, e.g., What is your guess between 15 and 32,
inclusive? The example output below should help clarify.
EXAMPLE
----------------
What is your guess between 1 and 44 inclusive? 2
Your guess was too low. Guess again.
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
play()
#Part 1
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.")
print("\n")
def play():
''' Plays a guessing game'''
number = int(random.randrange(1,10))
guess = int(input("What is your guess between 1 and 10 inclusive ?: "))
number_of_guess = 0
while guess != number :
(number)
#Quit
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
#Guessing
if guess < number:
if guess < number:
guess = int(input("Your guess was too low. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
if guess > number:
if guess > number:
guess = int(input("Your guess was too high. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
#Winner
if guess == number :
number_of_guess += 1
print("Congratulations you won in " + str(number_of_guess) + " tries!")
again()
def again():
''' Prompts users if they want to go again'''
redo = input("Do you want to play again (Y or N)?: ")
if redo.upper() == "Y":
print("OK. Let’s play again.")
play()
elif redo.upper() == "N":
print("OK. Have a good day.")
sys.exit(0)
else:
print("I’m sorry, I do not understand that answer.")
again()
main()
What you'll need is a place to hold the user's lowest and highest guess. Then you'd use those for the range checks, instead of the hardcoded 1 and 11. With each guess, if it's a valid one, you then would compare it to the lowest and highest values, and if it's lower than the lowest then it sets the lowest value to the guess, and if it's higher than the highest it'll set the highest value to the guess. Lastly you'll need to update the input() string to display the lowest and highest guesses instead of a hardcoded '1' and '10'.
You need to simplify a lot your code. Like there is about 6 different places where you ask a new value, there sould be only one, also don't call method recursivly (call again() in again()) and such call between again>play>again.
Use an outer while loop to run games, and inside it an inner while loop for the game, and most important keep track of lower_bound and upper_bound
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
redo = "Y"
while redo.upper() == "Y":
print("Let’s play")
play()
redo = input("Do you want to play again (Y or N)?: ")
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.\n")
def play():
lower_bound, upper_bound = 0, 100
number = int(random.randrange(lower_bound, upper_bound))
print(number)
guess = -1
number_of_guess = 0
while guess != number:
guess = int(input(f"What is your guess between {lower_bound} and {upper_bound - 1} inclusive ?: "))
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
elif guess not in list(range(lower_bound, upper_bound)):
print("You're outside the range")
continue
number_of_guess += 1
if guess < number:
print("Your guess was too low")
lower_bound = guess
elif guess > number:
print("Your guess was too high")
upper_bound = guess
print("Congratulations you won in", number_of_guess, "tries!")
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I have an almost working code for my number guessing game. It runs completely fine up until the very end when asking the player if they want to play again and they type in "yes"--the Terminal outputs this:
Ha ha. You took too many guesses! I win! ^__^
Would you like to play again? (yes/no) yes
I'm thinking of a number between 1 and 99!
Ha ha. You took too many guesses! I win! ^__^
Would you like to play again? (yes/no)
I thought to just put the entire program in a while loop, but I have a few opening questions in the game that should only be asked the first time they run the program, and not every time they want to replay the game. (e.g Whats your name? Do you want to play?) I am not sure how to rerun the program but starting just after those initial questions. With my current code, I am lost at what to write for when the player types in "yes" at the ending to replay the game.
import random
import sys
guesses_taken = 0
number = random.randint(1, 99)
name = input("\nHello, what's your name? ")
print(f"\nNice to meet you, {name}.")
answer = input("Would you like to play a guessing game? (yes/no) ").lower()
while True:
if answer == "no":
print("\nToo bad, goodbye!\n")
sys.exit()
elif answer == "yes":
print(f"\nOkay, let's play!")
break
else:
print("\nSorry, I didn't get that.")
while True:
print("\nI'm thinking of a number between 1 and 99!")
while guesses_taken < 6:
guess = input("Take a guess: ")
guesses_taken += 1
if int(guess) > number:
print("\nYour guess is too high!\n")
elif int(guess) < number:
print("\nYour guess is too low!\n")
else:
print("\nArgh..you guessed my number! You win! -__-")
break
while guesses_taken >= 6:
print("\nHa ha. You took too many guesses! I win! ^__^")
break
again = input("\nWould you like to play again? (yes/no) ")
if again == "no":
break
sys.exit()
The variables guesses_taken & number will both retain their values when replaying, which makes for a not-very-interesting game. You need to do something to change that, like -
again = input("\nWould you like to play again? (yes/no) ")
if again == "no":
break
else:
guesses_taken = 0
number = random.randint(1, 99)
Functions, etc can make the code cleaner, but this is the minimal change you need to make to get things working.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
In my evergrowing quest for knowledge I would like to know if there is any way I can reduce the line count or make the code more efficient. Its for a game I have made and I have challenged myself to make it as short as I can, (in the original it was about twice as long as this :D)
import random
gameLives,hints,wonGame,levels,awardedLives,levelRange=3,6,0,[1,2,3,4,5,6,7,8,9,10],[1,3,5,7,10,12,15,20,0,0],[5,10,20,50,100,200,250,300,400,500]
def is_valid(guess):
try:
guess=int(guess)
return True,guess
except:
print("Try again, not a number")
repeat=1
def GameLevel(Range,gameLives,level,hints):
lives,hints,targetnumber,repeat=gameLives,hints,random.randint(1,1),1
print("LEVEL {}\nThinking...".format(level))
if level>1:
print("You now have {} lives remaining".format(gameLives))
if level==10:
print("Welcome to the hardest level\nNo bonus lives are awarded for the final level")
print("This number is between 1 and "+str(Range))
while repeat==1:
guess=input("What is your guess? ")
guess,repeat,targetnumber=guess.lower(),0,str(targetnumber)
if guess=="hint":
if level>=3:
if hints!=1:
targetnumber=int(targetnumber)
print("Number is between {} and {}".format((targetnumber // 10) * 10, (targetnumber // 10 + 1) * 10))
repeat,hints=1,hints-1
else:
print("Sorry you have ran out of hints :(")
repeat=1
else:
print("Hints are not available until level 3")
repeat=1
elif guess==targetnumber:
print("Well done, You have guessed my number!")
return lives,hints
elif guess!=targetnumber:
if is_valid(guess)==True:
print("Sorry that is not my number, you have lost a life. :(")
targetnumber,lives,repeat=int(targetnumber),lives-1,1
if lives<=0:
print("You have lost all your lives, so this means I win\nThe program will now end")
input("")
exit()
if guess<targetnumber:
print("The target number is higher")
else:
print("The target number is lower")
else:
repeat=1
print("Welcome to my number guessing game!\nI will think of a number between a certain range and you have to guess it.\nEach time you guess my number I will think of a harder one.\nYou will start with {} lives and {} hints, Good Luck!\nTo use your hint you will have to enter the word hint\nExtra lives will be awarded for each completed level".format(gameLives,(hints-1)))
a,b=0,0
for level in levels:
Range=levelRange[a]
gameLives,hints=GameLevel(Range,gameLives,level,hints)
if gameLives>0 and wonGame!=10:
addLives=awardedLives[b]
if addLives!=0:
print("You have gained {} extra lives".format(addLives))
gameLives+=addLives
wonGame+=1
a,b=a+1,b+1
score=gameLives+10*(hints-1)
print("Calculating your score.\nYour score is {} . Well done!".format(score))
This was the smallest that I ever managed to get the program with still working in the same way, in the question the code was 63 lines, I managed to reduce it to 29 lines;
import random; gameLives,hints,wonGame,levels,awardedLives,levelRange=3,6,0,[1,2,3,4,5,6,7,8,9,10],[1,3,5,7,10,12,15,20,0,0],[5,10,20,50,100,200,250,300,400,500]
def is_valid(y):
try:y=int(y);return True
except:print("Try again, not a number")
def GameLevel(Range,gameLives,level,hints):
lives,hints,targetnumber=gameLives,hints,random.randint(1,Range);print("LEVEL {}\nThinking...".format(level))
if level>1:print("You now have {} lives remaining".format(gameLives))
if level==int(levels[-1]):print("Welcome to the hardest level\nNo bonus lives are awarded for the final level")
print("This number is between 1 and "+str(Range))
while True:
guess=input("What is your guess? ");targetnumber=str(targetnumber)
if guess.lower()=="hint":
if level>=3:
if hints!=1:targetnumber,hints=int(targetnumber),hints-1;print("Number is between {} and {}".format((targetnumber // 10) * 10, (targetnumber // 10 + 1) * 10))
else:print("Sorry you have ran out of hints :(")
else:print("Hints are not available until level 3")
elif guess==targetnumber:print("Well done, You have guessed my number!");return lives,hints
elif guess!=targetnumber and is_valid(guess)==True:
print("Sorry that is not my number, you have lost a life. :(");guess,targetnumber,lives=int(guess),int(targetnumber),lives-1
if lives<=0:exit(input("You have lost all your lives, so this means I win\nThe program will now end\n"))
print("The target number is {}".format("higher" if (guess<targetnumber) else "lower"))
print("Welcome to my number guessing game!\nI will think of a number between a certain range and you have to guess it.\nEach time you guess my number I will think of a harder one.\nYou will start with {} lives and {} hints, Good Luck!\nTo use your hint you will have to enter the word hint\nExtra lives will be awarded for each completed level".format(gameLives,(hints-1)));a,b=0,0
for level in levels:
gameLives,hints=GameLevel((levelRange[a]),gameLives,level,hints)
if gameLives>0 and wonGame!=int(levels[-1]):
if awardedLives[b]>0:print("You have gained {} extra lives".format(awardedLives[b]));gameLives+=awardedLives[b]
wonGame+=1
a,b=a+1,b+1
input("Calculating your score.\nYour score is {} . Well done!".format(gameLives+10*(hints-1)))
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
import random
computer=random.randint(1, 100)
guess=int(input("guess the number"))
if guess > 100:
print("your guess is too high")
elif guess < 1:
print("your guess is too low")
elif guess==computer:
print("well done!")
else:
print("you\'re wrong, guess again")
This is my current code. it's game where the computer randomly chooses a number and the player has to guess it. i have tried but i don't know how to ask the player if they want to play again and if they say yes how to restart it.
Wrap the game code to function and use while True to call it again and again
import random
def play():
computer=random.randint(1, 100)
guess=int(input("guess the number"))
if guess > 100:
print("your guess is too high")
elif guess < 1:
print("your guess is too low")
elif guess==computer:
print("well done!")
else:
print("you\'re wrong, guess again")
while True:
answer = input("do you want to play?")
if answer == 'yes':
play()
elif answer == 'no':
break
else:
print("dont understand")
Put all the if-else statements within one big while loop that keeps looping until the user guesses the number correctly. Then, after each losing outcome, give the user another chance to guess the number so that the loop has a chance to reevaluate the guess with the next iteration. In my modification below I decided to leave the last if-else statement outside of the loop because when the user guesses correctly, the code will break out of the loop to check if the guess is correct. Of course in this scenario it has to be correct so the user is told that he or she is right and the program terminates.
import random
computer=random.randint(1, 100)
guess=int(input("guess the number\n"))
while(guess != computer):
if guess > 100:
print("your guess is too high\n")
guess=int(input("guess the number again\n"))
elif guess < 1:
print("your guess is too low\n")
guess=int(input("guess the number again\n"))
if guess==computer:
print("well done!\n")
Just an overview of how you can do it.
initialize a variable play_again = "yes"
Place a while check on play_again:
while play_again == "yes":
Enclose all if statements and guess input in the while loop
Read the user input in a variable within but at the end of the loop:
play_again = raw_input("\n\nWant to play again?: ")
You can use a while loop for multiple iterations
import random
computer=random.randint(1, 100)
guess=int(input("guess the number"))
play_again = 'y'
while play_again == 'y':
if guess > 100:
print("your guess is too high")
elif guess < 1:
print("your guess is too low")
elif guess==computer:
print("well done!")
else:
print("you\'re wrong, guess again")
play_again = input("Want to play again(y/n): ")
You should put your code in while loop. Then after game ask user if they want to continue with input() function. If they say 'no' you can break the loop or set argument of while to False.
In the process of learning Python using the book 'Python Programming for the Absolute Beginner Third Edition' and struggling with a challenge that has been set.
I have to create a Number Guessing program where the player picks a number and the program tries to guess it by picking a random number then using higher or lower questions to get closer to the number. I've got most of it figured out but I'm struggling with the higher or lower loop. The trouble I'm having is that i can't get the program to not go above or below it's second to last guess i.e.
My number is 78
computer picks 50
i say higher
computer picks 80
i say lower
computer can then pick 12 (when i don't want it going below 50.
I'm using Python 3.1
Here is a copy of the code.
import random
computer_tries = 0
player_number = None
computer_guess = random.randint(1, 100)
print(
"""
Welcome Player to the fabulous number guessing game.
Please allow me to show you my incredible deduction skills
""")
question = None
while question != ("yes"):
question = input("Has the player picked a number? ")
question = question.lower()
if question == "yes":
print("\nI will now guess your number!!!\n")
while player_number == None:
computer_tries += 1
print(computer_guess, "\n")
confirmation = input("Is this the correct number? ")
confirmation = confirmation.lower()
if confirmation == "yes":
player_number = computer_guess
if computer_tries < 2:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"try to get it right!")
else:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"tries to get it right!")
else:
higher_lower = None
while higher_lower not in ("higher", "lower"):
higher_lower = input("Is my guess higher or lower"
+ " than your number? ")
higher_lower = higher_lower.lower()
if higher_lower == "higher":
higher = computer_guess
computer_guess = random.randint(higher, 101)
elif higher_lower == "lower":
lower = computer_guess
computer_guess = random.randint(0, lower)
else:
print("Please choose either higher or lower.")
input("\n\nPress the enter key to exit")
Thanks in advance for any help you folks can give.
Ally
I see the following problems with your code:
your random number generators are bound only on one side of the number spectrum, e.g. random.randint(0, lower) - so it's ignoring the higher bound. Similarly for computer_guess = random.randint(higher, 101).
I suggest you initialise higher and lower.
Some debug helps :)
Here's the working code:
import random
computer_tries = 0
player_number = None
computer_guess = random.randint(1, 100)
print(
"""
Welcome Player to the fabulous number guessing game.
Please allow me to show you my incredible deduction skills
""")
question = None
lower = 0 # initial lower guess
higher = 101 # initial higher guess
while question != ("yes"):
question = input("Has the player picked a number? ")
question = question.lower()
if question == "yes":
print("\nI will now guess your number!!!\n")
while player_number == None:
computer_tries += 1
print(computer_guess, "\n")
confirmation = input("Is this the correct number? ")
confirmation = confirmation.lower()
if confirmation == "yes":
player_number = computer_guess
if computer_tries < 2:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"try to get it right!")
else:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"tries to get it right!")
else:
higher_lower = None
while higher_lower not in ("higher", "lower"):
higher_lower = input("Is my guess higher or lower"
+ " than your number? ")
higher_lower = higher_lower.lower()
if higher_lower == "higher":
higher = computer_guess
computer_guess = random.randint(lower+1, higher-1)
elif higher_lower == "lower":
lower = computer_guess
computer_guess = random.randint(lower+1, higher-1)
else:
print("Please choose either higher or lower.")
print("DEBUG: number must be " + str(lower) + " < x < " + str(higher))
input("\n\nPress the enter key to exit")
You have to store something like min_comp_guess and max_comp_guess
Then, when you are about to "guess" number you have to generate it for a valid range (obviously min_comp_guess up to max_comp_guess).
I'm always second! :)
You are never storing the upper and lower bounds to the possible numbers. In your example, as soon as your program picks 50 and you say "higher", you need to store somewhere the information that "the number is definitely higher than 50". The same goes for when you answer "lower".
I may be completely wrong but whilst testing your code I found that by choosing the programs number was higher than my chosen number it would increase the number instead or a presumable decrease, not making it any closer to the number I had guessed. A similar higher/lower program I created had the same problem, to fix the problem I simply switched the more than and less than signs around, hopefully you find this helpful and could apply this to your program.