Changing random number in python - python

import random
def guess_number_game():
number = random.randint(1, 101)
points = 0
print('You already have ' + str(points) + ' point(s)')
playing = True
while playing:
guess = int(input('Guess the number between 1 and 100: '))
if guess > number:
print('lower')
elif guess < number:
print('Higher')
else:
print('You got it, Good job!!')
playing = False
points += 1
play_again = True
while play_again:
again = input('Do you want to play again type yes/no: ')
if again == 'yes':
playing = True
play_again = False
elif again == 'no':
play_again = False
else:
print('please type yes or no')
print('Now you have ' + str(points) + ' point(s)')
guess_number_game()
i just started to learn python and i made this simple number guessing game, but
if you try to play again you get the same number.
e.g. the number is 78 and you guessed it but you want to play again so you say you want to play again the number is still 78.
so how do i make it so that the number changes everytime someone plays the game

You need to set the number to the random generated number in the loop.
Example:
import random
def guess_number_game():
playing = True
while playing:
number = random.randint(1, 101)
points = 0
print('You already have ' + str(points) + ' point(s)')
playing = True
print(number)
guess = int(input('Guess the number between 1 and 100: '))
if guess > number:
print('lower')
elif guess < number:
print('Higher')
else:
print('You got it, Good job!!')
playing = False
points += 1
play_again = True
while play_again:
again = input('Do you want to play again type yes/no: ')
if again == 'yes':
playing = True
play_again = False
elif again == 'no':
play_again = False
else:
print('please type yes or no')
print('Now you have ' + str(points) + ' point(s)')
guess_number_game()

import random
def guess_number_game():
points = 0
print('You already have ' + str(points) + ' point(s)')
playing = True
play_again=False
number = random.randint(1, 101)
#print(number)
while playing:
guess = int(input('Guess the number between 1 and 100: '))
if guess > number:
print('lower')
elif guess < number:
print('Higher')
else:
print('You got it, Good job!!')
number = random.randint(1, 101)
points += 1
again = input('Do you want to play again type yes/no: ')
if again == 'yes':
playing = True
elif again == 'no':
playing = False
print('Now you have ' + str(points) + ' point(s)')
guess_number_game()

You define your random number outside of the game, set a new random number when someone decides to play again!
import random
def guess_number_game():
number = randbelow(1, 101)
points = 0
print('You already have ' + str(points) + ' point(s)')
playing = True
while playing:
print(number)
guess = int(input('Guess the number between 1 and 100: '))
if guess > number:
print('lower')
elif guess < number:
print('Higher')
else:
print('You got it, Good job!!')
playing = False
points += 1
play_again = True
while play_again:
again = input('Do you want to play again type yes/no: ')
if again == 'yes':
playing = True
play_again = False
number = randbelow(1, 101)
elif again == 'no':
play_again = False
else:
print('please type yes or no')
print('Now you have ' + str(points) + ' point(s)')
guess_number_game()

Related

Computer guessing number python

