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")
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.')
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 !!!")
I made a program that generates a random number between 100 and 999. The user needs to input an integer to guess the random number. The game will only end if the user inputs 0 or has 5 incorrect tries.
How would I modify it such that when the user inputs the answer, the program will tell you whether the integer entered is at the correct position or the correct digit at the wrong position? Like in this example: https://imgur.com/a/CSa3ntd
import random
num = random.randint(100,999)
attempts = 1
while attempts < 6:
guess = int(input("Try #{} - Please enter your guess: ".format(attempts)))
if guess == num:
print("Great! You have gotten the correct number!")
else:
print("Your guess is incorrect")
attempts = attempts + 1
else:
print("The correct number is {}, The game has ended.".format(num))
This code will tell the users which position are correct in case the number and the guess are different.
import random
num = random.randint(100,999)
attempts = 1
print(num)
while attempts < 6:
guess = int(input("Try #{} - Please enter your guess: ".format(attempts)))
if guess == num:
print("Great! You have gotten the correct number!")
break
else:
guess_str = str(guess)
for i, val in enumerate(str(num)):
if guess_str[i] == val:
print("The position num {} is correct".format(i + 1))
print("Your guess is incorrect")
attempts = attempts + 1
else:
print("The correct number is {}, The game has ended.".format(num))
You have two ways of doing this. You may convert your input to a string using str(my_num) and check if str(digit) in str(my_num) and to check if it is in the correct position use str(digit) == str(my_num)[correct_position]
The second way is using divisions and modulu. using (my num // (10 ** position)) % 10 will give you the digit in the position so you could easily compare.
Modify your else statement as :
num = str(num)
guess = str(guess)
correct_digit = 0
correct_digit_position = 0
for i in guess:
if i in num:
correct_digit += 1
if num.index('i') == guess.index('i') :
correct_position += 1
correct_digit -= 1
print(f"Try #{attempts} - {correct_position} correct digit and position, {correct_digit} correct digit but wrong position ")
I am struggling with some simple algorithm which should make python guess the given number in as few guesses as possible. It seems to be running but it is extremely slow. What am I doing wrong. I have read several topics already concerning this problem, but can't find a solution. I am a beginner programmer, so any tips are welcome.
min = 1
max = 50
number = int(input(("please choose a number between 1 and 50: ")))
total = 0
guessed = 0
while guessed != 1:
guess = int((min+max)/2)
total += 1
if guess == number:
print("The number has been found in ",total," guesses!")
guessed = 1
elif guess > number:
min = guess + 1
elif guess < number:
max = guess - 1
Thanks
ps. I am aware the program does not check for wrong input ;)
Your logic is backwards. You want to lower the max when you guess too high and raise the min when you guess too low. Try this:
if guess == number:
print("The number has been found in ",total," guesses!")
guessed = 1
elif guess > number:
max = guess - 1
elif guess < number:
min = guess + 1
Apart from having the logic backwards, you should not be using min and max as variable names. They are python functions. You can also use while True and break as soon as the number is guessed.
while True:
guess = (mn + mx) // 2
total += 1
if guess == number:
print("The number has been found in {} guesses!".format(total))
break
elif guess < number:
mn = guess
elif guess > number:
mx = guess
You will also see by not adding or subtracting 1 from guess this will find the number in less steps.
from random import randint
print('choose a number in your brain and if guess is true enter y else any key choose time of guess: ')
print("define the range (A,B) :")
A = int(input("A: "))
B = int(input("B: "))
time = int(input("time:"))
while time != 0:
ran = randint(A, B)
inp = input(f"is this {ran} ?")
time -= 1
if inp == "y":
print("bla bla bla python wins!")
break
print("NOPE!")
if time == 0:
print("computer game over!")
break
How do I make the loop work so that it will end when you get it right and ask the question again if you get it wrong?
When i guess wrong two or more times it will always say wrong no matter what.
import random;
import sys;
x = random.randint(1, 100);
print(x);
guess = int(input("Guess a number 1 to 100"));
if guess == x:
print("correct");
sys.exit()
while guess != x:
print("wrong");
int(input("Guess a number 1 to 100"));
print(x);
if guess == x:
print("Correct");
sys.exit()
Also what function records the number of times it loops. For example if I guess wrong 10 times then I want to print that I scored a 10.
You have forgotten to assign the second time around to the guess variable
while guess != x:
print("wrong");
guess = int(input("Guess a number 1 to 100")); #look here
print(x);
if guess == x:
print("Correct");
sys.exit()
Missing 'guess=' in the input line in the loop. To record number of times, just increment a variable in the loop.
[ADDENDUM]
import random;
import sys;
x = random.randint(1, 100);
print(x);
count = 1
guess = int(input("Guess a number 1 to 100: "));
while guess != x:
count += 1
guess = int(input("Wrong\nGuess a number 1 to 100: "));
print("Correct - score = "+str(100./count)+"%");
sys.exit(0)
Actually you should change your codes to:
import random
x=random.randint(1,100)
score=0
while True:
guess=int(input("Guess a number 1 to 100: "))
if guess==x:
print ("Correct!")
break
else:
print ("Not correct!")
score+=1
print ("your answers was wrong {} times.".format(score))
Better statements,less codes. Cheers!