I've been learning Python for about 4 days and I'm just dealing with my first problem.
import random
number=random.randint(1,10)
count=1
guess= int(input("Enter your guess between 1 and 10 : "))
while number != guess:
count = count + 1
if guess == number:
print("That is my number !")
while guess < number:
guess = int(input("Too low :( Guess again ! : "))
if guess == number:
print("That is my number !")
while guess > number:
guess = int(input("Too high :( Guess again ! : "))
if guess == number:
print("That is my number !")
My program just print only first input line and then nothing.
Enter your guess between 1 and 10 :
Why is that?
while number != guess:
count = count + 1
When I delete this two lines, it works perfectly.
In Python whitspace is significant, because the loop was not indented correctly, the your program did not work as expected. The corrected code looks like this:
import random
number = random.randint(1,10)
count = 1
guess = int(input("Enter your guess between 1 and 10 : "))
while number != guess:
count = count + 1
if guess == number:
print("That is my number !")
elif guess < number:
guess = int(input("Too low :( Guess again ! : "))
else:
guess = int(input("Too high :( Guess again ! : "))
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!")
I'm having an issue with my program. I'm working on a program that lets you play a small game of guessing the correct number. The problem is if you guess the correct number it will not print out: "You guessed it correctly". The program will not continue and will stay stuck on the correct number. This only happens if you have to guess multiple times. I've tried changing the else to a break command but it didn't work.
Is there anyone with a suggestion?
This is what I use to test it:
smallest number: 1
biggest number: 10
how many times can u guess: 10
If you try to guess the correct number two or three times (maybe more if u need more guesses) it will not print out you won.
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
guess = int(input("guess the number: "))
#while loop until the guess is the same as the random number
while guess != x:
#this is if u guessed to much u get the error that you've guessed to much
while count < amount:
if guess > x:
print("this is not the correct number, the correct number is lower \n")
guess = int(input("guess the number: "))
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
guess = int(input("guess the number: "))
count += 1
else: print("\n \nYou Lost, You've guessed", x, "times\n")
break
#this part is not working, only if you guess it at the first time. it should also print this if you guessed it in 3 times
else: print("You guessed it correctly", x)
test = (input("this is just a test if it continues out of the loop "))
print(test)
The main issue is that once guess == x and count < amount you have a while loop running that will never stop, since you don't take new inputs. At that point, you should break out of the loop, which will also conclude the outer loop
You can do it simply by using one while loop as follows:
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
#this is if u guessed too much u get the error that you've guessed too much
while count <= amount:
guess = int(input("guess the number: "))
if guess > x:
print("this is not the correct number, the correct number is lower \n")
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
count += 1
else:
print("You guessed it correctly", x)
break
if guess!=x:
print("\n \nYou Lost, You've guessed", count, "times\n")
As Lukas says, you've kind of created a situation where you get into a loop you can never escape because you don't ask again.
One common pattern you could try is to deliberately make a while loop that will run and run, until you explicitly break out of it (either because the player has guessed too many times, or because they guessed correctly). Also, you can get away with only asking for a guess in one part of your code, inside that while loop, rather than in a few places.
Here's my tweak to your code - one of lots of ways of doing what you want to:
import random
#counts the mistakes
count = 0
#asks to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#asks how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
#while loop until the guess is the same as the random number
while True:
if count < amount:
guess = int(input("guess the number: "))
#this is if u guessed to much u get the error that you've guessed to much
if guess > x:
print("this is not the correct number, the correct number is lower \n")
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
count += 1
else:
print("You guessed it correctly", x)
break
else:
print("\n \nYou Lost, You've guessed", x, "times\n")
PS: You got pretty close to making it work, so nice one for getting as far as you did!
This condition is never checked again when the guessed number is correct so the program hangs:
while guess != x:
How about you check for equality as the first condition and break out of the loop if true:
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
guess = int(input("guess the number: "))
if guess == x:
print("You guessed it correctly", x)
else:
while count < amount:
if guess > x:
print("this is not the correct number, the correct number is lower \n")
guess = int(input("guess the number: "))
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
guess = int(input("guess the number: "))
count += 1
else:
print("You guessed it correctly", x)
break
else:
print("You guessed too many times")
I'm learning how to program in Python and I found 2 tasks that should be pretty simple, but the second one is very hard for me.
Basically, I need to make a program where computer guesses my number. So I enter a number and then the computer tries to guess it. Everytime it picks a number I need to enter Lower or Higher. I don't know how to do this. Could anyone advise me on how to do it?
For example (number is 5):
computer asks 10?
I write Lower
computer asks 4?
I write Higher
Program:
I already made a program which automatically says Higher or Lower but I want to input Lower or Higher as a user.
from random import randit
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
guess = randint(min,max)
print(guess,"?")
if guess < number:
print("Higher")
min = guess
elif guess > number:
print("Lower")
max = guess
attemps += 1
print("I needed", attempts, "attemps")
You may want to put in a case for if it doesn't match you input, also I think you need a case for when the guess finally equals the number, you may want to allow an input for "Found it!" or something like that.
from random import randint
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
guess = randint(min,max)
print(guess,"?")
answer = str(input("Higher/Lower? "))
if answer == 'Higher':
min = guess
elif answer == 'Lower':
max = guess
attempts += 1
print("I needed", attempts, "attempts")
from random import randit
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
number = int(input("Number? "))
guess = randint(min,max)
print(guess,"?")
if guess < number:
print("Higher")
min = guess
elif guess > number:
print("Lower")
max = guess
attemps += 1
print("I needed", attempts, "attemps")
problem is your using a loop but inputting value once at start of app . just bring input inside the while statement hope this help
from random import randint
print('choos a number in your brain and if guess is true enter y else any key choose time of guess: ')
print("define the range (A,B) :")
A = int(input("A: "))
B = int(input("B: "))
time = int(input("time:"))
while time != 0:
ran = randint(A, B)
inp = input(f"is this {ran} ?")
time -= 1
if inp == "y":
print("bla bla bla computer wins!")
break
print("NOPE!")
if time == 0:
print("computer game over!")
break
from random import *
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
attemps =0
guess = randint(min,max)
while guess != number:
userInput=input(str(guess)+"?")
if userInput.lower()=="lower":
max=guess
elif userInput.lower()=="higher":
min=guess
attemps += 1
guess = randint(min,max)
print("I needed", attemps, "attempts to guess ur number ="+str(guess))
output:
Number? 5
66?lower
63?lower
24?lower
19?lower
18?lower
10?lower
4?higher
9?lower
6?lower
4?higher
I needed 10 attempts to guess ur number =5
The program is supposed to randomly generate a number between 1 and 10 (inclusive) and ask the user to guess the number. If they get it wrong, they can guess again until they get it right. If they guess right, the program is supposed to congratulate them.
This is what I have and it doesn't work. I enter a number between 1 and 10 and there is no congratulations. When I enter a negative number, nothing happens.
import random
number = random.randint(1,10)
print "The computer will generate a random number between 1 and 10. Try to guess the number!"
guess = int(raw_input("Guess a number: "))
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
guess = int(raw_input("Guess another number: "))
elif guess <= 0 and guess >= 11:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
elif guess == number:
print "Congratulations! You guessed correctly!"
Just move the congratulations message outside the loop. You can then also only have one guess input in the loop. The following should work:
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
else:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
print "Congratulations! You guessed correctly!"
The problem is that in a if/elif chain, it evaluates them from top to bottom.
Move the last condition up.
if guess == number:
..
elif other conditions.
Also you need to change your while loop to allow it to enter in the first time. eg.
while True:
guess = int(raw_input("Guess a number: "))
if guess == number:
..
then break whenever you have a condition to end the game.
The problem is that you exit the while loop if the condition of guessing correctly is true. The way I suggest to fix this is to move the congratulations to outside the while loop
import random
number = random.randint(1,10)
print "The computer will generate a random number between 1 and 10. Try to guess the number!"
guess = int(raw_input("Guess a number: "))
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
guess = int(raw_input("Guess another number: "))
elif guess <= 0 and guess >= 11:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
if guess == number:
print "Congratulations! You guessed correctly!"
I am struggling with some simple algorithm which should make python guess the given number in as few guesses as possible. It seems to be running but it is extremely slow. What am I doing wrong. I have read several topics already concerning this problem, but can't find a solution. I am a beginner programmer, so any tips are welcome.
min = 1
max = 50
number = int(input(("please choose a number between 1 and 50: ")))
total = 0
guessed = 0
while guessed != 1:
guess = int((min+max)/2)
total += 1
if guess == number:
print("The number has been found in ",total," guesses!")
guessed = 1
elif guess > number:
min = guess + 1
elif guess < number:
max = guess - 1
Thanks
ps. I am aware the program does not check for wrong input ;)
Your logic is backwards. You want to lower the max when you guess too high and raise the min when you guess too low. Try this:
if guess == number:
print("The number has been found in ",total," guesses!")
guessed = 1
elif guess > number:
max = guess - 1
elif guess < number:
min = guess + 1
Apart from having the logic backwards, you should not be using min and max as variable names. They are python functions. You can also use while True and break as soon as the number is guessed.
while True:
guess = (mn + mx) // 2
total += 1
if guess == number:
print("The number has been found in {} guesses!".format(total))
break
elif guess < number:
mn = guess
elif guess > number:
mx = guess
You will also see by not adding or subtracting 1 from guess this will find the number in less steps.
from random import randint
print('choose a number in your brain and if guess is true enter y else any key choose time of guess: ')
print("define the range (A,B) :")
A = int(input("A: "))
B = int(input("B: "))
time = int(input("time:"))
while time != 0:
ran = randint(A, B)
inp = input(f"is this {ran} ?")
time -= 1
if inp == "y":
print("bla bla bla python wins!")
break
print("NOPE!")
if time == 0:
print("computer game over!")
break