I'm very new to programming and am starting off with python. I was tasked to create a random number guessing game. The idea is to have the computer guesses the user's input number. Though I'm having a bit of trouble getting the program to recognize that it has found the number. Here's my code and if you can help that'd be great! The program right now is only printing random numbers and won't stop even if the right number is printed that is the problem
import random
tries = 1
guessNum = random.randint(1, 100)
realNum = int(input("Input a number from 1 to 100 for the computer to guess: "))
print("Is the number " + str(guessNum) + "?")
answer = input("Type yes, or no: ")
answerLower = answer.lower()
if answerLower == 'yes':
if guessNum == realNum:
print("Seems like I got it in " + str(tries) + " try!")
else:
print("Wait I got it wrong though, I guessed " + str(guessNum) + " and your number was " + str(realNum) + ", so that means I'm acutally wrong." )
else:
print("Is the number higher or lower than " + str(guessNum))
lowOr = input("Type in lower or higher: ")
lowOrlower = lowOr.lower()
import random
guessNum2 = random.randint(guessNum, 100)
import random
guessNum3 = random.randint(1, guessNum)
while realNum != guessNum2 or guessNum3:
if lowOr == 'higher':
tries += 1
import random
guessNum2 = random.randint(guessNum, 100)
print(str(guessNum2))
input()
else:
tries += 1
import random
guessNum3 = random.randint(1, guessNum)
print(str(guessNum3))
input()
print("I got it!")
input()
How about something along the lines of:
import random
realnum = int(input('PICK PROMPT\n'))
narrowguess = random.randint(1,100)
if narrowguess == realnum:
print('CORRECT')
exit(1)
print(narrowguess)
highorlow = input('Higher or Lower Prompt\n')
if highorlow == 'higher':
while True:
try:
guess = random.randint(narrowguess,100)
print(guess)
while realnum != guess:
guess = random.randint(narrowguess,100)
print(guess)
input()
print(guess)
print('Got It!')
break
except:
raise
elif highorlow == 'lower':
while True:
try:
guess = random.randint(1,narrowguess)
print(guess)
while realnum != guess:
guess = random.randint(1,narrowguess)
print(guess)
input()
print(guess)
print('Got It!')
break
except:
raise
This code is just a skeleton, add all of your details to it however you like.

Guess the number program in Python - after typing how many times I want to play, game is not working

I am working on Guess the number program in Python. I had to make some enhancements to it and add:
User has a default limit of 15 guesses (when enter key is hit)
Ask for a limit to the number of guests - this part doesn't work in my code.
import random
def main():
print('\n'*40)
print('Welcome to the Guess number game!')
print('\n'*1)
player_name = input("What is your name? ") print('\n'*1)
try_again = 'y'
number_of_guesses = 0
error = 0
guess_limit = 15
while ((try_again == 'y') or (try_again == 'Y')):
try:
limit = input('You have 15 default guesses to start. Do you like to have different number of guesses? ')
if limit.upper() == 'Y':
limit = input('How many times would you like to play? ') # after I input number of guesses I cannot proceed to the actual game
else:
number = random.randint(1, 100)
while (guess_limit != 0):
guess = int(input("Enter an integer from 1 to 100: "))
if (guess < 1) or (guess > 100):
print("ERROR! Integer must be in the range 1-100! ")
else:
if guess < number:
print ("Guess is low!")
elif guess > number:
print ("Guess is high!")
else:
print('\n'*1)
print ("YOU WIN! You made " + str(number_of_guesses) + " guesses.")
break
number_of_guesses += 1
guess_limit -= 1
print(guess_limit, 'guesses left')
print()
else:
#if guess_limit == 0:
print ("YOU LOSE! You made " + str(number_of_guesses) + " guesses.")
except ValueError:
print('ERROR: Non-numeric data. Please enter valid number!')
print('\n'*1)
try_again = input("Play again? Enter 'Y' or 'y' for yes: ")
print('\n'*1)
main()
OUTPUT: Welcome to the Guess number game!
What is your name? d
You have 15 default guesses to start.
Do you like to have different number of guesses? y
How many times would you like to play? 3 # after this I have
Play again? Enter 'Y' or 'y' for yes: # this result
How can I change that code?
you have to use
guess_limit = input("How many times would you like to play? ")
and then you have to check if it is blank or not by simple if conditions
if guess_limit == "":
guess_limit = 15
Below is the full code with well commented.
# import only system from os
from os import system
import random
def main():
# For clearing the screen
system('cls')
# For adding blank line
blank_line = '\n'*1
print('Welcome to the Guess number game!')
print(blank_line)
player_name = input("What is your name? ")
print(blank_line)
# to start the loop initially try_again = 'y'
try_again = 'y'
# Count number of guesses by player
number_of_guesses = 0
while (try_again.lower() == 'y'):
# Get number of times player want to guess
guess_limit = input("How many times would you like to play? ")
# If player enter nothing and hit enter
# then default value of guess_limit is 15
if guess_limit == "":
guess_limit = 15
# Convert the guess_limit to int data type
guess_limit = int(guess_limit)
# If user inputted number then go inside this try block
# else go inside except block
try:
# Generate random number in betwee 1-99 to be guess by the player
number = random.randint(1, 99)
# Loop untill there is no guesses left
while (guess_limit != 0):
# Player guess
guess = int(input("Enter an integer from 1 to 99: "))
# Check for valid number i.e number should be betwee 1 - 99
while ((guess < 1) or (guess > 99)):
guess = int(
input("ERROR! Please enter an integer in the range from 1 to 99: "))
# Check for High and low guess
if guess < number:
print("Guess is low")
elif guess > number:
print("Guess is high")
# If it is neither high nor low
else:
print(blank_line)
print("YOU WIN! You made " +
str(number_of_guesses) + " guesses.")
# To get out of the loop
break
# decrement the guess_limit by 1 on every iteration
guess_limit -= 1
print(guess_limit, 'guesses left')
# Increment number of guesses by the player
number_of_guesses += 1
print()
# If guess_limit is equal to 0, it means player have not guessed the number
# And player lose
if guess_limit == 0:
print("YOU LOSE! You made " +
str(number_of_guesses) + " guesses.")
except ValueError:
print('ERROR: Non-numeric data. Please enter valid number!')
print(blank_line)
# Ask again to play again
# If player enter anything other than 'Y' or 'y' then exit the game
try_again = input("Play again? Enter 'Y' or 'y' for yes: ")
print(blank_line)
main()

