Python string formatting issue - python

import random
def main():
the_number = random.randint(1,100)
guess = 0
no_of_tries = 0
while guess != the_number:
no_of_tries += 1
guess = int(input("Enter your guess: "))
if guess < the_number:
print "--------------------------------------"
print "Guess higher!", "You guessed:", guess
if guess == the_number - 1:
print "You're so close!"
if guess > the_number:
print "--------------------------------------"
print "Guess lower!", "You guessed:", guess
if guess == the_number + 1:
print "You're so close!"
if guess == the_number:
print "--------------------------------------"
print "You guessed correctly! The number was:", the_number
print "And it only took you", no_of_tries, "tries!"
if __name__ == '__main__':
main()
Right now, in my random number guessing game, if a person guesses lower or higher by one number, they receive the following message:
Guess lower! You guessed: 33
You're so close!
But I want to make it one sentence.
For example:
Guess lower! You guessed: 33. You're so close!
How would I implement this in my code? Thanks!

Simply put a comma (',') after your print statement if you want to avoid it advancing to the next line. For example:
print "Guess lower!", "You guessed:", guess,
^
|
The next print statement will add its output at the end of this line i.e., it will not move down to the start of the next line as you currently have.
Update re comment below:
To avoid the space due to the comma, you can use the print function. I.e.,
from __future__ import print_function # this needs to go on the first line
guess = 33
print("Guess lower!", "You guessed:", guess, ".", sep="", end="")
print(" You're so close!")
This will print
Guess lower!You guessed:33. You're so close!
This PEP also talks about the print function

Related

Guess My number game with limited number of guesses

I'm new to python and I'm trying to make the guess my number game with a limit of only 5 guesses, everything I've tried so far has failed. how can I do it?, I forgot to mention that I wanted the program to display a message when the player uses all their guesses.The code below only prints the "You guessed it" part after the 5 guesses whether they guess it or not.
import random
print ("welcome to the guess my number hardcore edition ")
print ("In this program you only get 5 guesses\n")
print ("good luck")
the_number = random.randint(1, 100)
user = int(input("What's the number?"))
count = 1
while user != the_number:
if user > the_number:
print ("Lower")
elif user < the_number:
print ("Higher")
user = int(input("What's the number?"))
count += 1
if count == 5:
break
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
input ("\nPress enter to exit")
Your edit says you want to differentiate between whether the loop ended because the user guessed right, or because they ran out of guesses. This amounts to detecting whether you exited the while loop because its condition tested false (they guessed the number), or because you hit a break (which you do if they run out of guesses). You can do that using the else: clause on a loop, which triggers after the loop ends if and only if you didn't hit a break. You can print something only in the case you do break by putting the print logic right before the break, in the same conditional. That gives you this:
while user != the_number:
...
if count == 5:
print("You ran out of guesses")
break
else:
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
However, this puts code for different things all over the place. It would be better to group the logic for "guessed right" with the logic for warmer/colder, rather than interleaving them with part of the logic for how many guesses. You can do this by swapping where you test for things - put the 'is it right' logic in the same if as the warmer/colder, and put the number of guesses logic in the loop condition (which is then better expressed as a for loop). So you have:
for count in range(5):
user = int(input("What's the number?"))
if user > the_number:
print("Lower")
elif user < the_number:
print("Higher")
else:
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
break
else:
print("You ran out of guesses")
You have two options: you can either break out of the loop once the counter reaches a certain amount or use or a for loop. The first option is simplest given your code:
count = 0
while user != the_number:
if user > the_number:
print ("Lower")
elif user < the_number:
print ("Higher")
user = int(input("What's the number?"))
count += 1
if count == 5: # change this number to change the number of guesses
break # exit this loop when the above condition is met

Code for a random secret number

The code allows me more than six times for input and also it did not print the else statement. My code is:
import random
secret = random.randint(1, 99)
guess = 0
tries = 0
print ('AHOY! I am the Dread Prites Roberts , and i have a secret!')
print ('It is a number from 1 to 99. I\'ll give you 6 tries ')
while guess != secret and tries < 6:
guess = int(input('What is your guess? '))
if guess < secret:
print ('Too Low, you scurvy dog!')
elif guess > secret:
print ('Too high, boy')
tries = tries + 1
elif guess == secret:
print ('Avast! you got it ! Found my seceret , you did!')
else:
print ('No more guess! Better Luck next time')
print ('The secret number was',secret)
I tried the code in Python 3.4. It prints the result more than six times. While guess is not equal to secret and tries... after 6 tries it will print 'No more guess better luck next time' but is executing again and again
your have an indentation problem (i guess happened by pasting) but your main problem is, that you are only incrementing tries when the guess was too high. Also you should move the last if else out of the while block, since the while condition is already taking care of vars.
Your implementation should look like this:
import random
secret = random.randint(1, 99)
guess = 0
tries = 0
print ('AHOY! I am the Dread Prites Roberts , and i have a secret!')
print ('It is a number from 1 to 99. I\'ll give you 6 tries ')
while guess != secret and tries < 6:
guess = int(input('What is your guess? '))
tries = tries + 1
if guess < secret:
print ('Too Low, you scurvy dog!')
elif guess > secret:
print ('Too high, boy')
if guess == secret:
print ('Avast! you got it ! Found my seceret , you did!')
else:
print ('No more guess! Better Luck next time')
print ('The secret number was',secret)

Loop until entry matches a predetermined value

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

How to delete space in Python?

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.

Guessing game in python

I have only just started to learn to program following http://learnpythonthehardway.org.
After learning about loops and if-statements I wanted to try to make a simple guessing game.
The problem is:
If you make an incorrect guess it gets stuck and just keeps repeating either "TOO HIGH" or "TOO LOW" until you hit crtl C.
I have read about while loops and have read other peoples code but I simply dont want to just copy the code.
print ''' This is the guessing game!
A random number will be selected from 1 to 10.
It is your objective to guess the number!'''
import random
random_number = random.randrange(1, 10)
guess = input("What could it be? > ")
correct = False
while not correct:
if guess == random_number:
print "CONGRATS YOU GOT IT"
correct = True
elif guess > random_number:
print "TOO HIGH"
elif guess < random_number:
print "TOO LOW"
else:
print "Try something else"
You have to ask the user again.
Add this line at the end (indented by four spaces to keep it within the while block):
guess = input("What could it be? > ")
This is just a quick hack. I would otherwise follow the improvement proposed by #furins.
Moving the request inside the while loop does the trick :)
print ''' This is the guessing game!
A random number will be selected from 1 to 10.
It is your objective to guess the number!'''
import random
random_number = random.randrange(1, 10)
correct = False
while not correct:
guess = input("What could it be? > ") # ask as long as answer is not correct
if guess == random_number:
print "CONGRATS YOU GOT IT"
correct = True
elif guess > random_number:
print "TO HIGH"
elif guess < random_number:
print "TO LOW"
else:
print "Try something else"

Categories

Resources