Why is this infinite while loop not working - python

def main():
import random
guesslist = []
ErrorTol = 5
guessesTaken = 0
print("|--------------------------------------------------------------------|")
print("| |")
print("|--------------------------------------------------------------------|")
print("| WELCOME! Please enter your name to begin this guessing game |")
print("|--------------------------------------------------------------------|")
print("| |")
print("|--------------------------------------------------------------------|")
myName = input()
again = ""
while again != "q":
number = random.uniform(-300, 300)
print('Well, ' + myName + ', I am thinking of a number between -300 and 300.')
while guessesTaken < 3:
print("Take a guess.")
guess = input()
guess = int(guess)
guesslist.append(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number or (abs(number - guess) <= ErrorTol):
break
if guess == number or (abs(number - guess) <= ErrorTol):
guessesTaken = guessesTaken
print('Good job, ' + myName + '! You guessed my number in ' + str(guessesTaken) + ' guesses!')
print("numbers you guessed:", guesslist)
else:
number = int(number)
print('Nope. The number I was thinking of was ' + str(number))
again = input("Hit 'q' to quit the program or any other keys to play the game again.").lower()[0]
main()
I can't get the program to loop properly, I have no clue what I did wrong! When I do not guess the number correctly, I should be able to hit any keys to try again and hit 'q' to try again, but when I hit any other keys it will not loop properly. Again, I have no clue what is wrong with this code.

You do not reset guessesTaken to zero so your program acts as if the user has already made there three guesses. Try something like this:
again = input("Hit 'q' to quit the program or any other keys to play the game again.").lower()[0]
guessesTaken = 0

You have to reset the amount of guesses when you check to see if the key is not equal to q. I put your code into another method, just better design!
Good luck!
import random
def main():
print("|--------------------------------------------------------------------|")
print("| |")
print("|--------------------------------------------------------------------|")
print("| WELCOME! Please enter your name to begin this guessing game |")
print("|--------------------------------------------------------------------|")
print("| |")
print("|--------------------------------------------------------------------|")
guess()
def guess():
guesslist = []
ErrorTol = 5
guessesTaken = 0
myName = input()
again = ""
while again != "q":
guessesTaken = 0
number = random.uniform(-300, 300)
print('Well, ' + myName + ', I am thinking of a number between -300 and 300.')
while guessesTaken < 3:
print("Take a guess.")
guess = input()
guess = int(guess)
guesslist.append(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number or (abs(number - guess) <= ErrorTol):
break
if guess == number or (abs(number - guess) <= ErrorTol):
guessesTaken = guessesTaken
print('Good job, ' + myName + '! You guessed my number in ' + str(guessesTaken) + ' guesses!')
print("numbers you guessed:", guesslist)
else:
number = int(number)
print('Nope. The number I was thinking of was ' + str(number))
again = input("Hit 'q' to quit the program or any other keys to play the game again.")

Related

some syntax issues im facing with python

Hey so i have started with python recently and im facing a syntax error when im trying to activate this code with python 3.1
This code is from the Automate the Boring Stuff and it's exactly the same as the author used and mine is facing an Error, any idea ?
btw the Error is with the elif condition
import random
print('Hello. What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 to 20 ')
secretNumber = random.randint(1, 20)
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses')
else:
print(' Nope, that number i was thinking of was ' + str(secretNumber))
code with identation fixed which ran on my machine
import random
print('Hello. What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 to 20 ')
secretNumber = random.randint(1, 20)
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses')
else:
print(' Nope, that number i was thinking of was ' + str(secretNumber))
Here is the correct indentation:
import random
print('Hello. What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 to 20 ')
secretNumber = random.randint(1, 20)
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses')
else:
print(' Nope, that number i was thinking of was ' + str(secretNumber))
Indentation is a very important concept of Python!
You have indentation errors on your code, elif and else should be indented at the same level of if. Same for the second 'else'.
import random
print('Hello. What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 to 20 ')
secretNumber = random.randint(1, 20)
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses')
else:
print(' Nope, that number i was thinking of was ' + str(secretNumber))
I think you are looking for this. Note the indentation of the if/else statements.
import random
print('Hello. What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 to 20 ')
secretNumber = random.randint(1, 20)
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken)
+' guesses')
else:
print(' Nope, that number i was thinking of was ' + str(secretNumber))
Disclaimer:
I'm a bit of a newb myself so there could be better answers out there.
Python is all about indentation. The indentations of the if/elif/else should be all on the same level. See below:
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break

