how could I create restriction in input when input is 100 above - python

There are I have two problem please help
problem 1 - input should be integer 1-100 rand_num = random.randint(1,100) if input goes 100 above then show enter valid number 1 to 100 how could I achieve this please help
Thanks!
and also Could please give me a another suggestion to make my project more better.
import random
LIVES = 10
SCORE = 0
HIGH_SCORE = 0
print("\t\t =============> Welcome to the number guessing game developed by Python <===============\n")
print("You have only 10 lives to guessing the number\n\
")
rand_num = random.randint(1,100)
print(rand_num)
while LIVES >=0:
try:
user = int(input("Choose a number between 1-100 : "))
if user == rand_num:
print("Congratulations You guessed it right.")
SCORE=11-LIVES
if SCORE > SCORE:
SCORE += HIGH_SCORE
print(f"Your score is {SCORE} ")
print(f"The Score Is {HIGH_SCORE}")
break
elif user > rand_num:
LIVES-=1
print(f"Too high! Please guess lower number.\n Current Lives= {LIVES}")
elif user < rand_num:
LIVES-=1
print(f"Too Low! Please guess higher number.\n Current Lives= {LIVES}")
except Exception as e:
print(e)

I added a few embellishments to your code so that it could be played more than once.
import random
LIVES = 10
SCORE = 0
HIGH_SCORE = 0
DONE = False
print("\t\t =============> Welcome to the number guessing game developed by Python <===============\n")
print("You have only 10 lives to guessing the number\n")
rand_num = int(random.randint(1,100))
print(rand_num)
while True:
while LIVES >=0:
try:
user_string = input("Choose a number between 1-100 : ")
if user_string == "Q" or user_string == "q":
DONE = True
break
user = int(user_string)
if user > 100 or user < 1: # To account for invalid guesses
print("Guesses must be from 1 to 100")
continue
if user == rand_num:
print("Congratulations You guessed it right.")
SCORE = LIVES
print(f"Your score is {SCORE} ")
if SCORE > HIGH_SCORE:
print("This is also a new high score!!!")
HIGH_SCORE = SCORE
print(f"The Current High Score Is {HIGH_SCORE}")
break
elif user > rand_num:
LIVES-=1
print(f"Too high! Please guess lower number.\n Current Lives= {LIVES}")
elif user < rand_num:
LIVES-=1
print(f"Too Low! Please guess higher number.\n Current Lives= {LIVES}")
except Exception as e:
print(e)
if (DONE == True):
break
# Let's do this again
print("\t\t =============> Welcome to the number guessing game developed by Python <===============\n")
print("You have only 10 lives to guessing the number\n")
rand_num = int(random.randint(1,100))
print(rand_num)
LIVES = 10
SCORE = 0
First off, I ensured that the user input was an integer by wrapping the value inside the "int" function. Next, per your request, I added a range test of the entered value so that it only allows guesses from "1" to "100". Then, I also added in another "while" loop to provide for a continuous number of games. That way, the number of tries could be kept and compared to any previous high score to see if a new high score was achieved. In order to exit the game and the highest level "while" loop a test is made to see if the user has entered "Q" or "q" to quit (you might want to add verbiage to the program to direct the user).
Anyway, try those out and see if that is close to what your are trying to accomplish.

Related

creating a python number guessing game

