How To Limit The Times a User Could Input - python-3.x

Hi I'm a beginner Making a Game Where The Program Generates a random Number And The User Needs To Guess The Number. If They Fail 5 Times They Lose. I Need To Count How Many Times The User Can Enter And If It Reaches 5 And Print You Lost And restart.
Something Like This
cnt = 0
if cnt >= 5:
print("You Lost")
pass

You need :
import random
op_number = random.randint(1,20)
# print(op_number)
number = int(input("Guess a number between 1 to 20 : "))
count=0
while True:
if count == 5:
print("You Lose.")
break
count+=1
if op_number == number:
print("You won")
break
else:
print("Incorrect guess. {} attempts left.".format(5-count))
number = int(input("Guess a number between 1 to 20 : "))

Related

Counting and Error Handling Block Guessing Game

Could you, please, help me to understand how should I use try/except block and count tries at the same time.
Here is the code without try/except block (it seems it's working fine):
import random
number = random.randint(1, 10)
tries = 3
name = input('Hi! What is your name?\n')
answer = input(f'{name}, let\'s play a game! Yes or No?\n')
if answer == 'Yes':
print(f'But be aware: you have only {tries} tries!\nReady?')
chat = input('')
print('Ok, guess a number from 1 to 10!')
while tries != 0:
choice = int(input('Your choice: '))
tries -= 1
if choice > number:
print('My number is less!')
elif choice < number:
print('My number is higher!')
else:
print('Wow! You won!')
break
print(f'You have {tries} tries left.')
if tries == 0 and choice != number:
print(f'Sorry, {name}, you lost... It was {number}. Try next time. Good luck!')
else:
print('No problem! Let\'s make it another time...')
This one is with try/except block.. Not sure where should I place 'choice' variable and where count 'tries', it keeps looping and looping:
import random
number = random.randint(1, 10)
tries = 3
name = input('Hi! What is your name?\n')
answer = input(f'{name}, let\'s play a game! Yes or No?\n')
if answer == 'Yes':
print(f'But be aware: you have only {tries} tries!\nReady?')
chat = input('')
print('Ok, guess a number from 1 to 10!')
while True:
try:
choice = int(input('Your choice: '))
if 0 < choice < 11:
while tries != 0:
tries -= 1
if choice > number:
print(f'My number is less!')
elif choice < number:
print(f'My number is higher!')
else:
print('Wow! You won!')
break
print(f'You have {tries} tries left.')
if tries == 0 and choice != number:
print(f'Sorry, {name}, you lost... It was {number}. Try next time. Good luck!')
else:
print(f'Hey {name}, I said, print a number from 1 to 10!')
except ValueError:
print('Please, enter a number!')
else:
print('No problem! Let\'s make it another time...')
Thanks!

Python3: How to loop my dice roller program back to the start

Writing my first solo program with no help from teacher or group, a simple code that can act as a D&D dice roller for any type or number of dice a user requires.
I've been working on it for about four hours, and I'm stuck on the last thing I want to do which is loop it back to the beginning instead of just ending when a user doesn't reroll the already chosen dice, I'd like it so it starts again from the top so the player can input a new dice value and number of rolls generated without closing the program and rerunning it.
import random
try:
min = 1
max = int(input("Enter the highest value of dice to be rolled: "))
except:
print("Your input was invalid, program rolled a d20 by default")
min = 1
max = 20
again = True
number_of_dice = int(input("Enter number of dice to roll: "))
for i in range(number_of_dice - 1):
print(random.randint(min, max))
while again:
print(random.randint(min, max))
reroll = input("Roll again? (y/n): ")
if reroll.lower() == "y" or reroll.lower() == "yes":
for i in range(number_of_dice - 1):
print(random.randint(min, max))
else:
print("Thank you")
break
You might try something like:
import random
while True:
try:
min = 1
max = int(input("Enter the highest value of dice to be rolled or 0 to exit: "))
except:
print("Your input was invalid, program rolled a d20 by default")
min = 1
max = 20
if max == 0:
break
if max < 0:
continue
again = True
number_of_dice = int(input("Enter number of dice to roll: "))
for i in range(number_of_dice - 1):
print(random.randint(min, max))
while again:
print(random.randint(min, max))
reroll = input("Roll again? (y/n): ")
if reroll.lower() == "y" or reroll.lower() == "yes":
for i in range(number_of_dice - 1):
print(random.randint(min, max))
else:
print("Thank you")
break
Also, I would suggest renaming "min" and "max" as they are reserved keywords

Unable to record how many times my while loop runs- Python3

I am working on a number guessing game for python3 and the end goal of this is to show the user if they play more than one game that they'll receive an average number of guesses. However, I am unable to record how many times the game actually runs. Any help will do.
from random import randint
import sys
def guessinggame():
STOP = '='
a = '>'
b = '<'
guess_count = 0
lowest_number = 1
gamecount = 0
highest_number = 100
while True:
guess = (lowest_number+highest_number)//2
print("My guess is :", guess)
user_guess = input("Is your number greater than,less than, or equal to: ")
guess_count += 1
if user_guess == STOP:
break
if user_guess == a:
lowest_number = guess + 1
elif user_guess == b:
highest_number = guess - 1
print("Congrats on BEATING THE GAME! I did it in ", guess_count, "guesses")
PLAY_AGAIN = input("Would you like to play again? y or n: ")
yes = 'y'
gamecount = 0
no = 'n'
if PLAY_AGAIN == yes:
guessinggame()
gamecount = gamecount + 1
else:
gamecount += 1
print("thank you for playing!")
print("You played", gamecount , "games")
sys.exit(0)
return guess_count, gamecount
print('Hello! What is your name?')
myname = input()
print('Well', myname, ', I want you to think of number in your head and I will guess it.')
print("---------------------------------------------------------------------------------")
print("RULES: if the number is correct simply input '='")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is GREATER then the output, input '>'")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is LESS then the output, input '<'")
print("---------------------------------------------------------------------------------")
print(" ALRIGHT LETS PLAY")
print("---------------------------------------------------------------------------------")
guessinggame()
guess_count = guessinggame()
print(" it took me this many number of guesses: ", guess_count)
## each game the user plays is added one to it
## when the user wants to the game to stop they finish it and
## prints number of games they played as well as the average of guess it took
## it would need to take the number of games and add all the guesses together and divide it.
It is because you are either calling guessinggame() everytime user wants to play again or you are exiting the program. Also you are setting gamecount to 0 every time you call guessinggame(). You should move gamecount declaration and initialization out of your function. Also increment gamecount before you call guessinggame().

