I'm fairly new to Python and I've made a random number guessing game. The problem I'm running into is I cannot get my program to exit the while loop when I reach 0 lives instead it tells me i have -1 lives or -2 lives etc. I've looked over the code and I'm struggling to see the flaw in my logic/programming. Any help with this would be appreciated!
from random import randint
randomnumber = randint(1, 30)
print("Welcome to the number guessing game!")
game = False
lives = 3
while not game or lives == 0:
playerguess = int(input("Please enter a number between 1 and 30: "))
if playerguess > 30 or playerguess < 1:
print("Please only enter numbers between 1 and 30")
elif playerguess == randomnumber:
print("Correct!")
game = True
elif playerguess == randomnumber - 1 or playerguess == randomnumber + 1:
lives -= 1
print("You were so close! You now have", lives, "lives remaining!")
else:
lives -= 1
print("Not even close! You now have", lives, "lives remaining!")
if game:
print("Congratulations you won with ", lives, "lives remaining!")
else:
print("Sorry you ran out of lives!")
Change to this while not game and lives > 0.
Your current statement while not game or lives == 0, means that the loop can continue if lives are not 0 or not game since you can run out of lives without changing game to True the loop won't exit.
This new condition will only allow to run the game if you have more than 0 lives and not game which will fix the issue.
Congratulations you won with 3 lives remaining!
...
Not even close! You now have 0 lives remaining!
Sorry you ran out of lives!
Your condition is wrong:
while not game and lives > 0:
You want to loop while the game is not complete (not game) and while the number of lives is greater than 0 (lives > 0).
You should improve your while conditions to while not game and lives > 0 or add a break command in your while loop that will only get called whenever you reach lives < 1:
...
while not game:
playerguess = int(input("Please enter a number between 1 and 30: "))
if playerguess > 30 or playerguess < 1:
print("Please only enter numbers between 1 and 30")
elif playerguess == randomnumber:
print("Correct!")
game = True
elif playerguess == randomnumber - 1 or playerguess == randomnumber + 1:
lives -= 1
print("You were so close! You now have", lives, "lives remaining!")
else:
lives -= 1
print("Not even close! You now have", lives, "lives remaining!")
#get out of loop if player died
if lives < 1:
break
if game:
...
Related
I created a game, in which there is a secret number, and you guess, then the computer guesses. The secret number changes every round. To win, either you or the computer needs to get a score of 2.
I don't know how many rounds it will take, so I loop the game 100 times in a while loop with the condition that the user_Score and computer_Score is not equal to 2,
However, when I run my code, it seems like it just skips the condition, and goes on 100 times, and I don't understand why.
while user_score != 2 or computer_score != 2:
for _ in range(100):
game()
The above code is the part which I am talking about, it is in the near bottom of my code
import random
computer_score = 0
user_score = 0
def game():
global user_score
global computer_score
secret_number = random.randrange(10)
while True:
user_guess = input("Guess a number from 0 - 10: ")
if user_guess.isdigit():
user_guess = int(user_guess)
if 0 <= user_guess <= 10:
break
else:
print("Enter a valid number from 0 - 10")
else:
print("Please enter a valid number from 0 - 10")
computer_guess = random.randrange(10)
if user_guess == secret_number:
print("Hooray! You guessed correctly")
user_score += 1
print(f"Your score is {user_score}")
else:
print("Sorry wrong guess")
print("Now Player 2's turn")
if computer_guess == secret_number:
print("Player 2 guessed the correct number!")
computer_score += 1
print(f"Player 2's score is {computer_score}")
else:
print("Player 2 guesed incorrectly")
print( f" Your score: {user_score}" + " " + f"Player 2 score: {computer_score}")
game()
while user_score != 2 or computer_score != 2:
for _ in range(100):
game()
if user_score == 2:
print(f"Hooray! You won with a score of {user_score} points")
print(f"Player 2 got {computer_score} points")
elif computer_score == 2:
print(f"Sorry, you lost. Your score is {user_score}, and Player 2 got {computer_score} points")
print( f" Your final score: {user_score}" + " " + f"Player 2 final score: {computer_score}" )
while user_score != 2 or computer_score != 2:
for _ in range(100):
game()
If a player gets a score of two, that will not stop the inner for loop. It's going to loop to 100, because that's what you told it to do.
I'm confused why you need the inner loop at all, though. Isn't the outer while loop enough?
while user_score != 2 or computer_score != 2:
game()
Also, wouldn't you want to use and here, instead of or? The way this is written, it will only stop if both scores are equal to 2. And if one of the players gets to a score of 3 while the other player has a score of 0 or 1, this loop will never exit.
It will always show this same fault. Because, at the beginning of the game when 1st round is over, the for loop starts iterating and it will continue for 100 times. Best way is to remove the for loop and just run the while loop.
while user_score != 2 or computer_score != 2:
game()
I'm a beginner in Python and I was wondering why this keeps looping, can someone help me out. When I print it out, it stays in a loop even tho I guessed the number right
import random
answer = random.randint(1,10)
lives = 5
out_of_lives = 0
print("Hi there! What is your name? ")
name = input()
print("Alright " + name + ", we're playing guess the number between 0 and 20.")
guess = int(input("Take a guess: "))
while (lives != 0) or (guess != answer):
if guess > answer:
print("Guess lower!")
lives = lives - 1
print("You have got", lives, "lives left")
guess = int(input('Try again, your new guess: '))
elif guess < answer:
print("Guess higher")
lives = lives - 1
print("You have got", lives , "lives left")
guess = int(input('Try again, your new guess: '))
elif guess == answer:
print("Good job, you guessed the number")
elif lives == 0:
print("Game over!, I was thinking about the number: ", answer)
Because you are not breaking the while loop.
One way to solve your problem is by inserting the conditions whether the user guessed the right number inside a main if condition of the guess is not the answer. And then break the loop when the user succeed. Like the following:
import random
answer = random.randint(1,10)
lives = 5
out_of_lives = 0
print("Hi there! What is your name? ")
name = input()
print("Alright " + name + ", we're playing guess the number between 0 and 20.")
guess = int(input("Take a guess: "))
while (lives > 1):
if guess != answer:
if guess > answer:
print("Guess lower!")
lives = lives - 1
print("You have got", lives, "lives left")
guess = int(input('Try again, your new guess: '))
elif guess < answer:
print("Guess higher")
lives = lives - 1
print("You have got", lives , "lives left")
guess = int(input('Try again, your new guess: '))
else:
print("Good job, you guessed the number")
break
print("Game over!, I was thinking about the number: ", answer)
yes this is because you also need to break the loop just where you want it to stop.
On the condition that the game is won, no adjustment to life or answers is set meaning you get stuck in the while loop.
It is because of the conditions of your while loop. You wrote that "Keep going if you have lives remain or you are wrong". So it will not stop when you still have lives even if you guessed correct, or it will not stop writing "Game over" as you did not guessed right. The right thing to do is to change the loop condition as: while (lives !=0) and (guess != answer):
Here's the correct code. Execute it. It'll solve your issue
import random
answer = random.randint(1,10)
lives = 5
out_of_lives = 0
print("Hi there! What is your name? ")
name = input()
print("Alright " + name + ", we're playing guess the number between 0 and 20.")
guess = int(input("Take a guess: "))
while(True):
if(lives==1):
print("Game over!, I was thinking about the number: ", answer)
break
else:
if guess == answer:
print("Good job, you guessed the number")
break
elif guess > answer:
print("Guess lower!")
lives = lives - 1
print("You have got", lives, "lives left")
guess = int(input('Try again, your new guess: '))
elif guess < answer:
print("Guess higher")
lives = lives - 1
print("You have got", lives , "lives left")
guess = int(input('Try again, your new guess: '))
I'm still quite new to Python so I apologise if this is too easy or stupid, but I was recently given the task to create a number guessing game. The game has 100 numbers, numbered from 1 to 100, and will also have a dice roll numbered 1 to 6 to determine how many tries you get (e.g If the user rolls a 4, the user will get 4 turns to try and guess the number between 1 to 100). So far I managed to complete most of it, however, upon testing the program myself, when I actually get the correct answer it doesn't display a win.
import random
random_number = random.randint(1, 5)#I made the range from 1 to 5 to make my chances of guessing the correct number greater#
guessnum_dice = random.randint(1, 6)
guess_count = 0
guess_limit = guessnum_dice
out_of_guesses = False
win = False
# This name function prints out the users name; this is because the task asks me to save each game's
# statisitics and record them within an external text file. Still haven't figured out how to do that
# as well :(
def name_function():
x = input("Enter your name: ")
print("Hello, " + x)
return
name_function()
user_roll = input("Type \"roll\" to roll the dice: ")
if user_roll == "roll":
print("You have "+str(guessnum_dice) + " guesses. Use them wisely!")
if guessnum_dice == 1:
user_guess = input("Guess the secret number: ")
if user_guess != random_number:
out_of_guesses = True
if guessnum_dice == 2:
while guess_count < guess_limit:
user_guess = input("Guess the secret number: ")
guess_count += 1
if user_guess < str(random_number):
print("Higher!")
elif user_guess > str(random_number):
print("Lower")
#Here Ive tried making the user's guess equal to the number, but to no success
elif user_guess == random_number:
win = True
print("You Win")
else:
out_of_guesses = True
if guessnum_dice == 3:
while guess_count < guess_limit:
user_guess = input("Guess the secret number: ")
guess_count += 1
if user_guess < str(random_number):
print("Higher!")
elif user_guess > str(random_number):
print("Lower")
elif user_guess == random_number:
win = True
print("You Win")
else:
out_of_guesses = True
if guessnum_dice == 4:
while guess_count < guess_limit:
user_guess = input("Guess the secret number: ")
guess_count += 1
if user_guess < str(random_number):
print("Higher!")
elif user_guess > str(random_number):
print("Lower")
elif user_guess == random_number:
win = True
print("You Win")
else:
out_of_guesses = True
if guessnum_dice == 5:
while guess_count < guess_limit:
user_guess = input("Guess the secret number: ")
guess_count += 1
if user_guess < str(random_number):
print("Higher!")
elif user_guess > str(random_number):
print("Lower")
elif user_guess == random_number:
win = True
print("You Win")
else:
out_of_guesses = True
if guessnum_dice == 6:
while guess_count < guess_limit:
user_guess = input("Guess the secret number: ")
guess_count += 1
if user_guess < str(random_number):
print("Higher!")
elif user_guess > str(random_number):
print("Lower")
elif user_guess == random_number:
win = True
print("You Win")
else:
out_of_guesses = True
if out_of_guesses:
print("You Lose! The number: " + str(random_number))
if win == True:
print("You won")
And here is the output:
Enter your name: Gary
Hello, Gary
Type "roll" to roll the dice: roll
You have 6 guesses. Use them wisely!
Guess the secret number: 4
Lower
Guess the secret number: 3
Lower
Guess the secret number: 2 ### Here you can see that 2 is the correct answer, but it wont display a-
Guess the secret number: 2 ### -win no matter how many times it gets entered
Guess the secret number: 2
Guess the secret number: 1
Higher!
You Lose! The number: 2
Process finished with exit code 0
Once again I apoligise if this seems confusing as I find it difficult to try and explain my problem. Any advice would be much appreciated
Please consider using loop to go through all guesses instead of using if statements, in this way your code will be more compact and you can change the loop counter as you wish.
Also when you get user input, cast it to integer so that you can compare the numbers, otherwise user input will remain as string. check out below solution:
#This is a guess the number game
import random
print("What is your name?")
myName = input()
print("Well, " + myName + ", I am thinking of a number between 1 and 20")
loopCounter = 0
myNumber = random.randint(1, 20)
while loopCounter < 6:
print("Take a guess.")
guessNumber = input()
guessNumber = int(guessNumber)
loopCounter = loopCounter + 1
if guessNumber < myNumber:
print("Your guess is too low.")
elif guessNumber > myNumber:
print("Your guess is too high.")
else:
loopCounter = str(loopCounter)
print("Well done, " + myName + ", you guessed the number in " + loopCounter + " guesses!")
break
if guessNumber != myNumber:
myNumber = str(myNumber)
print("Nope. The number was " + myNumber)
Hope this helps.
This is the code:
print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))
guess_limit = 5
guess_counter = 1
out_of_guesses = False
print("You have", str(guess_limit - guess_counter), "tries left")
while not out_of_guesses:
guess = int(input("Enter guess: "))
if guess == Magic_number:
print("Well done you got it!!")
exit(0)
elif guess < Magic_number:
print("That number is too small, try again")
elif guess > Magic_number:
print("That number is too high try again")
guess_counter += 1
print("You have", str(guess_limit - guess_counter), "tries left")
# exit clause
if guess_limit == guess_counter:
out_of_guesses = True
print("Game over, sorry")
And even if I get it correct on the first try it does something like this:
Welcome to my guessing game can you get the magic number
hint,
it's between 1 and 100
47
Enter your guess: 47
You have 4 tries left
Enter guess: 47
Well done you got it!!
As you can see even though i was correct on the first try it wasn't counted. Ps.(That is what shows up at the bottom of my screen where the code is executed.)
You do not check if guess == Magic_number after reading input on line 4.
Like this
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))
if guess == Magic_number:
print ("You won")
exit(0)
You don't need all those variables, check this.
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess_limit = 5
guess_counter = 0
while True:
guess = int(input("Enter guess: "))
if guess == Magic_number:
print("Well done you got it!!")
exit(0)
elif guess < Magic_number:
print("That number is too small, try again")
elif guess > Magic_number:
print("That number is too high try again")
guess_counter += 1
print(f"You have {guess_limit - guess_counter} tries left")
if guess_counter == guess_limit:
print("Game over, sorry")
exit(0)
I was just wondering if there is a way to limit the amount of times a user can input something on a while loop. This is simply a guess a number 1-100 game. I have the found variable = False.
while not found:
user_guess = int(input("Your guess: "))
if user_guess == random_number:
print("you got it!")
found = True
elif user_guess > random_number:
print("Guess lower")
else:
print("guess higher")
I wanted to see if i could make this code seem more like a game by limiting the amount a user can guess for the input. Ive had some ideas i just cannot wrap my head around it. do i have set a variable value for the input to set the amount of times it can run? Im new to programming so i am struggling a bit.
count = 0
max_guesses_allowed = pick your max here
while not found or count < max_guesses_allowed:
user_guess = int(input("Your guess: "))
if user_guess == random_number:
print("you got it!")
found = True
elif user_guess > random_number:
count += 1
print("Guess lower")
else:
count += 1
print("guess higher")
The standard way would be to count the number of loops, and then exit if they exceed the maximum.
max_allowed = 10
attempt = 0
while not found:
attempt += 1
user_guess = int(input("Your guess: "))
if user_guess == random_number:
print("you got it!")
found = True
elif attempt == max_allowed:
print("You've reached the maximum number of guesses.")
break
elif user_guess > random_number:
print("Guess lower")
else:
print("guess higher")