Infinite While Loop Help Needed - python

print("Hi. Welcome on Guess The Number!!")
from random import randint
randomnumber = randint(1,100)
print("Guess the number!!")
usernumber = int(input("Which number am I thinking about?"))
try = 0
while usernumber != randomnumber:
if usernumber < randomnumber:
print("Lower...")
print()
try += 1
usernumber = int(input("Which number am I thinking about"))
elif usernumber < randomnumber:
print("Higher")
print()
try += 1
usernumber = int(input("which numberam I thinking about?"))
print("Finally!!!")
if try <= 10:
print("Well done!!")
elif try > 10:
print("U lost")
print()
print("The End!")
This causes me an infinite loop when I put an input number that is higher than the random number.
How can I fix this?

In your code, both the if and the else only cater to usernumber < randomnumber. This is why you will end up with an infinite loop - because you haven't coded the if-else branch, that would handle such a case.

Related

How to tell which part of code should be inside a function?

I'm having a problem understanding which part of my code belongs to a funtions and which does not. My code is messy and I know I need to use functions to clean it up.
The code below is a console game whereby a computer generates a random integer between 1 and 100 and the user user guesses that number with a limited number of guesses.eg. 5 for hard. 10 for easy.
How can I use funtions in this code?
#TODO 1: Generate a random number between 1 and 100
import random
GUESS = random.randint(1, 100)
#TODO 2: Print the guess(,for debugging)
#TODO 3: Choose the difficulty("easy" or "hard")
difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ")
#TODO 4: Loop 5 times if the user typed 'hard' or 10 times if the user typed 'easy'
if difficulty == "hard":
try:
#TODO 4.1: User inputs the guesses the random number
print("You have 5 attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
#TODO 4.2: Compare the guess and the random number
if guess == GUESS:
print(f"{guess} is the correct guess")
elif guess > GUESS:
print(f"{guess} is too high")
#Count dowm
for _ in range(5, 1, -1):
print(f"You have {_-1} attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
if guess == GUESS:
print(f"{guess} is the correct guess")
break
elif guess > GUESS:
print(f"{guess} is too high")
elif guess < GUESS:
print(f"{guess} is too low")
elif guess < GUESS:
print(f"{guess} is too low")
#Count dowm
for _ in range(5, 1, -1):
print(f"You have {_-1} attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
if guess == GUESS:
print(f"{guess} is the correct guess")
break
elif guess > GUESS:
print(f"{guess} is too high")
elif guess < GUESS:
print(f"{guess} is too low")
except ValueError:
print("Please input a number")
elif difficulty == "easy":
#TODO 4.1: User inputs the guesses the random number
try:
print("You have 10 attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
#TODO 4.2: Compare the guess and the random number
if guess == GUESS:
print(f"{guess} is the correct guess")
elif guess > GUESS:
print(f"{guess} is too high")
#Count dowm
for _ in range(10, 1, -1):
print(f"You have {_-1} attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
if guess == GUESS:
print(f"{guess} is the correct guess")
break
elif guess > GUESS:
print(f"{guess} is too high")
elif guess < GUESS:
print(f"{guess} is too low")
elif guess < GUESS:
print(f"{guess} is too low")
#Count dowm
for _ in range(10, 1, -1):
print(f"You have {_-1} attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
if guess == GUESS:
print(f"{guess} is the correct guess")
break
elif guess > GUESS:
print(f"{guess} is too high")
elif guess < GUESS:
print(f"{guess} is too low")
#I probably have to use exceptions
#So im going to do a google search real quick
#value errors
except ValueError:
print("Please input a number")
In pseudo code, here's an example of one function that might be useful:
function CheckGuess (INTEGER guess, INTEGER answer) returns an STRING
if guess > answer
return "too high"
if guess < answer
return "too low"
else
return "exactly"
Now, keeping in mind that a function accepts 0 or more inputs and always returns single output, and that output should always be the same, given the same input, lets see how this can be used as a functional object.
if CheckGuess(7, 10) != "exactly"
guesses = guesses - 1;
This is only one way of dozens that could be useful. Hope this helps!
this could work, though i might have missed some functionality.:
def prompt(prompt):
prompt(input)
def guessing_game:
num_to_guess = random.randint(1,100)
while number_of_guesses > 0:
os.system("cls")
guessed_number = prompt("guess between 1 and 100")
if gessed_number == num_to_guess:
os.system("cls")
number_of_guesses = 0
print("you got it!")
else:
if number_guessed < num_to_guess:
os.system("cls")
print("to low...")
number_of_guesses =- 1
else:
os.system("cls")
print("too high...")
number_of_guesses =- 1
if number_of_guesses == 0:
print("you lost...")
quit()
if this dosent work, check for typos.

Counting Game Try/Except and calculating the users attempts

I am creating a python random counting game. I'm having some difficulties with certain parts. Can anyone here review my code? I'm having difficulty with trying to implement a try/except and a tries function that counts the user's attempts. I also have to verify that the number is a legitimate input and not a variable. So far I've gotten this far and its coming along good. I just need alittle help ironing out a few things. Thanks guys you rock.
Here is the code below:
import random
def main():
start_game()
play_again()
tries()
print("Welcome to the number guessing game")
print("I'm thinking of a number between 1 and 50")
def start_game():
secret_number = random.randint(1,50)
user_attempt_number = 1
user_guess = 0
while user_guess != secret_number and user_attempt_number < 5:
print("---Attempt", user_attempt_number)
user_input_text = input("Guess what number I am thinking of: ")
user_guess = int(user_input_text)
if user_guess > secret_number:
print("Too high")
elif user_guess < secret_number:
print("Too low")
else:
print("Right")
user_attempt_number += 1
if user_guess != secret_number:
print("You ran out of attempts. The correct number was"
+str(secret_number)+ ".")
def play_again():
while True:
play_again = input("Do you want to play again?")
if play_again == 'yes':
main()
if play_again =='no':
print("Thanks for playing")
break
def tries():
found= False
max_attempts=50
secret_number = random.randint(1, 50)
while tries <= max_attempts and not found:
user_input_text = start_game()
user_guess_count=+1
if user_input_text == secret_number:
print("It took you {} tries.".format(user_guess_count))
found = True
main()
Try this method:
def play_game():
print("Enter the upper limit for the range of numbers: ")
limit = int(input())
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
count = 1 #new line
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
count = count+

I don;t understand what is wrong with this code

Im getting a syntax error for elif option ==2:. I was wondering what I need to do to fix it. I followed the pseudocode my professor gave us but it still won't run. I'm wondering if I shouldn't have used elif or maybe something about the indentation is off.
import random
print("Welcome to the guess my number program")
while True:
print("1. You guess the number")
print("2. You type a number and see if the computer can guess it")
print("3. Exit")
option = int(input("Please enter your number here: "))
if option ==1:
#generates a random number
mynumber = random.randint(1,11)
#number of guesses
count = 1
while True:
try:
guess = int(input("Guess a number between 1 and 10:"))
while guess < 1 or guess > 10:
guess = int(input("Guess a number between 1 and 10:")) # THIS LINE HERE
except:
print("Numbers Only")
continue
#prints if the number you chose is too low and adds 1 to the counter
if guess < mynumber:
print("The number you chose is too low")
count= count+1
#prints if the number you chose is too high and adds 1 to the counter
elif guess > mynumber:
print("The number you choose is too high")
count = count+1
#If the number you chose is correct it will tell you that you guessed the number and how many attempts it took
elif guess == mynumber:
print("You guessed it in " , count , "attempts")
break
elif option == 2:
number = int(input("Please Enter a Number: "))
count = 1
while True:
randomval = random.randint(1,11)
if (number < randomval):
print("Too high")
elif (number > randomval):
print("Too low")
count = count+1
elif (number==randomval):
print("The computer guessed it in" + count + "attempts. The number was" + randomval)
break
else:
break
The problem is simple. There is no continuity between if option == 1 and elif option == 2, because of the in between while loop. What you have to do is remove the el part of elif option == 2 and just write if option == 2.
I haven't tested the whole program myself. But at a glance, this should rectify the problem.
Please comment if otherwise.

Guessing random number game python

My program is supposed to ask the user to guess a number between 0 and 100 however I can't seem to get the output right. At the moment if the the User number is greater than the random number, it prints out an infinite amount of "Your number is too high." Also if the first UserGuess is low, then all the following numbers will have the same prompt: ("Your number is too low") despite them being actually bigger than the random number. I have no idea what I am doing wrong. Any help would be greatly appreciated. Thank you!
from random import randint
def main():
guessesTaken = 0
randomNumber = randint(0,100)
#print(randomNumber)
giveUp = -1
UserGuess = int(input("Take a guess" + "(The random number is: " + str(randomNumber) + "): "))
while UserGuess != randomNumber:
guessesTaken += 1
if UserGuess < randomNumber:
UserGuess = int(input("Your guess is too high.Try again: "))
elif UserGuess > randomNumber:
UserGuess = int(input("Your guess is too high.Try again: "))
elif UserGuess == randomNumber or UserGuess == giveUp:
break
if UserGuess == randomNumber:
guessesTaken = str(guessesTaken)
print("Yes, that is right!")
print("It took you " + guessesTaken + " guesses")
if UserGuess == giveUp:
guessesTaken = str(guessesTaken)
randomNumber = str(randomNumber)
print("Better luck next time.")
print("You tried"+ guessesTaken + " guesses")
return
print (main())
if __name__ == "__main__":
main()
You need to get more user input once you're inside the loop. Consider
UserGuess = None
while UserGuess != randomNumber:
UserGuess = int(input("Take a guess" + "(The random number is: " + str(randomNumber) + "): "))
guessesTaken += 1
....
As it stands, you're taking only the first guess. Then you're repeatedly reevaluating it. Since there's no chance for the user to change their guess, it loops infinitely.
Also, you'll want to change up the order of your if/elifs.
As it stands, the structure is
if guess (is too low)
if the guess (is not too low), and (is too high)
if the guess (is not too low), and (is not too high), and (is correct) or (is 'give up')
A quick way to get it working would be
if UserGuess == randomNumber or UserGuess == giveUp:
...
elif UserGuess > randomNumber:
...
elif UserGuess < randomNumber:
....

Asking the user if they want to play again [duplicate]

This question already has answers here:
Ask the user if they want to repeat the same task again
(2 answers)
Closed 4 years ago.
Basically it's a guessing game and I have literally all the code except for the last part where it asks if the user wants to play again. how do I code that, I use a while loop correct?
heres my code:
import random
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
while guess == number:
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == yes:
guess= eval(input("Enter your guess between 1 and 1000 "))
if again == no:
break
One big while loop around the whole program
import random
play = True
while play:
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
play = False
separate your logic into functions
def get_integer_input(prompt="Guess A Number:"):
while True:
try: return int(input(prompt))
except ValueError:
print("Invalid Input... Try again")
for example to get your integer input and for your main game
import itertools
def GuessUntilCorrect(correct_value):
for i in itertools.count(1):
guess = get_integer_input()
if guess == correct_value: return i
getting_close = abs(guess-correct_value)<10
if guess < correct_value:
print ("Too Low" if not getting_close else "A Little Too Low... but getting close")
else:
print ("Too High" if not getting_close else "A little too high... but getting close")
then you can play like
tries = GuessUntilCorrect(27)
print("It Took %d Tries For the right answer!"%tries)
you can put it in a loop to run forever
while True:
tries = GuessUntilCorrect(27) #probably want to use a random number here
print("It Took %d Tries For the right answer!"%tries)
play_again = input("Play Again?").lower()
if play_again[0] != "y":
break
Don't use eval (as #iCodex said) - it's risky, use int(x). A way to do this is to use functions:
import random
import sys
def guessNumber():
number=random.randint(1,1000)
count=1
guess= int(input("Enter your guess between 1 and 1000: "))
while guess !=number:
count+=1
if guess > (number + 10):
print("Too high!")
elif guess < (number - 10):
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = int(input("Try again "))
if guess == number:
print("You rock! You guessed the number in ", count, " tries!")
return
guessNumber()
again = str(input("Do you want to play again (type yes or no): "))
if again == "yes":
guessNumber()
else:
sys.exit(0)
Using functions mean that you can reuse the same piece of code as many times as you want.
Here, you put the code for the guessing part in a function called guessNumber(), call the function, and at the end, ask the user to go again, if they want to, they go to the function again.
I want to modify this program so that it can ask the user whether or not they want to input another number and if they answer 'no' the program terminates and vice versa. This is my code:
step=int(input('enter skip factor: '))
num = int(input('Enter a number: '))
while True:
for i in range(0,num,step):
if (i % 2) == 0:
print( i, ' is Even')
else:
print(i, ' is Odd')
again = str(input('do you want to use another number? type yes or no')
if again = 'no' :
break

Categories