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 ()
Related
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.')
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
import random
n = int (input('guess the number'))
randomnumber = random.randint(1,100)
while True:
if n == randomnumber:
print ('you have won')
break
elif randomnumber > n :
print('you guessed too high')
else :
print ('you guessed too low')
print ('thank you for playing')
The loop never ends because neither n nor randomnumber gets updated inside the loop. Try to insert n = int (input('guess the number')) inside the loop.
Any Python program can be broken if you press Control + C. Furthermore, I think what you want is that the program should ask the user every time they get it wrong. So, at the end of the while loop, repeat the line of code asking the user for the value of n.
Like Jonathan said, it would be a better idea to move the input statement to the top of the loop and remove the first input statement at the top of the program.
import random
randomnumber = random.randint(1,100)
while True:
n = int (input('guess the number'))
if n == randomnumber:
print ('you have won')
break
elif randomnumber > n :
print('you guessed too high')
else :
print ('you guessed too low')
print ('thank you for playing')
It repeats itself because it is in a 'while true' is a loop and it will repeat itself forever to solve it remove the while true and break statments hope that helped!
import random
n = int (input('guess the number'))
randomnumber = random.randint(1,100)
if n == randomnumber:
print ('you have won')
elif randomnumber > n :
print('you guessed too high')
else:
print ('you guessed too low')
print ('thank you for playing')
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))
def guess(n):
import random
x = random.randint(1,1000000)
while n != x:
if n < x:
print("Too Low, Try Again")
elif n > x:
print("Too High, Try Again")
if n == x :
print("Congrats")
again = print(input(str("Play Again Y/N?: ")))
if again == Y:
n = print(input(str("Input Number 'n': ")))
print(guess(n))
elif again == N:
print("Goodbye")
How do i make the while loops stop looping if the condition is matched and move onto the next condition that i have stated. Thank you!
Use the break statement (it terminates the nearest enclosing loop), e.g.
if n < x:
print("Too Low, Try Again")
elif n > x:
print("Too High, Try Again")
else:
break
You can exit a loop early using break. I am not sure what you mean by "the next condition", but after a normal "break" excution will just start immediately after the loop. Python also has a nice construct where you can put an "else" clause after the loop which run only if the Loop exits normally.
You need to call a new input to change n. In your while statement, n is never redefined.
Try:
def guess(n):
import random
x = random.randint(1,1000000)
while n != x:
if n < x:
print("Too Low, Try Again")
elif n > x:
print("Too High, Try Again")
n = print(input(str("Input Number 'n': ")))
and if you want to stop the loop... Use break
if my_condition:
break
will stop your loop. It also works with for loops.
But asking for a new value of n will result, when x ==n, to end your while statement.
I'd write something like this:
import random
def guess():
x = random.randint(1,1000000)
n = x + 1 # make sure we get into the loop
while n != x:
n = input(str("Input Number 'n': "))
if n < x:
print("Too Low, Try Again")
elif n > x:
print("Too High, Try Again")
else:
print("Congrats")
break
if __name__ == '__main__':
while True:
guess()
again = input(str("Play Again Y/N?: ") == 'N'
if not again:
break
As previously stated,your indentation is incorrect for the statement "while..." and also for the "if x==n" .Move it to two tabs to the right,as you want to run the loop till the player wants to play the game.In your given code, the loop is running where there is no increment in x .Now regarding the break condition you can try something like this.
else:
print("Goodbye")
break