I wrote the Python code below that is supposed to "guess" a number between 1 and 100, you just have to tell it if the number you're thinking of is higher or lower. But for some reason when I try playing it, it always gets stuck when I tell it that my number is higher after telling it that it's lower or vice versa:
import random
import time
import math
correct = 0
goon = 'yes'
biggest = 100
smallest = 1
tries = 10
print 'Hi!'
time.sleep(0.5)
print 'I´m going to try and guess your number'
time.sleep(0.5)
print 'Just tell me if your number is bigger or smaller than what I guessed'
time.sleep(0.5)
print 'And of course you have to tell me when I´m right, ok?'
time.sleep(0.5)
print 'Type "b" if your number is smaller than what I guessed and type "s" if it´s bigger. When I´m right, type "r".'
time.sleep(0.5)
print 'Oh by the way, your number should be between 1 and 100.'
if goon == 'no' or goon == 'No' or goon == 'n':
print 'Ok, see you soon!'
else:
while goon == 'yes' or goon == 'Yes' or goon == 'y':
guess = random.randint(1,100)
print guess
answer = raw_input()
while correct == 0:
if answer == 'r':
correct = 1
endhooray = random.randint(1, 3)
if endhooray == 1:
print 'Yay, I got it!'
elif endhooray == 2:
print 'Finally!'
elif endhooray == 3:
print 'See, I´m good at this!'
elif answer == 'b':
smallest = guess
difference = 100 - guess
add = random.randint(1, difference)
guess = guess + add
if guess < biggest:
print guess
answer = raw_input()
elif guess > biggest:
while tries == 10:
add = random.randint(1, difference)
guess = guess + add
if guess < biggest:
print guess
answer = raw_input()
tries == 1000000
elif answer == 's':
biggest = guess
difference = guess - 100
difference = difference * -1
subtract = random.randint(1, difference)
guess = guess - subtract
if guess > smallest:
print guess
answer = raw_input()
elif guess < smallest:
while tries == 10:
subtract = random.randint(1, difference)
guess = guess - subtract
if guess > smallest:
print guess
answer = raw_input()
tries = 100000
else:
print 'Oops, I don´t know what that means'
break
I took the liberty to simplify your code. This should do the job:
import random
import time
# your intro here
correct = False
min_, max_ = 0, 100
while not correct:
guess = random.randint(min_, max_)
answer = raw_input("Is your number %d? (b/s/r): " % guess)
if answer == "b":
min_ = guess+1
print "Ok, I'll aim higher!"
elif answer == "s":
max_ = guess
print "Ok, I'll aim lower!"
elif answer == "r":
hooray = random.choice(["Yay, I got it!", "Finally!", "See, I'm good at this!"])
print hooray
correct = True
else:
print "Oops, I don't know what that means!"
Related
I am relatively new to Python, but I tried making random number generator guessing game where you just guess the number and if it's right you win and if you lose the attempt counter decreases, like this:
import random
a = random.randint (1, 20)
c = input('Select difficulty (1, 2, 3, 4) : ')
d = int(c)
def main():
if d == 1:
tries = e = 15
elif d == 2:
tries = e = 10
elif d == 3:
tries = e = 5
elif d == 4:
tries = e = 3
else:
tries = e = 1
for tries in range(tries, -1, -1):
tries -= 1
b = int(input('Pick a number from 1-20 : '))
if a == b:
print('Congratulations!')
print('# of tries : ', e - tries)
exit()
elif tries == 0:
print('No more attempts left, game over')
exit()
else:
print('Incorrect')
print('Attempts left : ', tries)
restart = input("Play again? (y/n)")
if restart == "y":
main()
else:
exit()
main()
So this program doesn't make sense unless you guess correctly on the first try because the attempt counter always stays the same. I think it's because everytime it goes back to the main() it redefines 'tries' as 15, 10, etc. The problem is if I put the 'if d == 1' section before def main() then it will say that 'tries' was referenced before assignment. There's probably a simple solution that I'm not seeing here and it's going way over my head, so hopefully what I'm asking makes sense. Feedback on the code irrelevant to the issue also appreciated.
Thanks.
The other answers will work just fine, but as a side note, you're calling main() inside main() which creates a recursive function. Unless you have a particular reason to do this, it should be avoided. Every previous attempt at the game will be held in memory until the user opts not to retry, and if you go far enough you'll run into a RecursionError. Try wrapping the whole program in a while loop, something like this:
import random
def main():
retry = True
while retry:
answer = random.randint(1, 20)
tries = 5 # Insert your own logic for num of tries
while tries > 0:
guess = int(input('Pick a number between 1 and 20: '))
if guess == answer:
print('Correct!')
break
else:
print('Incorrect')
tries -= 1
retry = input("Play again? (y/n)") == 'y'
main()
It's a little confusing to me why you're doing tries = e = num
A much cleaner way to do it would be to have a while loop that runs while the number of tries hasn't run out. You could set that number of tries to a variable based on the selected difficulty
One way to do it could be like this:
import random
# set number of tries based on difficulty chosen first, then all this
number = random.randint(1,50)
number_of_guesses = 0
while number_of_guesses < tries:
guess = input("Take a guess ")
guess = int(guess)
number_of_guesses = number_of_guesses + 1;
guesses_left = tries - number_of_guesses;
if guess < number:
print("Your guess is too low! You have " + str(guesses_left) + " guesses left")
if guess > number:
print("Your guess is too high! You have " + str(guesses_left) + " guesses left")
if guess == number:
break
if guess == number:
print("Good job! You guessed the number in " + str(number_of_guesses) + " tries :)")
if guess != number:
print("Sorry. The number I was thinking of was " + str(number) + " :)")
I changed the for loop to a while loop, removed the "tries = e = 15" and moved the "tries -= 1"
import random
a = random.randint (1, 20)
c = input('Select difficulty (1, 2, 3, 4) : ')
d = int(c)
def main():
if d == 1:
tries = 15
elif d == 2:
tries = 10
elif d == 3:
tries = 5
elif d == 4:
tries = 3
else:
tries = 1
while tries > 0:
b = int(input('Pick a number from 1-20 : '))
if a == b:
print('Congratulations!')
print('# of tries : ', tries)
exit()
else:
print('Incorrect')
tries -= 1
print('Attempts left : ', tries)
restart = input("Play again? (y/n)")
if restart == "y":
main()
else:
exit()
main()
Whenever you run the game and start guessing it asks first what is guess #0? I'm trying to get it to display "what is guess #1?" but. at the same time keep the number of guesses equal to the number guessed (if that makes sense). Here's my code so far:
import random
def play_game(name, lower=1, upper=10):
secret = random.randint(lower, upper)
tries = 0
print("-----------------------------\n"
"Welcome, {}!\n"
"I am thinking of a number\n"
"between {} and {}.\n"
"Let's see how many times it\n"
"will take you to guess!\n"
"-----------------------------".format(name, lower, upper))
# Main loop
guessing_numbers = True
while guessing_numbers:
guess = input("What is guess #{}?\n".format(tries))
while not guess.isdigit():
print("[!] Sorry, that isn't a valid input.\n"
"[!] Please only enter numbers.\n")
guess = input("What is guess #{}?\n".format(tries))
guess = int(guess)
tries += 1
if guess < secret:
print("Too low. Try again!")
elif guess > secret:
print("Too high. Try again!")
else:
guessing_numbers = False
if tries == 1:
guess_form = "guess"
else:
guess_form = "guesses"
print("--------------------------\n"
"Congratulations, {}!\n"
"You got it in {} {}!\n"
"--------------------------\n".format(name,tries,guess_form))
if tries < 3:
# Randomly chooses from an item in the list
tries_3 = ["Awesome job!","Bravo!","You rock!"]
print (random.choice(tries_3))
# ---
elif tries < 5:
tries_5 = ["Hmmmmmpff...","Better luck next time.","Ohhh c'mon! You can do better than that."]
print (random.choice(tries_5))
elif tries < 7:
tries_7 = ["You better find something else to do..","You can do better!","Maybe next time..."]
print (random.choice(tries_7))
else:
tries_8 = ["You should be embarrassed!","My dog could do better. Smh...","Even I can do better.."]
print (random.choice(tries_8))
choice = input("Would you like to play again? Y/N?\n")
if "y" in choice.lower():
return True
else:
return False
def main():
name = input("What is your name?\n")
playing = True
while playing:
playing = play_game(name)
if __name__ == "__main__":
main()
I have the number of "tries" set to 0 at the beginning. However, if I set that to 1 then play the game and it only takes me 3 tries it will display that it took me 4 tries. so I'm not sure what to do. Still somewhat new to python so I would love some help
Anywhere that you have input("What is guess #{}?\n".format(tries)), use guess = input("What is guess #{}?\n".format(tries+1)). (adding +1 to tries in the expression, but not changing the variable itself)
so im a python beginner and i cant find a way to put a input varible in a random like so,
import time
import random
choice = input('easy (max of 100 number), medium(max of 1000) or hard (max of 5000)? Or custom)')
time.sleep(2)
if choice == 'custom':
cus = input(' max number?')
print ('okey dokey!')
eh = 1
cuss = random.randrange(0, (cus))
easy = random.randint(0, 100)
medium = random.randint(0, 1000)
hard = random.randint (0, 5000)
if choice == 'easy' or 'medium' or 'hard' or cus:
while eh == 1:
esy = int(input('what do you think the number is?)'))
if esy > easy:
time.sleep(2)
print ('too high!')
elif esy == easy:
print (' CORRECT!')
break
elif esy < easy:
print ('TOO low')
is there any way i can put a number that someone typed in a random, like in line 9?
There are multiple things wrong with your code. You're using ('s with print, which suggests you're using python3. This means that when you do cus = input(), cus is now a string. You probably want to do cus = int(input())
Doing choice == 'easy' or 'medium' or 'hard' or cus will always be True; I have no idea why people keep doing this in Python, but you need to do choice == 'easy' or choice == 'medium' or choice == 'hard' or choice == 'cus'. Of course, a better way to do it is with a dictionary.
values = {'easy': 100, 'medium': 1000, 'hard': 5000}
And then do
value = values.get(choice)
if not value:
value = int(input("Please enter custom value"))
And then you can do
randomvalue = random.randint(1,value)
Convert your variable cus to an int and pass it as you normally would
cuss = random.randrange(0, int(cus))
My program is stuck while it tells you to think of a number in the range of selected numbers and I'm unsure how to fix this.
I'm not entirely sure what I'm doing even but the start of the program works properly.
from random import randrange
import time
def guessNumber(min_no, max_no):
try:
return randrange(min_no, max_no)
except ValueError:
return min_no
left = 0
right = len(L)-1
while left<=right:
m = (left+right)//2
if x == L[m]:
return m
elif x < L[m]:
right = m-1
else: # L[m] < x
left = m+1
def userNoInput(msg):
while 1:
try:
return int(input(msg))
except:
print("Numbers Only !")
sys.exit(0)
print("Enter two numbers, low then high.")
min_no = userNoInput("low = ")
max_no = userNoInput("high = ")
print ("Think of a number in the range %d and %d."%(min_no, max_no))
max_no += 1
while True:
guess = guessNumber(min_no, max_no)
count = 0
L = []
for i in range(low, high+1):
L.append(i)
while True:
print("Is your number Less than, Greater than, or Equal to %d ?") % (L[(int(len(L)/2))])
guess = guessNumber(low, high)
guess = input("Type 'L', 'G' or 'E': ")
guess = guess.upper()
if guess == 'E':
break
elif guess == 'L': guess < number
elif guess == 'G': guess > number
else:
print (guess)
print ("Your number is" + guess + "." + "I Found it in" + number + "guesses.")
desired output:
Enter two numbers, low then high.
low = 2
high = 18
Think of a number in the range 2 to 18.
Is your number Less than, Greater than, or Equal to 10?
Type 'L', 'G' or 'E': g
Is your number Less than, Greater than, or Equal to 14?
Type 'L', 'G' or 'E': L
Is your number Less than, Greater than, or Equal to 12?
Type 'L', 'G' or 'E': L
Your number is 11. I found it in 3 guesses.
Yep, the infinite loop in over first guessing caused program to hang.
There should be only one event loop, something like this:
from random import randrange
import time
def guess_number(min_no, max_no):
return randrange(min_no, max_no)
def user_num_input(msg):
try:
return int(raw_input(msg))
except ValueError:
print('Numbers Only!')
sys.exit(1)
def get_hint(current_guess):
return raw_input('Is your number Less than, Greater than, or Equal to %d? (L, G, E): ' % current_guess)
print('Enter two numbers, low then high.')
min_no = user_num_input('low = ')
max_no = user_num_input('high = ')
assert max_no >= min_no
print ('Think of a number in the range %d and %d.' % (min_no, max_no))
iteration = 1
while True:
guess = guess_number(min_no, max_no)
hint = get_hint(guess)
while hint not in ['E', 'L', 'G']:
print('You gave unknown answer. Please retry.')
hint = get_hint(guess)
if hint == 'E':
break
elif hint == 'L':
max_no = guess
elif hint == 'G':
min_no = guess
else:
raise ValueError('Unreachable!')
iteration += 1
print ('Your number is %d. I found it in %d guesses.' % (guess, iteration))
This code will do it for you . There were many mistakes in that code of yours :-
1.) Infinite While loop ( while True:
guess = guessNumber(min_no, max_no) ) .
2.) You dont need lists/arrays for this problem.
3.) while True:
guess = guessNumber(min_no, max_no) , this function is wrong . since you are returning the value ,it is not going past the except statement.
4.) No need of def userNoInput(msg): function , anyways no issues.
5.) The last line ( Print statement is wrong too )
Hoping this will help you
P.S:- Just a suggestion , whenever you get an infinite loop or some issues like that , you should firstly try yourself by printing statements inside loop and see where the issue is .
from random import randrange
import time
def guessNumber(min_no, max_no):
left = min_no
right = max_no
if left == right:
return left
m = (left+right)/2
return m
def userNoInput(msg):
while 1:
try:
return int(input(msg))
except:
print("Numbers Only !")
sys.exit(0)
print("Enter two numbers, low then high.")
min_no = userNoInput("low = ")
max_no = userNoInput("high = ")
# print min_no,max_no
print ("Think of a number in the range %d and %d."%(min_no, max_no))
max_no += 1
count = 0
while True:
count+=1
guess = guessNumber(min_no, max_no)
print("Is your number Less than, Greater than, or Equal to %d ?") %guess
temp = raw_input("Type 'L', 'G' or 'E': ")
temp = temp.upper()
if temp == 'E':
break
elif temp == 'L':
max_no = guess-1;
elif temp == 'G':
min_no = guess+1;
print "Your number is %r . I Found it in %r guesses." %(guess,count)
I am having trouble finding a way to get the user to repeat the code without having to exit out the shell. This is what I have so far.
import random
randomNum = random.randint(1, 10)
start = True
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#The code cant be both less than and greater than. The or function allows this
while (answer > randomNum) or (answer < randomNum):
if (answer == randomNum + 1):
print "Super Close"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#First one
elif (answer == randomNum + 2):
print "Pretty Close"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Second one
elif (answer == randomNum + 3):
print "Fairly Close"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Third one
elif (answer == randomNum + 4):
print "Not Really Close"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Fourth one
elif (answer == randomNum + 5):
print "Far"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Fifth one
elif (answer == randomNum - 5):
print "Far"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Sixth one
elif (answer == randomNum - 4):
print "Not Really Close"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Seventh one
elif (answer == randomNum - 3):
print "Fairly Close"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Eighth one
elif (answer == randomNum - 2):
print "Pretty Close"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Nineth one
elif (answer == randomNum - 1):
print "Super Close"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Tenth one
else:
print "Good Job!"
print randomNum
if (start == True):
answerAgain = raw_input("Do you want to restart this program ? ")
if answerAgain == ("Yes", "yes", "ya", "Ya", "Okay", "Sure", "Si", "Start"):
#Empty space because I don't know what to put in here.
else:
print "See ya next time!"
I would like to know how to get all of this code to apply to one variable or to repeat without me having to write it 50 times.
I recommend enclosing the whole thing in a while loop.
start = True
while start == True:
"""your code here"""
answerAgain = raw_input("Do you want to restart this program ? ")
if answerAgain == ("Yes", "yes", "ya", "Ya", "Okay", "Sure", "Si", "Start"):
start = True
else:
start = False
That way your entire code will run again if start == True.
I would also recommend that you use a list for your responses.
responses = ["Super Close", "Pretty Close", "Fairly Close", "Not Really Close", "Far"]
That way you can map to the appropriate response using the difference:
print responses[abs(answer - randomNum) - 1]
Put code in while loop to repeat it.
start = True
while start:
# code
if answerAgain.lower() in ('no', 'niet', 'bye'):
start = False
If you use the absolute value between the number the user provides and your random number, you only have to document half as many cases (i.e. -1 and +1 get treated the same).
Rather than asking for their new answer in after each case, move this code to the top of the main loop since it's requests at the start of the program and following all 'wrong' answers.
For usage, you'll probably want to convert all 'word' answers to lowercase, as case doesn't appear to matter in the case.
You can use quit() to cleanly exit the program.
So maybe like this:
import random
while(True):
randomNum = random.randint(1, 10)
answer = 0
while abs(answer - randomNum) > 0:
answer = int(input("Try to guess a random number between 1 and 10. "))
if abs(answer - randomNum) == 1:
print("Super Close")
elif abs(answer - randomNum) == 2:
print("Pretty Close")
# the other cases ...
# gets here if abs(answer - randonNum) == 0, i.e. they guessed right
print("Good Job!", randomNum)
answerAgain = input("Do you want to restart this program ? ")
if answerAgain.lower() in ["yes", "ya", "y", "okay", "sure", "si", "start"]:
pass
else:
print("See ya next time!")
quit()