How to repeat an action until it is completed in Python - python

from random import randint
guessed = randint(0,2)
user_guess = input("What do you think the number I'm thinking of is?")
if user_guess == guessed:
print("Correct!")
else:
print("Incorrect!")
I'm looking for a way for the code to repeat or a way to print different messages until user_guess is the same as guessed.
If the person guesses incorrectly, I want to be able to tell them that, and then give them another chance.
Thanks, sorry for beginner question.

Stay in a while loop as long as the guess is wrong.
You need the first guess to "prime" the loop.
# get the first user guess
while user_guess != guessed:
print "Incorrect"
# Get next user guess
Note that the code for "next user guess" will be very similar to "first user guess".

Use a while loop.
from random import randint
correct = False
while (not correct):
guessed = randint(0,2)
user_guess = int(input("What do you think the number I'm thinking of is?"))
if user_guess == guessed:
print("Correct!")
correct = True
else:
print("Incorrect!")

Related

There is a game to find a random number base on condition?

I would like to generate a random number (1,100), however, the random number is bigger than the user idea changes the range of random EX: computer random =36 but users answer is 87 so tell the computer my answer is bigger than your guess, the computer change its range (36,100) and vice versa.
this program runs just one time and doesn't repeat asking for select more randomly.
Thank you so much
from random import randint
a = int(1)
b = int(100)`enter code here`
guess = randint(a,b)
print(guess)
answer = input ("your idea:")
while answer != "done":
if answer == "big":
a = int(guess)
guess = randint(a,100)
print(guess)
if answer == "small":
b = int(guess)
guess = randint(1, b)
print(guess)
else:
answer == "done"
print("your guess number ", guess, "is right")
break
else:
answer == "done"
print("your guess number ", guess, "is right")
break
The break is indented outside the else. So it'll break regardless of the value of the answer. Just indent the break inside the else and it'll be fine

How to repeat code from a certian point when user input is incorrect

I'm new to Python so I'm not really sure on the basics so I understand this is probably a stupid question.
I'm making code where the user inputs a number, and if they get it wrong, I want the code to restart and ask them to guess again till it's right. How do I do this?
print("Let's play a game! Type in a number and see if you guess mine correctly!")
num = input("Type in a number: ")
for x in range (0,1):
if num == "7":
print("Correct!")
else:
print("Nope, try again!")
(Also I know that a lot of this code is probably wrong.)
You can put it in a while loop:
verified = None
while verified is None:
num = input("Type in a number: ")
if num == "7":
print("Correct!")
# if answer is good
verified = True
else:
print("Nope, try again!")

Python Random Guessing Game