Reverse Number Guessing Game Python

So, recently i have been trying to program a reverse number guessing game whereby the computer tries to guess the number i have in mind. The output i should get is as shown below:
Enter the range: 6
Think of a random number between 1 and 6 and press enter once done!
Is it smaller than 4, 'y' or 'n'?y
Is it smaller than 2, 'y' or 'n'?n
Is it smaller than 3, 'y' or 'n'?y
Wonderful it took me 3 questions to find out that you had the number 2 in mind!
These are my codes so far:
import random
maxNum = int(input('Enter the range: '))
input('Think of a random number between 1 and ' + str(maxNum) + ' and press enter once done!')
lowBound = 1
highBound = maxNum
response = ''
noOfGuesses = 0
numberHasBeenGuessed = False
randomNumber = random.randint(lowBound,highBound)
while not numberHasBeenGuessed:
noOfGuesses += 1
response = input("Is it smaller than " + str(randomNumber) + ", 'y' or 'n'?")
if response == "n" or response == 'N':
lowBound = randomNumber + 1
randomNumber = random.randint(lowBound,highBound)
elif response == "y" or response == "Y":
highBound = randomNumber - 1
randomNumber = random.randint(lowBound,highBound)
else:
print ('Please only type y, Y, n or N as responses')
numberHasBeenGuessed = True
print('Wonderful it took me ' + str(noOfGuesses) + ' attempts to guess that you had the number ' + str(randomNumber) + ' in mind')
The main algorithm is working but somehow it cant detect it when the number has been 'guessed'..
does anyone know why?
I will greatly appreciate the help :)
Here is a version using try/except
import random
maxNum = int(input('Enter the range: '))
input('Think of a random number between 1 and ' + str(maxNum) + ' and press enter once done!')
lowBound = 1
highBound = maxNum
response = ''
noOfGuesses = 0
numberHasBeenGuessed = False
randomNumber = random.randint(lowBound,highBound)
while not numberHasBeenGuessed:
noOfGuesses += 1
response = input("Is it smaller than " + str(randomNumber) + ", 'y', 'n', or 'Thats it'?")
if response == "n" or response == 'N':
lowBound = randomNumber + 1
try:
randomNumber = random.randint(lowBound,highBound)
except ValueError:
numberHasBeenGuessed = True
elif response == "y" or response == "Y":
highBound = randomNumber - 1
try:
randomNumber = random.randint(lowBound,highBound)
except ValueError:
numberHasBeenGuessed = True
else:
print ('Please only type y, Y, n or N as responses')
print('Wonderful it took me ' + str(noOfGuesses) + ' attempts to guess that you had the number ' + str(randomNumber) + ' in mind')
When it encounters a ValueError, it will take it that it has found your number. Please make sure there are no other situations that can result in an incorrect answer with this code, as I obviously haven't tested it thoroughly.
You could also put the try/except clauses in a def to make it more compact as they are the same pieces of code, but I wasn't sure if that was allowed or not for your project, so I left it.
You have numberHasBeenGuessed = True outside of the while loop - which means that it can't get called until the loop is over - so it will be forever stuck.
When it gets to your guess - lets say I have the number 7. Your program asks 'Is 7 smaller or larger than 7?' Obviously that makes no sense, 7 is 7. 7 is not smaller or larger than 7: and your program knows that and crashes. So you need to introduce a new user input option:
import random
maxNum = int(input('Enter the range: '))
input('Think of a random number between 1 and ' + str(maxNum) + ' and press enter once done!')
lowBound = 1
highBound = maxNum
response = ''
noOfGuesses = 0
numberHasBeenGuessed = False
randomNumber = random.randint(lowBound,highBound)
while not numberHasBeenGuessed:
noOfGuesses += 1
response = input("Is it smaller than " + str(randomNumber) + ", 'y', 'n', or 'Thats it'?")
if response == "n" or response == 'N':
lowBound = randomNumber + 1
randomNumber = random.randint(lowBound,highBound)
print(randomNumber)
elif response == "y" or response == "Y":
highBound = randomNumber - 1
randomNumber = random.randint(lowBound,highBound)
print(randomNumber)
elif response == "Thats it": #New input option 'Thats it'
numberHasBeenGuessed = True #Stops the while loop
else:
print ('Please only type y, Y, n or N as responses')
print('Wonderful it took me ' + str(noOfGuesses) + ' attempts to guess that you had the number ' + str(randomNumber) + ' in mind')
Now, you can input 'Thats it' when your number is guessed and the program finishes with the output you want. (Of course, change the inputs and what not to what you want)
Also final programmer tip: comment your code with hashtags, so you know (and others helping) what each part does.