How to continue with number of guesses after ValueError in guessing game?

I'm going through the Automate the Boring Stuff with Python videos on youtube. I finished the one about random number guessing game and am now adding some stuff to it to make it more complete.
I added some code that makes it so that if you don't enter an integer (which creates a ValueError) the program tells you that you didn't enter an integer. However, the point of the game is that you only get 6 guesses, but when the error comes up it, it resets the number of guesses.
How can I make it so that the error doesn't reset the number of cases?
Here's the code:
# This is a guess the number game.
import random
print ('Hello, what is your name?')
name = input ()
name = name.strip()
print ('Well, ' + name + ' I am thinking of a number between 1 and 20.')
secretNumber = random.randint (1, 20)
print ('DEBUG: Secret number is ' + str(secretNumber))
while True:
try:
for guessesTaken in range (1, 7):
print ('Take a guess.')
guess = int (input ())
if guess < secretNumber:
print ('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break # This condition is for the correct guess
if (guess == secretNumber and guessesTaken == 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guess.')
break
elif (guess == secretNumber and guessesTaken > 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
break
else:
print ('Nope. The number I was thinkig of was ' + str(secretNumber))
break
except ValueError:
print ('You did not enter a number.') # This condition is for if a non-integer is entered.
I feel like I've tried every combination of where I can but the try and for loop, but can't seem to figure it out.
The outer while loop seems unnecessary because it allows you to try even after 6 attempts.
Therefore the break in the last three conditions will also be deleted.
You should put the try into the for loop so that if an exception is raised, the program will continue to count the number of attempts.
I would do something like:
# This is a guess the number game.
import random
print('Hello, what is your name?')
name = input()
name = name.strip()
print('Well, ' + name + ' I am thinking of a number between 1 and 20.')
secretNumber = random.randint(1, 20)
print('DEBUG: Secret number is ' + str(secretNumber))
for guessesTaken in range(1, 7):
try:
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break # This condition is for the correct guess
except ValueError:
print('You did not enter a number.') # This condition is for if a non-integer is entered.
if (guess == secretNumber and guessesTaken == 1):
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guess.')
elif (guess == secretNumber and guessesTaken > 1):
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
else:
print('Nope. The number I was thinkig of was ' + str(secretNumber))
The except block also should be moved, to be related to the try block, under the block of the loop because we don't want to stop the for loop as I mentioned before.
This is a guess the number game.
import random
print ('Hello, what is your name?')
name = input ()
guess = 0
name = name.strip()
print ('Well, ' + name + ' I am thinking of a number between 1 and 20.')
secretNumber = random.randint (1, 20)
print ('DEBUG: Secret number is ' + str(secretNumber))
while True:
for guessesTaken in range (1, 7):
try:
print ('Take a guess.')
guess = int (input ())
if guess < secretNumber:
print ('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break # This condition is for the correct guess
except ValueError:
print ('You did not enter a number.') # This condition is for if a non-integer is entered.
if (guess == secretNumber and guessesTaken == 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guess.')
break
elif (guess == secretNumber and guessesTaken > 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
break
else:
print ('Nope. The number I was thinkig of was ' + str(secretNumber))
break

Python Statistics File

I've created a python guessing game but now I want to be able to save the game statistics to a file at the end of each game. For each game the statistics to be recorded include the player name, their play status(win or loss) and the number of tries. I need the game to be saved in this format:
Username|status|number of guesses
If anyone could help me with that, that would be kind.
This is the code I have for the game:
import random
number = random.randint(1, 100)
player_name = input("Hello, What's your name?: ")
number_of_guesses = 0
print("Okay! "+ player_name+ " I am guessing a number between 1 and 100:")
max_guesses = random.randint(1, 6)
print("You have " + str(max_guesses) + " guesses. ")
while number_of_guesses < max_guesses:
guess = int(input())
number_of_guesses += 1
if guess < number:
print("Your guess is too low")
if guess > number:
print("Your guess is too high")
if guess == number:
break
if guess == number:
print("You guessed the number in " + str(number_of_guesses) + " tries!")
else:
print("You did not guess the number, the number was " + str(number))
f = open("Statistics.txt", "a")
f.write(player_name), (number_of_guesses)
f.close()
f = open("Statistics.txt", "r")
print(f.read())

Number Guessing Game Python 3.8

A random number between 1 and 6, this represents a roll of a dice. The random number becomes the number of allowed guesses from the user. I cannot get the dice number to be same as amount of guesses allowed.
This is what I have so far:
import random
number = random.randint(1, 100)
player_name = input("Hello, What's your name?")
number_of_guesses = 0
print('okay! '+ player_name+ ' I am guessing a number between 1 and 100:')
min_value = 1
max_value = 6
print(random.randint(min_value, max_value))
while number_of_guesses < 5:
guess = int(input())
number_of_guesses += 1
if guess < number:
print("Your guess is too low")
if guess > number:
print("Your guess is too high")
if guess == number:
break
if guess == number:
print("You guessed the number in " + str(number_of_guesses) + " tries!")
else:
print("You did not guess the number, the number was " + str(number))
OK, this should fix your issues:
import random
number = random.randint(1, 100)
player_name = input("Hello, What's your name?")
number_of_guesses = 0
print('okay! '+ player_name+ ' I am guessing a number between 1 and 100:')
max_guesses = random.randint(1, 6)
print(f"You have {max_guesses} tries. ")
won = False
while number_of_guesses < max_guesses:
guess = int(input())
number_of_guesses += 1
if guess < number:
print("Your guess is too low")
if guess > number:
print("Your guess is too high")
if guess == number:
won = True
break
if won:
print("You guessed the number in " + str(number_of_guesses) + " tries!")
else:
print("You did not guess the number, the number was " + str(number))
However, this seems like some starting-out project, so it is important to understand what every code line is doing. In case you are not sure about anything, ask away :)
It looks like you're printing the random number, but not really using it. Could you try the following:
import random
number = random.randint(1, 100)
player_name = input("Hello, What's your name?")
number_of_guesses = 0
print('okay! '+ player_name+ ' I am guessing a number between 1 and 100:')
min_value = 1
max_value = 6
random_number = random.randint(min_value, max_value)
print(random_number)
while number_of_guesses < random_number:
guess = int(input())
if guess < number:
print("Your guess is too low")
if guess > number:
print("Your guess is too high")
if guess == number:
break
number_of_guesses += 1
if guess == number:
print("You guessed the number in " + str(number_of_guesses) + " tries!")
else:
print("You did not guess the number, the number was " + str(number))

NameError: name is not defined in Python code

Trying my first Python game with Python 3.6. Have tried several IDEs including Geany, and Wing Personal.
The error is:
Traceback (most recent call last):
File "game1.py", line 7, in
myName = input()
File "", line 1, in
#This is a guess the numbers game.
import random
guessesTaken = 0
print("Hello! What is your name?")
myName = input()
number = random.randint(1, 20)
print("Well, " + myName + ", I am thinking of a number between 1 and 20.")
while guessesTaken < 6:
print("Take a guess.")
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print("Your guess is too low.")
if guess > number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print("Good job, " + myName + "! You guesses my number in " + guessesTaken + " guesses!")
if guess != number:
number = str(number)
print("Nope. The number I was thinking of was " + number)
This code has multiple indentation errors. Indentation generally means four spaces or one tab character. So, the code inside each if-else condition should be indented by one level.
Also, in one of the conditions:
if guess > number:
break
What do you expect that to do? Break is used to stop the loops. I guess you want to exit the program for this particular case. For that you can use return 0 or sys.exit().
Here is the code, properly indented:
#This is a guess the numbers game.
import random
import sys
guessesTaken = 0
print("Hello! What is your name?")
myName = input()
number = random.randint(1, 20)
print("Well, " + myName + ", I am thinking of a number between 1 and 20.")
while guessesTaken < 6:
print("Take a guess.")
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print("Your guess is too low.")
if guess > number:
sys.exit()
if guess == number:
guessesTaken = str(guessesTaken)
print("Good job, " + myName + "! You guesses my number in " + guessesTaken + " guesses!")
if guess != number:
number = str(number)
print("Nope. The number I was thinking of was " + number)

Categories

Resources