Implement the GuessNumber game. In this game, the computer
- Think of a random number in the range 0-50. (Hint: use the random module.)
- Repeatedly prompt the user to guess the mystery number.
- If the guess is correct, congratulate the user for winning. If the guess is incorrect, let the user know if the guess is too high or too low.
- After 5 incorrect guesses, tell the user the right answer.
The following is an example of correct input and output.
I’m thinking of a number in the range 0-50. You have five tries to
guess it.
Guess 1? 32
32 is too high
Guess 2? 18
18 is too low
Guess 3? 24
You are right! I was thinking of 24!
This is what I got so far:
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
while guessed == False:
userInput = int(input("Guess 1?"))
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + randomNumber + "!")
elif userInput>randomNumber:
print(randomNumber + "is too high.")
elif userInput < randomNumber:
print(randomNumber + "is too low.")
elif userInput > 5:
print("Your guess is incorrect. The right answer is" + randomNumber)
print("End of program")
I've been getting a syntax error and I don't know how to make the guess increase by one when the user inputs the wrong answer like, Guess 1?, Guess 2?, Guess 3?, Guess 4?, Guess 5?, etc...
Since you know how many times you're going through the loop, and want to count them, use a for loop to control that part.
for guess_num in range(1, 6):
userInput = int(input(f"Guess {guess_num} ? "))
if userInput == randomNumber:
# insert "winner" logic here
break
# insert "still didn't guess it" logic here
Do you see how that works?
You forgot to indent the code that belongs in your while loop. Also, you want to keep track of how many times you guessed, with a variable or a loop as suggested. Also, when giving a hint you probably want to print the number guessed by the player, not the actual one. E.g.,
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
count = 0
while guessed is False and count < 5:
userInput = int(input("Guess 1?"))
count += 1
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + randomNumber + "!")
elif userInput > randomNumber:
print(str(userInput) + " is too high.")
elif userInput < randomNumber:
print(str(userInput) + " is too low.")
if count == 5:
print("Your guess is incorrect. The right answer is" + str(randomNumber))
print("End of program")
You are facing the syntax error because you are attempting to add an integer to a string. This is not possible. To do what you want you need to convert randomNumber in each print statement.
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
while guessed == False:
userInput = int(input("Guess 1?"))
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + str(randomNumber) + "!")
elif userInput>randomNumber:
print(str(randomNumber) + "is too high.")
elif userInput < randomNumber:
print(str(randomNumber) + "is too low.")
elif userInput > 5:
print("Your guess is incorrect. The right answer is" + randomNumber)
print("End of program")
import random
arr=[]
for i in range(50):
arr.append(i)
answer=random.choice(arr)
for trial in range(5):
guess=int(input("Please enter your guess number between 0-50. You have 5
trials to guess the number."))
if answer is guess:
print("Congratulations....You have guessed right number")
break
elif guess < answer-5:
print("You guessed too low....Try again")
elif guess > answer+5:
print("You guessed too high..Try again")
else:
print("Incorrect guess...Try again please")
print("the answer was: "+str(answer))
Just a three things to add:
The "abstract syntax tree" has a method called literal_eval that is going to do a better job of parsing numbers than int will. It's the safer way to evaluate code than using eval too. Just adopt that method, it's pythonic.
I'm liberally using format strings here, and you may choose to use them. They're fairly new to python; the reason to use them is that python strings are immutable, so doing the "This " + str(some_number) + " way" is not pythonic... I believe that it creates 4 strings in memory, but I'm not 100% on this. At least look into str.format().
The last extra treat in this is conditional assignment. The result = "low" if userInput < randomNumber else "high" line assigns "low" of the condition is met and "high" otherwise. This is only here to show off the power of the format string, but also to help contain conditional branch complexity (win and loss paths are now obvious). Probably not a concern for where you are now. But, another arrow for your quiver.
import random
from ast import literal_eval
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
win = False
for guess_count in range(1,6):
userInput = literal_eval(input(f"Guess {guess_count}: "))
if userInput == randomNumber:
print(f"You are right! I was thinking of {randomNumber}!")
win = True
break
else:
result = "low" if userInput < randomNumber else "high"
print(f"{userInput} is too {result}")
if win:
print ("YOU WIN!")
else:
print("Better luck next time")
print("End of program")

How Do I Make This Python Guessing Game Start Again?

I want to add some code to the end of this guessing game which will ask the user if they want to play again. If they say yes, the program will, I suppose, just run again from the beginning. I've tried multiple ideas, but none have worked. The closest was another if loop at the end. Thank you! x
print("Welcome to this guessing game!")
import random
x = random.randrange(50)
guess = int(input("I've picked an integer between 1 to 99. Guess what it is: "))
while x != "guess":
print
if guess < x:
print("Your guess is too low!")
guess = int(input("Guess again:"))
elif guess > x:
print("Your guess is too high!")
guess = int(input("Guess again:"))
else:
print ("You guessed the right number!")
Something like:
while True:
your code
if input("Continue? Y/N: ").lower() not in {"y", "yes"}:
break
At the end of every play, this gets input from the user, converts it to lower case, and sees if it's "y" or "yes". If it's not, the game breaks out of the loop, i.e. quits. Otherwise it keeps looping.
You could wrap your game in a function. And then on user say "yes", you invoke the function. And at the end of you game, reask the samequestion.
This is what function is made for.
Pseudo code:
function askUser(){
'Do you want to play'=>yes: launchGame, no:print("ok bye bye")
}
function myGame(){
//your game
askUser()
}
for example
import random
something="yes"
while(something == "yes"):
#your code...
#....
#from your code
else:
print ("You guessed the right number!")
something=input("Do you want to play again? (yes/no)")#input return str? I use raw_input all the time in p2.7
and this:
while x != "guess":
why to guess use " "?
x = random.randrange(50) so x never being a string "guess" its like while True: or while 1:
print("Welcome to this guessing game!")
import random
x = random.randrange(50)
guess = int(input("I've picked an integer between 1 to 99. Guess what it is: "))
while True:
if guess < x:
print("Your guess is too low!")
guess = int(input("Guess again:"))
elif guess > x:
print("Your guess is too high!")
guess = int(input("Guess again:"))
else:
print ("You guessed the right number!")
break
You are learning about the basics of python too little advice to read more books
x is the type of int and guess you use "" included "guess" he is not a variable name and become a string

Python Syntax error while making a little game

New to Python and trying to figure out what went wrong here. Making a simple game in which I have to guess the number that was randomly generated by the computer. Thanks for your help.
Here's what I have:
guessed == random.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
entered = 0
while entered != guessed
entered = raw_input("Enter your suggestion:")
entered = int(guessed_number)
if entered > guessed
print('Try less')
else
print('Try more')
print('You win!')
You're missing colons at the end of your conditionals and loops, aka while entered != guessed:. Add them to the end of the if and else lines as well. Also you are using the comparison (==) operator when assigning guessed instead of the assignment operator (=).
Also you will notice it prints "Try more" even when they guess the correct number, and then it will print "You win!". I'll leave this as an exercise to the new developer to fix.
entered = int(guessed_number)
makes no sense because you don't have a guessed_number variable. I think you meant to do
entered = int(raw_input("Enter your suggestion:")
Also, you're missing colons after your block starts at while, if, and else.
Welcome to Python 3.x! Here's the fixed code for you.
#Import Random
import random as r
#Create a random Number!
guessed = r.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
#Initiate variable --entered--
entered = 0
while (entered != guessed):
entered = int(input("Enter your suggestion:"))
#Fixed your if/else tree with correct indents and an elif.
if (entered > guessed):
print('Try less')
elif (entered <guessed):
print('Try more')
else:
print('You win!')
To add to the list:
guessed == random.randint(1,100)
should be
guessed = random.randint(1,100)
I'm sure you'd rather assign to guessed than compare it random.randint(1,100) and then throw the result of that comparison away.
entered = int(guessed_number)
It doesn't make any sense. There is no variable for 'guessed_number'.
I have edited your code to make it work:
import random
guessed = r.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
entered = 0
while (entered != guessed):
entered = int(input("Enter your suggestion:"))
if (entered > guessed):
print('Try less')
elif (entered <guessed):
print('Try more')
else:
print('You win!')
Hope that helps!
~Edward

Categories