Python simple loop doesnt work as intended - python

i just dont undersand why it dosent work and what i need to do to fix it. the goal is to make a counting game so i any tips one a restart button would be great aswell. there is no error i just dosent get out of the first loop.
import random
secrectnumber = random.randint(1,100)
nummberguess = 5
print("guess a Number between 1 and 100")
number = False
wrongguess = True
while wrongguess and nummberguess>0:
guess=input()
print( "writte a number")
if guess.isdigit():
guess=int(guess)
number = True
wrongguess = False
else:
print("invalid input")
while number:
nummberguess=nummberguess-1
if guess== secrectnumber:
print("you did it")
break
elif secrectnumber>guess:
print("the number is higeher")
wrongguess = True
elif secrectnumber<guess:
print("the number is lower")
wrongguess = True

There's 2 things wrong with your code based on what you wrote:
If input is not a digit, the loop will run forever. This is because the first part of the condition, while wrongguess is always true and nummberguess>0 is also always true because you're not decrementing/incrementing it. What is that supposed to do? Terminate if number_of_guess ≥ 5? You need to add a counter to actually terminate the first loop after max number of guesses is reached or whatever the desired output may be.
The second while loop is redundant. It'll print the same number in guess if the number is not the intended secret number.
To rectify your code, your second chunk of the code should be within the first, without the while loop. Something like this:
import random
secrectnumber = random.randint(1,100)
nummberguess = 5
print("guess a Number between 1 and 100")
number = False
wrongguess = True
while wrongguess and nummberguess>0:
guess=input()
print( "writte a number")
if guess.isdigit():
# this won't work for input = 31, you need to iterate the string instead and check if all characters are digits, something like this:
# sum([x.isdigit() for x in str(guess)]) == len(guess) <-- Number, this won't work for floating point numbers because '3', '.', '1', '4' (3, 1, 4 is digit, but '.' isn't). Just something to think about
guess=int(guess)
number = True
wrongguess = False
else:
print("invalid input")
nummberguess -= 1
if guess== secrectnumber:
print("you did it")
break
elif secrectnumber>guess:
print("the number is higeher")
wrongguess = True
elif secrectnumber<guess:
print("the number is lower")
wrongguess = True

It can be done very simply as :
import random
secrectnumber = random.randint(1, 100)
nummberguess = 5
print("guess a Number between 1 and 100")
for i in range(nummberguess):
guess = input()
if guess.isdigit():
guess = int(guess)
if guess == secrectnumber:
print("you did it")
break
elif secrectnumber > guess:
print("the number is higeher.", end="")
if i == nummberguess -1:
print(" Exhausted !!!")
else:
print(" Try again !!!")
elif secrectnumber < guess:
print("the number is lower.", end="")
if i == nummberguess -1:
print("Exhausted !!!")
else:
print("Try again !!!")

Related

How to use a loop to make something repeat until conditions are met? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 months ago.
I'm trying to make a simple number guessing game. I wanted to try to see if I could do this myself without looking up any answers but I'm very confused on how to keep the game going if the guess is not correct. Here is what I have so far:
import random
#ask user to guess a number:
guess = int(input("Guess a number from 0 to 100: \n"))
#create random number:
computer_number = random.randint(0, 100)
#How can i make this block of code loop to keep on giving the user tries??
if guess == computer_number:
print("You won")
elif guess > computer_number:
print("Try a lower number!")
else:
print("Try a higher number!")
import random
#ask user to guess a number:
#create random number:
computer_number = random.randint(0, 100)
#How can i make this block of code loop to keep on giving the user tries??
while True:
guess = int(input("Guess a number from 0 to 100: \n"))
if guess == computer_number:
print("You won")
break
elif guess > computer_number:
print("Try a lower number!")
else:
print("Try a higher number!")
You could use a while loop to loop the game until a condition is met.
For example:
#create random number:
computer_number = random.randint(0, 100)
while True:
#ask user to guess a number:
guess = int(input("Guess a number from 0 to 100: \n"))
#How can i make this block of code loop to keep on giving the user tries??
if guess == computer_number:
print("You won")
break
elif guess > computer_number:
print("Try a lower number!")
else:
print("Try a higher number!")
it's very easy you just need an while loop:
while condition:
#while condition True run what stands here
So the answer to your question is:
import random
#create random number:
computer_number = random.randint(0, 100)
guess = -1
#we need to firs declare the variables so we can use them in the condition
while guess != computer_number:
#ask user to guess a number:
guess = int(input("Guess a number from 0 to 100: \n"))
if guess == computer_number:
print("You won!")
elif guess > computer_number:
print("Try a lower number!")
else:
print("Try a higher number!")