SUPER new to programming so bear with me, please. I am taking my first ever programming class and for a project, I was given a list of requirements I need to fulfill, creating a simple number guessing game has been the only thing I've not had a lot of trouble with so I decided to give it a go.
(i need 1 class, function, dictionary or list, for loop, and while loop) What I, well at least have tried to make is a guessing game that gives a limit of 2 guesss for a # between 0 and 10, any help would be greatly appreciated. :)
import random
class Player:
player = ""
playerscore = 0
def gamestart(self):
self.number = random.randint(0,7)
self.guesss = 0
self.list = []
self.limit = 3
print()
print("Guess what number I'm thinking off")
print()
print("Might even give you a hit if you do well enough")
print()
while self.limit > 0:
self.player_guess = int(input("Well? What are you waiting for? Start guessing:"))
print()
if self.player_guess > 7 or self.player_guess < 0:
print("Wow that was a terrible guess, think harder or we might be here all week long")
print("also,", self.player_guess , "is not in the range...")
print("Becareful though, you only have", self.limit, "guesss left")
elif self.player_guess > self.number:
self.guesss += 1
self.limit-= 1
print("WRONG")
print(self.player, "You only have", self.limit, "guesss left")
self.list.append(self.player_guess)
elif self.player_guess < self.number:
self.guesss += 1
self.limit -= 1
print("oh oh... wrong again!")
print()
print(self.player, "You only have", self.limit, "guesss left.")
self.list.append(self.player_guess)
else:
self.limit -= 1
self.playerscore += 1
self.list.append(self.player_guess)
print()
print("wow, you actually got it right")
print()
print(self.player_guess, "IS THE CORRECT ANSWER!")
print()
print("you only had",self.limit,"left too...")
print("Lets see all the numbers you guessed")
print()
for i in self.list:
print(i)
self.list.clear()
I found the question confusing, however the following code should work as a number guessing game, hope I answered your question.
import random
game = "true"
guesses = 2
while game == "true":
comp_number = int(random.uniform(1,8))
print("I have randomly selected a number between 1 and 7 (inclusive), you have 2 attempts to guess the number.")
while guesses > 0:
if guesses == 2:
turn = "first"
else:
turn = "final"
guess = int(input("Please submit your "+turn+" guess:"))
while guess < 1 or guess > 7:
print("Invalid guess, remember my number is between 1 and 7 (inclusive)")
guess = int(input("Resubmit a valid guess:"))
if guess == comp_number:
print("Congratulations you guessed my number, you win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break
else:
print("Incorrect number, try again.")
guesses -= 1
print("You where unable to guess my number, I win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break

Guess the number, play again

I'm making a guess the number game. My code is almost complete but I need to make it so that the program asks the player if they want to play again and then restarts. Could someone help me with how I should go about that? I tried making a new function ex. def game_play_again and then call the game_play() function but it's not reseting the attempts which leads to it not looping correctly.
This is my code right now
import random
MIN = 1
MAX = 100
attempts = 5
win = False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
#print game instructions
def game_start():
print(f"Im thinking of a number between {MIN} and {MAX}. Can you guess it within
{attempts} attempts? ")
input("Press enter to start the game ")
#process user input
def game_play():
global number, attempts, last_hint, win
while attempts > 0:
print()
print(f"You have {attempts} {'attempts' if attempts > 1 else 'attempt'} left.")
if attempts == 1:
print(f"This is your last chance. So i'll give you one more hint. Its's an {last_hint} number.")
while True:
try:
guess = int(input("Try a lucky number: "))
if guess in range(MIN, MAX+1):
break
else:
print(f"Please enter numbers between {MIN} and {MAX} only!")
except ValueError:
print("Plese enter numbers only!")
if guess == number:
win = True
break
if attempts == 1:
break
if guess > number:
if guess-number > 5:
print("Your guess is too high. Try something lower.")
else:
print("Come on you are very close. Just a bit lower.")
else:
if number-guess > 5:
print("Your guess is too low. Try something higher.")
else:
print("Come on you are very close. Just a bit higher.")
attempts -= 1
#print game results
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
game_start()
game_play()
game_finish(win)
You can simply reset your variables to initial values and then call game_play()
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
want_play_again = int(input("Want play again? [1-Yes / 2-No]"))
if want_play_again == 1:
game_play_again()
else:
print("Bye")
/
def game_play_again():
attempts = 0
win = False
game_play()
Within a while(True) loop, write a menu driven statement asking the user if they want to repeat. If they do, initialise values and call game methods. If they do not, break the loop.
pseudocode:
while(True):
choice = input('play again? y/n)
if choice=='y':
attempts, win = 5, False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
game_start()
game_play()
game_finish()
elif choice=='n':
break
else:
print('invalid input')
The above code should be in main, with all methods within its scope.
Better yet, in place of all the initializations, add an init() method declaring them and call them when necessary.
The indentation in the code you have submitted is faulty, so I'm not sure if a related error is involved.

My guessing game repeatedly prints in console if you guess incorrectly

I am new to python and built this for practice. How come if you guess incorrectly the print function runs repeatedly. Additionally, if you make a correct guess the corresponding print function doesn't run.
import random
print("Welcome to the Guessing Game")
rand = random.randint(1, 9)
count = 0
running = True
guess = int(input("Pick a number from 1 - 9"))
while guess != rand:
count += 1
if guess > rand:
print("Too High")
running = False
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
running = False
elif guess < rand:
print("Too Low")
If the number is incorrect we need to ask the player to guess again. You can use break to avoid having an infinite loop, here after 5 guesses.
The conversion of the input to integer will throw an error if the entry is not a valid number. It would be good to implement error handling.
import random
print("Welcome to the Guessing Game")
rand = random.randint(1, 9)
count = 0
running = True
guess = int(input("Pick a number from 1 - 9"))
while guess != rand:
count += 1
if guess > rand:
print("Too High")
running = False
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
running = False
break
elif guess < rand:
print("Too Low")
if i >= 5:
break
guess = int(input("Try again\nPick a number from 1 - 9"))
in the first while loop, when player guesses the correct number we need to break.
Also for counting the number of rounds that player played we need a new while loop based on count.
When we use count in our code we should ask player every time that he enters the wrong answer to guess again so i used input in the while
import random
print("Welcome to the Guessing Game:")
rand = random.randint(1, 9)
count = 0
while count!=5:
guess = int(input("Pick a number from 1 - 9:"))
count += 1
if guess > rand:
print("Too High")
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
break
elif guess < rand:
print("Too Low")
print('you lost')

Python program ends even if the condition are not met

The condition is that the program will end:
-if the balance is less than or equal to zero.
-if the balance is greather than or equal to 200.
But the problem is that it ends after I input 1 or 2 (1 for heads and 2 for tails) and you need to run it again and the balance is not saved.
Here is my code:
import random
def Guess_Check(guess,balance): #function for guess check
coin_flip = int( random.choice([1,2]))
if coin_flip == 1:
print("It's heads!!")
else:
print("It's tail!")
if guess == coin_flip: #if guess is correct
print("Congrats you guessed right, You won $9.")
balance = balance+9
else: #if guess is wrong
print("Sorry your guess was wrong, You loss $10.")
balance = balance-10
print("Avalilable balanace is :", balance)
return (balance)
def Balance_Check(Balance): #Balance Check
if Balance <= 10: #we can't play the game if balance is below $10
print("Sorry!! You run out of money.")
return(1)
if Balance >=200:
print("Congrats!! You reached your Target $200.")
return(1)
balance = 100 #beginning amount
while True:
bal = Balance_Check(balance) #check the available balance
if bal==1:
break
print("Guess heads by entering 1 or tails by entering 2 for this coin flip.") #Asking the player to guess
guess = int(input())
Balance = Guess_Check(guess,balance)
You messed up a few of the things like which balance to take at the right time when to stop the loop etc.
Here's the code if you want to take the user input once and then check the guess:
import random
def Guess_Check(guess,balance): #function for guess check
coin_flip = random.choice([1,2])
if coin_flip == 1:
print("It's heads!!")
else:
print("It's tail!")
if guess == coin_flip: #if guess is correct
print("Congrats you guessed right, You won $9.")
balance = balance+9
else: #if guess is wrong
print("Sorry your guess was wrong, You loss $10.")
balance = balance-10
print("Avalilable balanace is :", balance)
return (balance)
def Balance_Check(Balance): #Balance Check
if Balance <= 10: #we can't play the game if balance is below $10
print("Sorry!! You run out of money.")
return 0
elif Balance >=200:
print("Congrats!! You reached your Target $200.")
return 1
balance = 100 #beginning amount
print("Guess heads by entering 1 or tails by entering 2 for this coin flip.") #Asking the player to guess
guess = int(input())
while Balance_Check(balance) not in [0,1]: # You need to run the loop till balance becomes 0 or 200
balance = Guess_Check(guess,balance)
But if you want to take user input on every chance use:
import random
def Guess_Check(guess,balance): #function for guess check
coin_flip = random.choice([1,2])
if coin_flip == 1:
print("It's heads!!")
else:
print("It's tail!")
if guess == coin_flip: #if guess is correct
print("Congrats you guessed right, You won $9.")
balance = balance+9
else: #if guess is wrong
print("Sorry your guess was wrong, You loss $10.")
balance = balance-10
print("Avalilable balanace is :", balance)
return (balance)
def Balance_Check(Balance): #Balance Check
if Balance <= 10: #we can't play the game if balance is below $10
print("Sorry!! You run out of money.")
return 0
elif Balance >=200:
print("Congrats!! You reached your Target $200.")
return 1
balance = 100 #beginning amount
while Balance_Check(balance) not in [0,1]: # You need to run the loop till balance becomes 0 or 200
guess = int(input("Guess heads by entering 1 or tails by entering 2 for this coin flip."))
balance = Guess_Check(guess,balance)
Sample output: (Not complete output as it was long)
Congrats you guessed right, You won $9.
Avalilable balanace is : 206
Congrats!! You reached your Target $200.

I am trying to replay the game when I run out of guesses (Play again when I run out of gusses or find the right answer)

I am trying to reply to this game and store the count in the passed memory but, any time I run the code again the game starts from scratch and the previous score is lost.
How can I store and continue from the past round.
import random
MAX_GUESSES = 5 #max number of guesses allowed
MAX_RANGE = 20 #highest possible number
#show introductionpygame
print("welcome to my franchise guess number game")
print("guess any number between 1 and", MAX_RANGE)
print("you will have a range from", MAX_GUESSES, "guesses")
#choose random target
target = random.randrange(1, MAX_RANGE + 1)
#guess counter
guessCounter = 0
#loop fovever
while True:
userGuess = input("take a guess:")
userGuess =int(userGuess)
#increment guess counter
guessCounter = guessCounter + 1
#if user's guess is correct, congratulate user, we're done
if userGuess == target:
print("you got it la")
print("it only took you",guessCounter, "guess(es)")
break
elif userGuess < target:
print("try again, your guess is too low.")
else:
print(" your guess was too high")
#if reached max guesses, tell answer correct answer, were done
if guessCounter == MAX_GUESSES:
print(" you didnt get it in ", MAX_GUESSES, "guesses")
print("the number was", target)
break
print("Thanks for playing ")
#main code
while True:
playOneRound() #call a function to play one round of the game
goAgain = input("play again?(press ENTER to continue, or q to quit ):")
if goAgain == "q":
break
you forgot to mention the function name playOneRound. The code below works fine.
import random
MAX_GUESSES = 5 # max number of guesses allowed
MAX_RANGE = 20 # highest possible number
# show introductionpygame
print("welcome to my franchise guess number game")
print("guess any number between 1 and", MAX_RANGE)
print("you will have a range from", MAX_GUESSES, "guesses")
def playOneRound():
# choose random target
target = random.randrange(1, MAX_RANGE + 1)
# guess counter
guessCounter = 0
# loop fovever
while True:
userGuess = input("take a guess:")
userGuess = int(userGuess)
# increment guess counter
guessCounter = guessCounter + 1
# if user's guess is correct, congratulate user, we're done
if userGuess == target:
print("you got it la")
print("it only took you", guessCounter, "guess(es)")
break
elif userGuess < target:
print("try again, your guess is too low.")
else:
print(" your guess was too high")
# if reached max guesses, tell answer correct answer, were done
if guessCounter == MAX_GUESSES:
print(" you didnt get it in ", MAX_GUESSES, "guesses")
print("the number was", target)
break
print("Thanks for playing ")
# main code
while True:
playOneRound() # call a function to play one round of the game
goAgain = input("play again?(press ENTER to continue, or q to quit ):")
if goAgain == "q":
break

Categories

Resources