Enter blank value in try statements

I am making a blackjack game for school and for this part, the user can choose their bet. It can be 0 to quit, press enter to keep the previous bet, or type a new bet. I got the enter 0 part, but I think my ValueError is blocking the user from entering a blank value. I apologize for the messy code. Is there another except statement I could add in to allow some mistakes, or do i need to restructure the entire loop?
import random
import sys
def main():
restart = True
bank_balance = 1000
player_name = input("Please enter your name: ")
while (restart):
print (f"Welcome {player_name}, your bank balance is ${bank_balance} ")
correct = False
user_bet=0
bet = input_bet(user_bet, bank_balance)
if (user_bet == 0):
print('Quiting the game')
break
win_lose = play_hand(player_name, bet)
bank_balance+=win_lose
print(f'Your bank balance: ${bank_balance}')
play=bet
def input_bet(bet, money):
correct = False
while not correct:
try:
enough_money = False
while not enough_money:
bet=int(input("Bet? (0 to quit, press 'Enter' to stay at $25) "))
if (bet > money):
print('not enough money')
elif (bet == 0):
return 0
elif (bet <= money):
print(f'Betting ${bet}')
enough_money=True
return bet
correct = True
except ValueError:
print('Please enter a number')
def play_hand(name, bet):
player= []
dealer= []
play_again = True
dealer.append(random.randint(1, 11))
player.extend([random.randint(1, 11), random.randint(1, 11)])
print ('The dealer received card of value', *dealer)
print(name, 'received cards of value', player[0], 'and', player[-1])
print(f'Dealer total is {sum(dealer)}')
print(f"{name}'s total is {sum(player)}", '\n')
stay = False
bust = False
while (sum(player) <= 21 and stay == False and play_again == True):
hors= input(f"Type 'h' to hit and 's' to stay ")
if (hors == 'h'):
new_card= random.randint(1, 11)
player.append(new_card)
print(f'{name} pulled a {new_card}')
print(f'Dealer total is {sum(dealer)}')
print(f"{name}'s cards are", *player)
print(f"{name}'s total is {sum(player)}", '\n')
elif (hors == 's'):
stay=True
print('stay')
if (sum(player) > 21 ):
bust = True
print('You busted!')
return -bet
while (stay == True and sum(dealer) < 17 and bust == False and play_again == True):
dealer.append(random.randint(1, 11))
print('The dealers cards are', *dealer)
print('The dealers total is', sum(dealer), '\n')
if (sum(dealer) <= 21 and sum(dealer) > sum(player)):
print("The dealer wins!")
return -bet
elif (sum(player) <= 21 and sum(player) > sum(dealer)):
print("You win!")
return bet
if (sum(dealer) > 21):
print ('You win! The dealer busted!')
return bet
if (sum(dealer) == sum(player)):
print('Its a Tie! ')
return 0
main()
The immediate issue is that int("") raises a ValueError, rather than returning 0 like int() does. The solution is to check the return value of input before you attempt to produce an int.
def input_bet(money):
while True:
response = input("Bet? (0 to quite, press 'Enter' to stay at $25) ")
if bet == "0":
return 0
if bet == "":
bet = "25"
try:
bet = int(bet)
except ValueError:
print("Please enter a number")
continue
if bet > money:
print("Not enough money")
continue
return bet
The only parameter input_bet needs is the player's total amount, to prevent betting more than is available. No initial bet is needed.