How to restart this

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")

Project with a python loop program

My son has this project he has to do in python and is stuck.
He needs to make a number guessing game. The code must generate a random secret number between 0 and 10, then give the user 5 attempts to guess that number, each guess if not correct must indicate if it is higher or lower than the secret random number. After each guess the code needs to display text stating what has happened. The code also needs to store all guesses and display them at the end. Needs to be made using loop, if, elif, else and an array or list code.
The attempt so far is below
print("Hi there, lets play a little guessing game. Guess the number between 0 and 10")
from random import randint
x = [randint(0,10)]
counter = 0
guess = input("Enter guess:")
while counter < 5:
print("You have " + str(counter) + " guesses left")
counter = counter +1
if guess == x:
print("Congrats you got it")
break
elif guess > x:
print("Too high")
elif guess < x:
print("Too low")
else:
print("You lost")
break
Any help to correct my sons code would be appreciated as this project is due soon and he cannot access his tutor
This should do it. What the code does is explained in comments below.
You need to do x=randint(0,10) which will assign the random number to a variable, i.e x=4 rather than `x = [randint(0,10)], which assigns the random number to a list ,x=[4]```
Also you need to ask for a guess in the loop, instead of doing it only one before the loop started.
Also you would need to convert the string to an int for comparison i.e. guess = int(input("Enter guess:"))
print("Hi there, lets play a little guessing game. Guess the number between 0 and 10")
#Create a random number
from random import randint
x = randint(0, 10)
counter = 0
won = False
#Run 5 attempts in a loop
while counter<5:
#Get the guess from the user
guess = int(input("Enter guess:"))
counter = counter+1
#Check if the guess is the same, low or high as the random number
if guess == x:
print("Congrats you got it")
won = True
break
elif guess > x:
print("Too high")
elif guess < x:
print("Too low")
print("You have " + str(5 - counter) + " guesses left")
#If you didn't won, you lost
if not won:
print("The number was ", x)
print("You Lost")
So here are the corrections. So x has been initialized as array rather than an integer. So none of the comparisons with guess will be working. Also the counter logic is wrong. Rather than starting from zero, start from 5 which is the maximum number of chances and go from the reverse rather. Then at each if/elif loop append all the guesses and print it in the end.
Here is the corrected code
from random import randint
x = randint(0,10)
print(x)
counter = 5
guesses=[] #initalize an empty list to store all guesses
while counter != 0:
guess = input("Enter guess:")
if guess == x:
print("Congrats you got it")
guesses.append(guess)
break
elif guess > x:
print("Too high")
guesses.append(guess)
elif guess < x:
print("Too low")
guesses.append(guess)
else:
print("You lost")
break
counter = counter-1
print("You have " + str(counter) + " guesses left")
print(guesses)
Edit:
x = [randint(0,10)] wouldn't work as you are creating a list here instead of single guess
print("You have " + str(counter) + " guesses left") is also incorrect. You might instead set counter to 5 and check for counter > 0 and do counter -= 1, that way message can be fixed
Lastly to store all guesses you would need a variable
from random import randint
if __name__ == "__main__":
number_to_guess = randint(0,10)
guesses = []
for c in range(5,0,-1):
guessed = input("Enter guess:")
guessed = guessed.strip()
assert guessed.isnumeric()
guessed = int(guessed)
guesses.append(guessed)
if guessed == number_to_guess:
print("yes")
break
elif guessed > number_to_guess:
print("more")
else:
print("less")
c -= 1
print("pending guesses", c)
print("Expected - ", number_to_guess)
print("All guesses - ", guesses)

Python Guessing Game Reject Invalid User Input

