Before writing this question, I looked for something similar in the forum, but did not find any. So here is my version of the guessing game. I want the user to guess a number from 0 to 10 that the computer has "thought". But I want to calculate the difference of the numbers and show whether the user is close or not to figuring out the correct number.
My code is as follows:
import math
import random
intnum = random.randrange(0,11)
print(intnum)
print ("The computer generated a random number from 0 to 10! Can you guess it?")
guess = 0
while guess != intnum:
guess = int(input ("Pick a number!!: "))
num = abs(guess-intnum)
print (num)
if (num==0):
print ("Congrats! The answer is %s" % (guess))
break
elif (num>0 or num<=2):
print ("You are less than 2 away. Keep going!")
elif (num>2 or num<=5):
print ("You are more than 2 away. Try again!")
elif (num>5):
print ("You are more than 5 away!! Try again.")
I print the computers number and the difference, to find my bugs easily. There is a logical error that I cannot solve. If the computer generates a number 9, and I guess a number 1, the difference is 9-1=8. But the program, prints "You are less than 2 away", which is incorrect. What am I doing wrong? I would like to use this in a larger version with more numbers but for starters I scaled it down a bit to find the correct logic and syntax.
This block needs rewriting from
if (num==0):
print ("Congrats! The answer is %s" % (guess))
break
elif (num>0 or num<=2):
print ("You are less than 2 away. Keep going!")
elif (num>2 or num<=5):
print ("You are more than 2 away. Try again!")
elif (num>5):
print ("You are more than 5 away!! Try again.")
to
if (num==0):
print ("Congrats! The answer is %s" % (guess))
break
elif (num>0 and num<=2):
print ("You are less than 2 away. Keep going!")
elif (num>2 and num<=5):
print ("You are more than 2 away. Try again!")
elif (num>5):
print ("You are more than 5 away!! Try again.")
I understand what you're trying to do with the "or"s in your initial code block, but the computer will think differently, and in this case, "and" is your friend.
The right statement is:
elif (num<=2):
print ("You are less than 2 away. Keep going!")
The condition you are using does not do what you want.
You need to check if a number lies in an interval. To do so, you need to ensure that the number is greater that the lower bound and lower than the upper bound
You need to change the or to and in your conditions
Related
So I'm new to this programming thing... But this has me stumped. To the point that I'm wondering if the website I'm running Python on is wrong. (repl.it is the website).
So I did one of those guess the number games as a small fun challenge. This is the code that I came up with:
from random import randint
print ("Welcome to guess the number!")
answer = str(randint(0,100))
print (answer)
print ()
def something():
answerTwo = str(randint(0,100))
print (answerTwo)
idea(answerTwo)
def idea(x):
number = str(input("Guess a number between 0 and 100:"))
if number != x:
if (number > x):
print()
print(number + " is too high!")
print()
idea(x)
elif (number < x):
print()
print(number + " is too low!")
print()
idea(x)
else:
print()
print ("That is correct!")
again = input("Would you like to play again?:")
if again == "yes":
something()
else:
print ("Thanks for playing!")
idea(answer)
On the 4th and 8th line I print out the random number chosen so that I can quickly test to make sure everything works. Then I removed the print functions in the final product and tested again. Except when I removed the print functions it stopped working after some amount of time. For example, it'll say 39 is too low but 40 is too high, which is impossible since they're is no number in between them. If you put the print functions back in it works again, but remove them and it'll start acting up eventually.
I apologize if it's something really obvious but I just don't understand how this is possible.
Here is the github thingy for it
https://gist.github.com/anonymous/4a370664ae8ddb29aec5915eb20e686f
Thanks for your time!
There is no integer i such that 39 < i < 40.
There is however a numeric string s such that "39" < s < "40". Observe:
>>> "39" < "4" < "40"
True
In short: It has nothing to do with your print calls, instead, just work on actual numbers and cast your input to a number using int(). print() can handle numbers just fine.
This is my code:
from sys import exit
import random
number = random.randint(1, 10)
count = 0
def guess():
print ("Input a number 1 - 10")
guess = input()
if guess == "I give up":
print ("The correct number was", number,"!")
print ("You tried", count, "times before giving up!")
exit(0)
else:
if guess == (number):
print ("CORRECT!")
print (count, "failed attempts.")
exit(0)
else:
print ("WRONG!")
print ("Try again!")
global count
count += 1
while True:
guess()
If I run this, I can keep guessing but never get the correct number. I said I gave up, and it gave me the correct number. But I already guessed that number, so I don't know what's the problem.
You are taking the input as a string rather than an integer. Thus, you may be comparing "5" to 5, which is false. Instead, call if int(guess) == (number)
I created a guess the number program and used a while loop to allow the user to continue guessing until he/she could get it right, as seen here:
import random
number = random.randrange(1, 6)
print "Guess the number, between 1 and 6"
guess = "yes"
while guess != number:
guess = int(raw_input('>'))
if guess == number:
break
print "Good job! You got it right!"
print number
elif guess > number:
print "Too High"
print number
number = random.randrange(1, 6)
elif guess < number:
print "Too Low"
print number
number = random.randrange(1, 6)
The problem is, when I am trying to guess the number, it will randomly end, whether me guessing the first time, 4 times, or 30 times. Also, I originally had,
guess = int(raw_input('>'))
in place of,
guess = "yes"
and replaced it to get rid of the extra and useless raw_input i'd initially need to add into terminal. Why am i able to make it equal "yes" and why doesn't it matter what I put there?
Example of Bug:
Guess the number, between 1 and 6
>3
Too High
2
>4
Too Low
5
>6
Too High
5
>3
Too High
1
>2
Too High
1
>5
Good job! You got it right!
5
------------------
(program exited with code: 0)
Press return to continue
It worked that time, and now:
Guess the number, between 1 and 6
>3
Too Low
4
------------------
(program exited with code: 0)
Press return to continue
The issue you have is that your while loop is testing if number matched guess after picking a new number value but before getting a new guess. This means that you'll say the player guessed wrong, but they they become right afterwards and the loop will end.
Try this instead:
import random
print "Guess the number, between 1 and 6"
guess = 'y' # the values set here don't actually matter, they just need to be different
number = 'x'
while guess != number:
number = random.randint(1, 6)
guess = int(raw_input('>'))
if guess == number:
print "Good job! You got it right!"
elif guess > number:
print "Too High"
print number
elif guess < number:
print "Too Low"
print number
I've also changed your use of random.randrange to random.randint, which will make it actually return 6s some of the time (randrange excludes the upper bound).
guess = "yes" works because guess != number will always be True on the first check in the while loop, at which point the user is asked for input. Also, in the if block, put the break statement after all the print's.
import random
number = random.randrange(1, 6)
print "Guess the number, between 1 and 6"
guess = "yes"
while guess != number:
guess = int(raw_input('>'))
if guess == number:
break
print "Good job! You got it right!"
print number
break
elif guess > number:
print "Too High"
print number
number = random.randrange(1, 6)
break
elif guess < number:
print "Too Low"
print number
number = random.randrange(1, 6)
break
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 am learning Python on Codecademy, and I am supposed to give the user 3 guesses before showing "you lose". I think my code allows 3 entries, but the website shows "Oops, try again! Did you allow the user 3 guesses, or did you incorrectly detect a correct guess?" unless the user guesses correctly within 3 trials. Can someone tell me what's wrong?
from random import randrange
random_number = randrange(1, 10)
count = 0
# Start your game!
guess= int(raw_input("Please type your number here:"))
while count < 2:
if guess==random_number:
print "You win!"
break
else:
guess=int(raw_input("Please guess again:"))
count+=1
else:
print "You lose!"
print random_number
Your loop will indeed ask the user for three guesses. (As can be trivially seen by running the code—ignore those other answers telling you to change the loop condition, that's the wrong solution.)
The problem with your loop is a more subtle one: because of the way it's structured, the third guess is never tested! You can see this by setting random_number to a constant and guessing wrong twice, then right on the last try; you still lose.
Your best bet is to use a more straightforward loop structure, where the asking and the checking happens in the same iteration of the loop.
for attempt in xrange(3):
guess = int(raw_input("Please enter a number: "))
if guess == random_number:
print "You win!"
break
print "Wrong! Try again."
else:
print "You lose! The number was", random_number
If you want a different prompt on the second and subsequent guesses, try this:
prompt = "Please enter a number"
for attempt in xrange(3):
guess = int(raw_input(prompt + ": "))
if guess == random_number:
print "You win!"
break
prompt = "Wrong! Try again"
else:
print "You lose! The number was", random_number
You need while count <= 2. Your count starts at 0. Then it goes through the body of your loop once. Then it gets incremented to 1. Then it goes through your loop body another time. Finally, once it increments to 2, your while condition evaluates to false, and the loop body doesn't execute a third time.
Be careful with corner cases when you're setting up conditions. :)
The condition should be:
while count < 3:
To make it easier to understand, I suggest you start the counter in count = 1 and write the condition like this:
while count <= 3:
Now it's more clear that exactly 3 repetitions are allowed. But let's see why your code was wrong:
count starts at 0, and it's true that 0 < 2, so we enter the loop
At the first failed attempt, count gets incremented to 1, and it's true that 1 < 2 so we enter the loop once more
At the second failed attempt, count gets incremented to 2, and it's no longer true that 2 < 2 so we exit the loop
So you see, only two attempts were being considered.