looking for advice for coding project

So as of right now the code needs to re-ask the problem given if the answer given was too high or too low. Also, if the answer is correct, it should tell them and then loop back to the question ('How many problems do you want?')
def main():
gamenumber = int(input("How many problems do you want?\n"))
count = 0
while count < gamenumber:
num_1 = randint(1,10)
num_2 = randint(1,10)
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
answer = (num_1*num_2)
count += 1
for guess in range(1):
if guess == answer:
print (' Thats Correct!')
for guess in range(1):
if guess > answer:
print (' Answer is to high')
for guess in range(1):
if guess < answer:
print ('Answer is to low')
main()
First of all can you please check your code. You have used "guess" variable in the for loop. When the program is executed the value of guess is say 40(4X10). When for statement is executed the guess values becomes 0 because of that you are getting the output as low. Make sure u change the variable you use in for loop to "num" and then check your output.
Why are you using 3 for loops you can do that in single for loop.
Please find the below code:-
from random import randint
def main():
ans = 'y'
while ans != 'n':
gamenumber = int(input("How many problems do you want?\n"))
count = 0
while count < gamenumber:
num_1 = randint(1,10)
num_2 = randint(1,10)
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
print(guess)
answer = (num_1*num_2)
print("=====>",answer)
count += 1
for num in range(1):
if guess == answer:
print (' Thats Correct!')
elif guess > answer:
print (' Answer is to high')
elif guess < answer:
print ('Answer is to low')
yes_no_input = str(input("Do you want to continue (y/n) ?"))
ans = accept_ans(yes_no_input)
if ans == 'n':
print("thanks for the test")
break;
def accept_ans(ans):
if not ans.isalpha():
print("Enter only y and n")
ans = str(input("Do you want to continue (y/n) ?"))
if ans == 'y' or ans == 'n':
return ans
if ans != 'y' or ans != 'n':
print("please enter y for YES and n for NO")
ans = str(input("Do you want to continue (y/n) ?"))
if ans != 'y' or ans != 'n':
accept_ans(ans)
if __name__ == '__main__':
main()
After
print("Thats correct")
you need to call the
main()
function again.

Categories