This is my code:
import random
Random = random.randint(1, 10)
print("Number:" + str(Random))
Number = int(input("Guess the number I am thinking of from 1-10"))
while int(Random) != Number:
if(Random > Number):
Number = input("Too low. Guess again!")
elif(Number > Random):
Number = input("Too high. Guess again!")
print("You guessed it!")
When the correct number is guessed, this happens, which is what is supposed to happen.
Number:8
Guess the number I am thinking of from 1-10 8
You guessed it!
But, when the number isn't guessed correctly, it loops though the elif statement only.
Number:10
Guess the number I am thinking of from 1-10 6
Too low. Guess again! 7
Too high. Guess again! 6
Too high. Guess again! 5
Too high. Guess again! 4
Too high. Guess again! 3
Too high. Guess again! 2
Too high. Guess again! 1
Too high. Guess again! 10
Too high. Guess again! 9
Too high. Guess again! 8
Have you tried casting int onto the input within both input lines in the while loop? It seems to work for me when it's like:
if(Random > Number):
Number = int(input("Too low. Guess again!"))
elif(Number > Random):
Number = int(input("Too high. Guess again!"))
import random
number=random.randint(1,10)
guess=int(input("Guess the number I am thinking of from 1-10")
while guess !=number:
if guess < number:
print("Your answer was too low...")
else:
print("Your number was too high...")
guess= int(input("Please try again...")
print("Congratulations! Correct answer!")
you can use this as your reference. thank you...
This is an improved version of your code:
import random
answer = random.randint(1, 10)
print("Number:" + str(answer))
guess = int(input("Guess the number I am thinking of from 1-10"))
while answer != guess:
if guess < answer:
guess = int(input("Too low. Guess again!"))
elif guess > answer:
guess = int(input("Too high. Guess again!"))
print("You guessed it!")
Some remarks on the changes:
The main thing is the int() around the input(). input() gets you a value as a string, but you want to compare the values of the numbers, not the strings. For example '12' < '2' but 12 > 2.
Your variables' names had capital letters in them, that's a bad idea in Python, since that signals to editors and other programmers that they're classes instead of variables.
Your variable Random had the same name as the module you're using, making it easy to get confused, answer seemed like a better choice.
Your code was indented with 2 spaces, but most editors default to 4 and that's also inline with standard Python style guidelines.
Instead of flipping the order of variables, it's often best to make your code read as close as possible to what it means; for example, if guess < answer is exactly what you're saying: "too low".
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed last month.
For right now, I have it so it will print the random number it chose. However, whether I get it wrong or right it always says I am wrong.
here is my code:
import random
amount_right = 0
number = random.randint(1, 2)
guess = input
print(number)
print(
"welcome to this number guessing game!! I am going to think of a number from 1-10 and you have to guess it! Good luck!")
input("enter your guess here! ")
if guess != number:
print("Not quite!")
amount_right -= 1
print("you have a score of ", amount_right)
else:
print("good Job!!")
amount_right += 1
print("you have a score of ",amount_right,"!")
what did I do wrong? I am using Pycharm if that helps with anything.
I tried checking my indentation, I tried switching which lines were the if and else statements (lines 13 - 21) and, I tried changing lines 18 - 21 to elif: statements
guess = int(input())
You need to convert your guess to int and there should be () in input
Also there are 2 input() in your code. One is unnecessary. This can be the code.
import random
amount_right = 0
number = random.randint(1, 2)
print(number)
print(
"welcome to this number guessing game!! I am going to think of a number from 1-10 and you have to guess it! Good luck!")
guess = int(input("enter your guess here! "))
if guess != number:
print("Not quite!")
amount_right -= 1
print("you have a score of ", amount_right)
else:
print("good Job!!")
amount_right += 1
print("you have a score of ",amount_right,"!")
So I had to make a guessing game where we have someone enter a number, then someone else has to guess that number until they get it right. We also have to state how many tries it took. This is my code so far, but I got stuck in a while loop and I'm not sure how to get out. Any help is appreciated. We also aren't allowed to use return, so I'm stuck. Should
I maybe use a for loop instead?
initial = int(input("Enter the integer for the player to guess. "))
guess = int(input("Enter your guess. "))
tries = 0
while initial != guess:
tries = tries + 1
if initial < guess:
print("Too high - try again: ")
elif initial > guess:
print("Too low - try again: ")
print("You guessed it in", tries,".")
Your issue is that you're not taking input within the body of the loop, so the input doesn't actually change. The fix for this is really simple:
initial = int(input("Enter the integer for the player to guess. "))
guess = int(input("Enter your guess. "))
tries = 0
while initial != guess:
tries = tries + 1
if initial < guess:
guess = int(input("Too high - try again: ")
else:
guess = int(input("Too low - try again: ")
print("You guessed it in", tries,".")
All I did here was replace your calls to print with input and conversion code. I also replaced the elif with else because your while loop already checks that the values aren't equal and the if checks if the initial value is less than the guess so the only possibility left is that the initial value is greater than the guess.
By the way, you should probably be doing input validation as there's nothing stopping the user from entering something which wouldn't convert to an integer.
I need help with an assignment I have for Intro to Python.
The assignment is to have the computer pick a random number between 1 and 100 and the user has to guess the number. If your guess is too high then you will be told. If your guess was too low then you will be told. It will continue repeating until you guess the correct number that was generated.
My issue is that if an input is a string then you would get a prompt saying that it is not a possible answer. How do I fix this issue?
P.S. If it would not be too much trouble, I would like to get tips on how to fix my code and not an answer.
Code:
import random
#answer= a
a= random.randint(1,100)
#x= original variable of a
x= a
correct= False
print("I'm thinking of anumber between 1 and 100, try to guess it.")
#guess= g
while not correct:
g= input("Please enter a number between 1 and 100: ", )
if g == "x":
print("Sorry, but \"" + g + "\" is not a number between 1 and 100.")
elif int(g) < x:
print("your guess was too low, try again.")
elif int(g) > x:
print("your guess was too high, try again.")
else:
print("Congratulations, you guessed the number!")
So if you want to sanitize the input to make sure only numbers are being inputted you can use the isdigit() method to check for that. For example:
g=input("blah blah blah input here: ")
if g.isdigit():
# now you can do your too high too low conditionals
else:
print("Your input was not a number!")
You can learn more in this StackOverflow thread.
I have a quick question.
I want to make my number guessing game tell the user if they are 2 numbers away from guessing the random number.
I do not want the program to say how many numbers away the user is.
The way I'm thinking is this. I just can't put this into proper code.
Random_number = 5
guess = 3
print('you are close to guessing the number!')
guess = 7
print('you are close to guessing the number!')
guess = 2 #more than 2 away from the number
print('you are NOT close to guessing the number')
I am going to start by saying my python is rusty and someone please fix it if im off alittle.
All you need to do if use an if statement.
random = 5
guess = 3
if( guess == random ):
print('your right!')
elif ( abs (guess - random) <= 2 ):
print('you are close to guessing the number!')
else:
print('you are not close enough!')
Edited the elseif logic according to #9000's suggestion.
Try this:
for number in range (2):
if guess == Random_number:
print('you guessed the number!')
if guess - number == Random_number or guess + number == Random_number:
print('you are close to guessing the number!)
Here is the explanation. The first line is saying "for the numbers in the range of 0 to 2 set number equal to that number." So the next if part will run 3 times: for number equaling 0, 1, and 2. So, if your guess is within 2 of the random number, it will print you are close to the random number. If you have the correct guess, it will obviously print you guessed it correctly.
I've written a game where a player tries to guess a random number (see code below). Suggestions such as 'Too low...' and 'Too High...' are also provided. But what about reversing it and letting the computer guess a number that a player has selected. I have difficulty with this and I dont know why. I think I need a 'push' from someone but not the actual code as I need to attempt this myself. I would appreciate it if some would help me on this.
Here is the code(Python 3) where the player has to guess the number:
#Guess my Number - Exercise 3
#Limited to 5 guesses
import random
attempts = 1
secret_number = random.randint(1,100)
isCorrect = False
guess = int(input("Take a guess: "))
while secret_number != guess and attempts < 6:
if guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
guess = int(input("Take a guess: "))
attempts += 1
if attempts == 6:
print("\nSorry you reached the maximum number of tries")
print("The secret number was ",secret_number)
else:
print("\nYou guessed it! The number was " ,secret_number)
print("You guessed it in ", attempts,"attempts")
input("\n\n Press the enter key to exit")
Thanks for your help.
at each iteration through your loop, you'll need a new random.randint(low,high). low and high can be figured out by collecting your computers guesses into 2 lists (low_list) and (high_list) based how the user responds when the computer tells the user it's guess. Then you get low by max(low_list)+1 and you get high by min(high_list)-1. Of course, you'll have to initialize low_list and high_list with the lowest and highest numbers allowed.
You could just keep the lowest of the "too high" guesses and the highest of the "too_low" guesses instead of the lists. It would be slightly more efficient and probably the same amount of work to code, but then you couldn't look back at the computer's guesses for fun :).
You begin with a range from the minimum allowed number to the maximum allowed number, because the unknown number could be anywhere in the range.
At each step, you need to choose a number to query, so dividing the space into two blocks; those on the wrong side of your query number will be dropped. The most efficient way to do this in the minimum number of queries is to bisect the space each time.
I suggest you restrict the game to integers, otherwise you'll end up with a lot of messing about with floating point values regarding tolerance and precision and so on.
Assuming you know the range of numbers it could be is (a,b).
Think about how you would narrow down the range. You'd start by guessing in the middle. If your guess was low, you'd guess between your last guess and the top value. If it was high you'd guess between the lowest possible value and the last guess. By iteratively narrowing the range, eventually you'd find the number.
Here's some pseudo code for this:
loop{
guess = (a+b)/2
if high:
b = guess - 1
else if low:
a = guess + 1
else:
guess = answer
}
I just did this with a different person, use a while loop and use print("<,>,="), then do an if statement. You need a max point, middlepoint and low point and to get the middle point you need to do midpoint=((highpoint=lowpoint)//2) and in the if statement you have to do change the maxpoint and lowpoint.