While Loop complication in guess the number game

So I am making a guess the number game in Python 3
After the whole process, I want my while loop to generate another number so that I can start the game again without running the program again.
Please let me know what I'm doing wrong, and if you could provide me with some insight on how to use the while loop, it'll be much appreciated.
Here's the code :
import random
while True:
number = random.randint(1, 1000)
count = 0
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
Not sure if the code you pasted was a typo (on indentation), but I may have accidentally changed your implementation.
Regardless, you should just add another while loop, and a break condition when the user gets it right.
import random
while True:
number = random.randint(1, 1000)
count = 0
while True: # Added, and added another layer of indentation
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
break # Added
In doing so, the code will keep looping to guess the correct number until they are correct. And then generate a new number to guess. However this code will never end unless you add another breaking condition (such as setting a flag the while loop will check to break out of the outer loop.
I wrote some quick code that prompts the user if they want to continue playing or not and then loops through and continues the game with a new number if they want to. I also fixed some minor bugs. Your count kept getting reset in the loop so it would always say you found it in 1 try.
import random
def promptUser():
user_continue = input("Do you want to continue playing? y/n")
if (user_continue == 'y'):
number = random.randint(1, 10)
game(0, number)
def game(count, number):
while True:
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
promptUser()
break
promptUser()

Basic Python Programming Issue

I am new to this website so apologies if I have formatted my code wrong. I am having some trouble with my program; I want to have Player One able to re-enter their number if their first entry was greater than ten. My program seems to end after the first if statement.
Is there any particular statement I could use to get this job done?
Thanks.
#Program that gives Player2 five guesses to guess Player1's number.
import time
Number_To_Guess = int(input('Player One Enter Your Chosen Number: '))
if Number_To_Guess > 10:
print('Your Number Must Be Less Than 10')
elif Number_To_Guess < 10:
Player_Two_Guess = int(input('Player Two Guess The Number: '))
time.sleep(3)
Program that gives Player2 five guesses to guess Player1's number.
This will work until user got right guess:
import time
Number_To_Guess = int(input('Player One Enter Your Chosen Number: '))
if Number_To_Guess > 10:
print('Your Number Must Be Less Than 10')
elif Number_To_Guess < 10:
Player_Two_Guess = 0
TotalGuesses = 0
while Player_Two_Guess != Number_To_Guess and TotalGuesses < 5:
TotalGuesses += 1
Player_Two_Guess = int(input('Player Two Guess The Number: '))
time.sleep(3)
But i would reduce the sleep time :D
Added a counter to reduce the number of guesses to 5.
An infinite loop will do the work:
while True:
Number_To_Guess = int(input('Player One Enter Your Chosen Number: '))
if Number_To_Guess > 10:
print('Your Number Must Be Less Than 10')
else:
break
Player_Two_Guess = int(input('Player Two Guess The Number: '))

Resources