How do I make the code reapte such that users can guess the answer to the random number only three times, how do I make it stop at a point? Thanks.
This is a random number guessing game, I'm a total beginner to python and can't find anything that helps me on the web (or it may be that I'm just dumb)
import random
print('what difficulty do you want? Type Easy or Hard accordingly')
difficulty = input('')
if difficulty == 'Hard':
print('your going to have a tough time')
hardrandomnum = random.randint(1,100)
def main():
print('try to guess the number')
playerguess = float (input(""))
if playerguess > hardrandomnum:
print ("guess a lower number")
if playerguess < hardrandomnum:
print("guess a higher number")
if playerguess == hardrandomnum:
print("correct")
restart = 4
if restart >4:
main()
if restart == 4:
exit()
main()
Loops and breaks.
For example if you want to run the code three times wrap it in a for loop:
for i in range(3):
[here goes your code]
or you could make a while loop and break:
while(True):
[here goes your code]
if condition is met:
break
you could use a for loop:
for i in range(3):
#your code
the number in range() indicates how many times you visit the code inside
there are also while loops but for your usecase a for loop should do the trick
Use a looping structure as below answer mentions.
Example with while loop
def repeat_user_input(num_tries=3):
tries = 0
result = []
while tries < num_tries:
tries += 1
result.append(float(input()))
return result
print(repeat_user_input())
Example with a list comprehension and range
def repeat_user_input(num_tries=3):
return [float(input()) for _ in range(num_tries)]
I believe you are looking for something like the below?
import random
import sys
guess_counter = 0
random_number = 0
easy_hard = input('Chose your difficulty lever by typing "easy" or "hard" ')
if easy_hard.lower() == 'easy':
print('Your in luck! You are about to have fun')
random_number = random.randint(1,10)
elif easy_hard.lower() == 'hard':
print('Woow this game is not going to be easy')
random_number = random.randint(1,100)
else:
print('You need to type either easy or hard and nothing else')
sys.exit()
while guess_counter < 4:
user_number = int(input('Guess: '))
if user_number < random_number:
print('Try higher number')
guess_counter += 1
elif user_number > random_number:
print('Trye lower number')
guess_counter += 1
else:
print('Congrats! You Won')
break
else:
print('Ooops! Looks like you luck run out.')
Related
I am making number guesser program and I am trying to figure out how to restart this if you get the number wrong. I have tried while true loops and It just keeps asking the question. I need some help with this thanks (python). EDIT: j1-lee answered question very good!
import random
ask = input("Guess a number between 0 and 10")
r1 = random.randint(0, 1)
print("The number is % s" %(r1))
if int(ask) == r1:
print("right")
else:
print("wrong")
Your while True approach was right. You only need to add break at an appropriate place:
import random
while True:
ask = input("Guess a number between 0 and 10: ")
r1 = random.randint(0, 10)
print(f"The correct number is {r1}.")
if int(ask) == r1:
print("... and you were right!")
break
else:
print("Try again!")
Use a while loop and set a break when user is correct. Also, change you random generator range, you'll only get 0 and 1
if you want the user keep guessing till they find the correct answer, try this:
import random
r1 = random.randint(0, 11)
# print("The number is % s" %(r1))
while True:
ask = input("Guess a number between 0 and 10: ")
if int(ask) < 0 or int(ask) > 10:
print('number you picked is not between 0 and 10')
else:
if int(ask) == r1:
print("correct!")
break
else:
print("try again")
This is my first post ever about programming!
Folks, when i execute this algorithm (a guessing game), it doesnt stop asking me for more inputs, even when i write "quit", that was supposed to be the quiting word. The "break" order doesnt work, and i can't find out why. Maybe it works, but when it quits the loop, it executes the "startgame()" at the bottom, but i need this "startgame()" at the bottom to make the game run for the first time, since the game is inside a function and i need to call it to start the game.
import random
def startgame():
a = random.randint (1,10)
cont = 0
while True:
b = input("Guess a number: ")
if b == 'quit':
break
elif int(b) > a:
print("Too high!")
cont += 1
True
elif int(b) < a:
print ("Too low!")
cont += 1
True
elif int(b) == a:
print ("You got it right!")
print ('You needed ',cont,'guesses!')
startgame()
startgame()
Any ideas about how to solve this?
Your code has a few small issues, but it actually works, you just didn't test enough to find your actual problem.
The issues:
the True lines don't do anything, you don't need them for the while loop; the while will evaluate the True right after it and loop forever.
you're mixing single and double quotes for your strings - that gets hard to read and confusing quickly, so you're better off using one style, preferably whatever PEP8 recommends. https://www.python.org/dev/peps/pep-0008/
The problem:
your break works just fine; try running your script and entering 'quit' at the first prompt, it quits as expected.
the reason it appears not to work is because you restart the entire game by calling the startgame function again after winning the game. This causes a new, nested call from within the game (think 'Inception') and when the game breaks, it ends up on the previous level.
A solution would be to remove the call to startgame() and instead wrapping the whole thing in a second while, for example like this:
import random
def startgame():
b = 0
while b != 'quit':
a = random.randint(1, 10)
cont = 0
while True:
b = input('Guess a number: ')
if b == 'quit':
break
elif int(b) > a:
print('Too high!')
cont += 1
elif int(b) < a:
print('Too low!')
cont += 1
elif int(b) == a:
print('You got it right!')
print('You needed ', cont, 'guesses!')
startgame()
For times like these, I usually use a simple control variable and run the loop on it. For ex:
right_guess=False
while not right_guess:
and then just go
if guess=right:
right_guess=True
break
just remove the startgame() from inside the loop and replace it by break
import random
def startgame():
a = random.randint (1,10)
cont = 0
while True:
b = input("Guess a number: ")
if b == 'quit':
break
elif int(b) > a:
print("Too high!")
cont += 1
elif int(b) < a:
print ("Too low!")
cont += 1
elif int(b) == a:
print ("You got it right!")
print ('You needed ',cont,'guesses!')
break # remove this break statement if you want to restart it again after winning
startgame ()
import random
answer = random.randrange(1,100)
guess = 101
while int(guess) != 0 :
guess = input('Enter a number between 1 and 100 or enter 0 to exit: ')
guess = int(guess)
if guess < answer :
print('Too low')
elif guess > answer :
print('Too high')
else:
print('Correct')
print('Game closed')
I have to make a random number guessing game and to close the game you enter 0 it is supposed to print game closed which it does however it also prints the if < since 0 is always going to be lower than the guess how would i get it to not include the if <
You need to rank your conditions in the order of preference. What takes the highest precedence? You'd want if guess == answer to be your first priority, because if that's the case then there's no need to check anything else and your program is done. What's your second priority? If 0 is typed then the game ends.
In other words, start with the more specific conditions (not something as broad as guess > answer).
Reframe your conditional statements as such:
if guess == answer:
print('Correct')
break
elif guess == 0:
print('Game closed')
elif guess > answer:
print('Too high')
else:
print('Too low')
You also need to set guess to 0 to break out of the loop (or just add a break as I've done here)
Re-formulate your code a bit:
import random
answer = random.randrange(1,100)
while True :
guess = int(input('Enter a number between 1 and 100 or enter 0 to exit: '))
if guess == 0:
print('Game closed')
break
elif guess < answer :
print('Too low')
elif guess > answer :
print('Too high')
else:
print('Correct!')
break
number = 7
def magicnumber (guess):
if number<guess:
print ("too high")
elif number>guess:
print ("too low")
elif number == guess:
print ("well done")
return magicnumber
Above is my code for my magic number guessing program. My question is how to insert a loop counter. I did some research on loop counter integration, and many people have said to use the enumerate function, problem is I have no idea how to use such a function and if it is appropriate in my case. Normally, I jus declare a counter variable as 0 then use the += function to add 1 to that variable but in my case this does not work as I cant declare the variable before the def magicnumber (guess) line and if I were to declare it, the counter would revert back to 0 after the return. I am therefore enquiring how to add a loop count as I only want the user to have 5 guesses.
Thanks
counter = 5
while counter > 0:
guess = int(raw_input())
if magicnumber(guess) == number:
break
counter -= 1
Another approach:
for i in range(5):
guess = int(raw_input())
if magicnumber(guess) == number:
break
Try using the answer from here: That's what static variables are for (among other things).
That would result in the following code
number = 7
def magicnumber (guess):
magicnumber.counter += 1
if(magicnumber.counter <= 5):
if number<guess:
print ("too high")
elif number>guess:
print ("too low")
elif number == guess:
print ("well done")
magicnumber.counter = 0#If you want to reset the counter
return
else:
print "Out of trials!"
return
magicnumber.counter = 0
I'm currently in the process of creating a game where it loops over and over again until you guess the right number.
The problem I'm having is getting the looping command right. I want to go for a while loop but I can get it to work, for certain parts of the script. If I use a "while true" loop, the if statement's print command is repeated over and over again but if I use any symbols (<, >, <=, >= etc.) I can't seem to get it to work on the elif statements. The code can be found below:
#GAME NUMBER 1: GUESS THE NUMBER
from random import randint
x = randint(1,100)
print(x) #This is just here for testing
name = str(input("Hello there, my name's Jarvis. What's your name?"))
print("Hello there ",name," good to see you!")
num = int(input("I'm thinking of a number between 1 and 100. can you guess which one it is?"))
attempt = 1
while
if num == x:
print("Good job! it took you ",attempt," tries!")
num + 1
elif num >= x:
print("Too high!")
attempt = attempt + 1
elif num <= x:
print("Too low!")
attempt = attempt + 1
else:
print("ERROR MESSAGE!")
Any and all help is appreciated.
You can use a boolean in the while :
from random import randint
x = randint(1,100)
print(x) #This is just here for testing
name = str(input("Hello there, my name's Jarvis. What's your name?"))
print("Hello there ",name," good to see you!")
attempt = 1
not_found = True
while not_found:
num = int(input("I'm thinking of a number between 1 and 100. can you guess which one it is?"))
if num == x:
print("Good job! it took you ",attempt," tries!")
not_found = False
elif num > x: #Don't need the equals
print("Too high!")
elif num < x: #Don't need the equals
print("Too low!")
else:
print("ERROR MESSAGE!")
attempt = attempt + 1
You should put your question in the loop, because you want to repeat asking after each failure to get it right. Then also break the loop when user found it:
attempt = 0
while True:
attempt = attempt + 1
num = int(input("I'm thinking of a number between 1 and 100. can you guess which one it is?"))
if num == x:
print("Good job! it took you ",attempt," tries!")
break
elif num >= x:
print("Too high!")
attempt = attempt + 1
elif num <= x:
print("Too low!")
else:
print("ERROR MESSAGE!")
Your while needs a colon, and a condition
while True:
and if you use a while True: you have to end the loop, you can use a variable for this.
while foo:
#Your Code
if num == x:
foo = False
Also, you could use string format instead of breaking your string. For example,
print("Good job! it took you %s tries!" % attempt)
or
print("Good job! it took you {0} tries!".format(attempt))