I'm taking my first-ever Python class and, like most Python classes, the last assignment is to create a guessing game from 1-100 that tracks the number of VALID tries. The element that I just cannot get (or find here on stackoverflow) is how to reject invalid user input. The user input must be whole, positive digits between 1 and 100. I can get the system to reject everything except 0 and <+ 101.
The only things I can think to do end up telling me that you can't have operators comparing strings and integers. I keep wanting to use something like guess > 0 and/or guess < 101. I've also tried to create some sort of function, but can't get it to work right.
# Generate random number
import random
x = random.randint(1,100)
# Prompt user for input
print("I'm thinking of a number from 1 to 100")
counter = 0
while True:
guess = input("Try to guess my number: ")
# Check if input is a positive integer and is not 0 or >=101
# this line doesn't actually stop it from being a valid guess and
# counting against the number of tries.
if guess == "0":
print(guess, "is not a valid guess")
if guess.isdigit() == False:
print(guess, "is not a valid guess")
else:
counter += 1
guess = int(guess)
# Begin playing
if guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
print(guess, "is correct! You guessed my number in", counter, "tries!")
import random
x = random.randint(1,100)
# Prompt user for input
print("I'm thinking of a number from 1 to 100")
counter = 0
while True:
guess = input("Try to guess my number: ")
try:
guess = int(guess)
if(100 > guess > 0):
counter += 1
guess = int(guess)
# Begin playing
if guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
print(guess, "is correct! You guessed my number in", counter, "tries!")
break
else:
print("Number not in range between 0 to 100")
except:
print("Invalid input")
# Generate random number
import random
x = random.randint(1,100)
# Prompt user for input
print("I'm thinking of a number from 1 to 100")
counter = 1
while True:
try:
guess = int(input("Try to guess my number: "))
if guess > 0 and guess < 101:
print("That's not an option!")
# Begin playing
elif guess == x:
print(guess, "is correct! You guessed my number in", counter, "tries!")
break
elif guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
counter += 1
except:
print("That's not a valid option!")
My instructor helped me out. (I posted to keep from needing that from the guy who's giving me the grade.) Here is what we came up with. I'm posting it to help out any future Python learner that may have this particular rejecting user input problem.
Thank you guys for posting SO FAST! Even though I needed the instructor's help, I would've looked even more incompetent without your insights. Now I can actually enjoy my holiday weekend. Have a great Memorial Day weekend!!!
import random
x = random.randint(1,100)
print("I'm thinking of a number from 1 to 100.")
counter = 0
while True:
try:
guess = input("Try to guess my number: ")
guess = int(guess)
if guess < 1 or guess > 100:
raise ValueError()
counter += 1
if guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
print(guess, "is correct! You guessed my number in", counter, "tries!")
break
except ValueError:
print(guess, "is not a valid guess")

Getting an "invalid literal for int with base 10" in Python

import random
print("Welcome to RNG Guesser!\n")
gld = random.randrange(1,10)
counter = 0
ccounter = 0
while True:
print("Number of tries: {}".format(counter))
print("Number of correct guesses: {}".format(ccounter))
num = input("Enter a number: ")
if num is "exit":
print("Number of tries: {}".format(counter))
print("Number of correct guesses: {}".format(ccounter))
break
else:
if int(num) is gld:
print("Congratulations, your guessed number {} was right!".format(num))
counter += 1
ccounter += 1
elif int(num) < gld:
print("Pick a higher number!")
counter += 1
else:
print("Pick a lower number!")
counter += 1
Why am I getting the "invalid literal for int" when I type in exit? I tried converting the input variable to int, I tried with an else statement, I tried making 2 variables, one for string one for int, and none of them worked.
I believe the issue is from the line:
if num is "exit"
Is evaluating to False and further down the script when Python tries to convert the literal string exit to an int, it will fail.
Try replacing is with ==
The problem is that is compares two objects to see if they are the same, whereas what want to is to see if the tow objects' values are the same. Check this stack overflow thread for more info.
Assuming that the incorrect indentation in the question is just a copy-paste mistake... try this:
x = input('enter x > ')
print('x == "exit": {}'.format(x == "exit"))
print('x is "exit": {}'.format(x is "exit"))
Here's what happens:
enter x > exit
x == "exit": True
x is "exit": False
Or maybe:
x is "exit": True
The is operator compares object identity but you are trying to compare the contents of two strings.
Note that you cannot give a string with non-numeric characters to int().
Now num is supposed to be a str, and it could be anything from user input. Also note that when you want to evaluate two values, use == instead of is. is is supposed to be used as judging if two things are the same object.
If you want to use if-else, try this:
if num == "exit":
print("Number of tries: {}".format(counter))
print("Number of correct guesses: {}".format(ccounter))
break
elif not num or not all(char.isdigit() for char in num):
print("You are not giving a number.")
else:
if int(num) == gld:
print("Congratulations, your guessed number {} was right!".format(num))
counter += 1
ccounter += 1
elif int(num) < gld:
print("Pick a higher number!")
counter += 1
else:
print("Pick a lower number!")
counter += 1
Here, all(char.isdigit() for char in num) is checking for every character in num to see if they are all numbers. We should be aware that anything could appear in user's input. Only numbers can be converted to int.
We have another solution which is more clear and simple. You may need to read some documents on try...except... in Python.
try:
if int(num) ...
except ValueError:
# num is not able to be converted to int
print("You are not giving a number.")

Categories