Is there a way to fix the obtaining negative numbers in the code below?
import random
number = random.randrange(1, 100)
guess = int(input("I’m thinking of a number between 1 and 100 " + "Can you guess it? "))
number1 = number - guess
number2 = (number) - guess
if guess>number:
print ("You were " + str(number1)+ " away! ")
else:
if guess<number:
print ("You were " + str(number2)+ " away! ")
else:
if guess == number:
print ("You got it right ")
the whole code should be simplified to:
import random
number = random.randint(1, 100)
guess = int(input("Im thinking of a number between 1 and 100 Can you guess it? "))
if guess!=number:
print ("You were",abs(guess-number),"away! ")
else:
print ("You got it right ")
Or just:
print(["You were "+str(abs(guess-number))+" away! ","You got it right "][number==guess])
Whole code:
import random
number = random.randint(1, 100)
guess = int(input("Im thinking of a number between 1 and 100 Can you guess it? "))
print(("You were "+str(abs(guess-number))+" away! ","You got it right ")[number==guess])
abs() will return the absolute value of the difference.
abs(number - guess)
Related
I created a while loop so I would keep on asking the user questions until they got the number right. But when a do a random number, for example, it either prints "Pick a higher number" or "pick a lower number" infinitely. Can someone help me out here.
from random import randint
answer = randint(1, 100)
print("Guess a number between 1 and 3.")
guess = int(input())
count = 0
while guess != answer:
if guess < answer:
print("Pick a higher number.")
count += 1
elif guess > answer:
print("Pick a lower number.")
count += 1
elif guess == answer:
print("You got it!")
print("It took you " + str(count) + " tries.")
Try this.
while True:
guess = int(input("Guess a number between 1 and 3."))
if guess < answer:
print("Pick a higher number.")
count += 1
elif guess > answer:
print("Pick a lower number.")
count += 1
elif guess == answer:
print("You got it!")
break
Let me phrase it this way: When do you obtain the input from the user? What happens on a second loop run? Is guess at any time updated?
The answers to these (suggestive) questions will lead you to the right path:
You have to request input from the user in every loop run.
This will lead you to the point about how to start the loop.
from random import randint
answer = randint(1, 100)
count = 0
keep_loop = True
prompt = "Guess a number between 1 and 3."
while keep_loop:
print(prompt)
guess = int(input())
if guess < answer:
prompt = "Pick a higher number."
count += 1
elif guess > answer:
prompt = "Pick a lower number."
count += 1
elif guess == answer:
print("You got it!")
keep_loop = False
print("It took you " + str(count) + " tries.")
#Write a short program that will do the following
#Set a value your favorite number between 0 and 100
#Ask the user to guess your favorite number between 0 and 100
#Repeat until they guess that number and tell them how many tries it took
#If the value they guessed is not between 0 and 100
#tell the user invalid guess and do not count that as an attempt
My problem is that even if the user guesses a number between 0 and 100, it still prints out the "Invalid guess. Try again". How do I control my loop to skip past the print statement and question repeat if it's acceptable input(1-100)? Thanks in advance!
favoriteNumber = 7
attempts = 0
guess = raw_input("Guess a number between 0 and 100: ")
if (guess < 0) or (guess > 100):
print "Invalid guess. Try again"
guess = raw_input("Guess a number between 0 and 100: ")
attempts1 = str(attempts)
print "it took " + attempts1 + "attempts."
Use input and not raw_input,so you get integer and not string
favoriteNumber = 7
attempts = 0
while True:
guess = input("Guess a number between 0 and 100: ")
if (guess < 0) or (guess > 100):
attempts=attempts+1
print "Invalid guess. Try again"
else:
attempts=attempts+1
break
attempts1 = str(attempts)
print "it took " + attempts1 + " attempts."
In Python 2.7.10 it appears that if you do not convert a string to an integer, it accepts it but all rules that apply to numbers return false.
Here is a working example:
favoriteNumber = 7
attempts = 0
guess = raw_input("Guess a number between 0 and 100: ")
if (int(guess) < 0) or (int(guess) > 100):
print "Invalid guess. Try again"
guess = raw_input("Guess a number between 0 and 100: ")
attempts1 = str(attempts)
print "it took " + attempts1 + " attempts."
In Python 3.4 the original code yields an error where it tells you that it is a string instead of an integer. But, like Paul said you could put raw_input inside of an int() command.
you raw_input returns a string, which is always > 100. Cast it to a number with int(raw_input())
I want to have a user try a guessing game. The program should loop until the user guesses right.
How can I compare the values? Right now its going through the else part every time, even when the user guesses right.
Here is the code;
import sys
from random import randint
secret_number = randint(0, 100)
num_guesses = 0
guess = 0
while guess != secret_number:
guess = raw_input("Enter a number: ")
if (guess < secret_number):
print "Your guess is too low. Please try again."
else:
print "Your guess is too high. Please try again."
num_guesses = num_guesses + 1
print "Thank you, you guessed right"
print guess
You need to convert the string that raw_input returns into an integer using int, so the comparison operator works the way you expect it to:
guess = int(raw_input("Enter a number: "))
raw_input will return string, you compare string with int and nothing works
also you will never guess the number:
your code hav 2 options: too low or too high
also you never compare tries with max tries (try to fix that by yourself)
corrected version:
import sys
from random import randint
secret_number = randint(0, 100)
num_guesses = 0
guess = 0
while guess != secret_number:
guess = raw_input("Enter a number: ")
if (int(guess) < secret_number):
print "Your guess is too low. Please try again."
elif (int(guess) > secret_number) :
print "Your guess is too high. Please try again."
else:
print "Thank you, you guessed right"
break
num_guesses = num_guesses + 1
print guess
I have a question about How to delete a space in my guessing game.
Here is my source code:
import random
print ("I’m thinking of an integer, you have three guesses.")
def tovi_is_awesome():
random_integer = random.randint (1, 10)
chances = 3
for i in [1,2,3]:
print ("Guess", i, ": ", end=" ")
guess = eval(input("Please enter an integer between 1 and 10: "))
if guess < random_integer:
print ("Your guess is too small.")
elif guess > random_integer:
print ("Your guess is too big.")
else:
print ("You got it!")
break
if guess != random_integer:
print ("Too bad. The number is: ", random_integer)
tovi_is_awesome ()
When I run it, I got this:
I’m thinking of an integer, you have three guesses.
Guess 1 : Please enter an integer between 1 and 10:
How can I delete that space after "Guess 1"?
Or are there any better ways to avoid that space?
Thank you!
This is my first question in SOF lol
print ("Guess", i, ": ", end=" ")
You could write it like;
print ("Guess {}: ".format(i), end=" ")
So you can avoid from that space. You could check this one for examples.
Here is a simple guess game, check it carefully please. It may improve your game. You dont' have to use eval().
random_integer = random.randint (1, 10)
chances = 3
gs=1
while 0<chances:
print ("Guess {}".format(gs))
guess = int(input("Please enter an integer between 1 and 10: "))
if guess<random_integer:
print ("Your guess is too small.")
chances -= 1 #lost 1 chance
gs += 1 #increase guess number
elif guess > random_integer:
print ("Your guess is too big.")
chances -= 1
gs +=1
else:
print ("You got it!")
break
It's really simple, just showing you some basic logic. You may consider in the future catching errors with try/except etc.
print ("Guess %d:" % (i) )
Writing this way will delete the space.
I am making a random number guessing game and I was wondering if when your guess is 3 less than or more than the answer it would print something like "Close! The answer was (the answer)"
import random
while True:
dicesize = raw_input('What size die do you want to guess from?>')
number = random.randrange(1, int(dicesize))
guess = raw_input('What is your guess?>')
if int(guess) == number:
print 'Correct!'
print " "
# less than 3 print "close"?
# more than 3 print "close"?
else:
print 'Nope! The answer was', number
print " "
(I have the print " " to make a space between each of the loops)
while True:
dicesize = raw_input('What size die do you want to guess from?>')
number = random.randrange(1, int(dicesize))
guess = int(raw_input('What is your guess?>'))
if guess == number:
print('Correct!')
print(" ")
elif abs(number-guess) < 3:
print("Close")
else:
print('Nope! The answer was', number)
Just get the absolute value abs(number-guess), which will cover both cases, if the guess is less than 3 above or below the number.
In [1]: abs(10-7)
Out[1]: 3
In [2]: abs(7-10)
Out[2]: 3
More simply, use chained conditionals
if number-3 < guess < number+3:
print("Close")