Working in Python 3.
I'm still relatively new to Python (only a few weeks worth of knowledge).
The prompt that I was given for the program is to write a random number game where the user has to guess the random number (between 1 and 100) and is given hints of being either too low or too high if incorrect. The user would then guess again, and again until they reach the solution. After the solution, the number of guesses should tally at the end.
import random
def main():
# initialization
high = 0
low = 0
win = 0
number = random.randint(1, 100)
# input
userNum = int(input("Please guess a number between 1 and 100: "))
# if/else check
if userNum > number:
message = "Too high, try again."
high += 1
elif userNum == number:
message = "You got it correct! Congratulations!"
win += 1
else:
message = "Too low, try again."
low += 1
print()
print(message)
# loop
# while message != "You got it correct! Congratulations!":
# display total
print()
print("Number of times too high: ", high)
print("Number of times too low: ", low)
print("Total number of guesses: ", (high + low + win))
main()
I'm struggling to figure out how to make the loop work. I need the random number to be static while the user guesses with inputs. After each attempt, I also need them to be prompted with the correct message from the if/else check.
You could set 'userNum' to be 0, and encase all the input in a while loop:
userNum = 0
while (userNum != number):
This will continually loop the guessing game until the user's guess equals the random number. Here's the full code:
import random
def main():
# initialization
high = 0
low = 0
win = 0
number = random.randint(1, 100)
userNum = 0
while (userNum != number):
# input
userNum = int(input("Please guess a number between 1 and 100: "))
# if/else check
if userNum > number:
message = "Too high, try again."
high += 1
elif userNum == number:
message = "You got it correct! Congratulations!"
win += 1
else:
message = "Too low, try again."
low += 1
print()
print(message)
# loop
# while message != "You got it correct! Congratulations!":
# display total
print()
print("Number of times too high: ", high)
print("Number of times too low: ", low)
print("Total number of guesses: ", (high + low + win))
print("You win")
main()
You can just put your guesses in a simple loop:
import random
def main():
# initialization
high = 0
low = 0
win = 0
number = random.randint(1, 100)
while win == 0:
# input
userNum = int(input("Please guess a number between 1 and 100: "))
# if/else check
if userNum > number:
message = "Too high, try again."
high += 1
elif userNum == number:
message = "You got it correct! Congratulations!"
win += 1
else:
message = "Too low, try again."
low += 1
print()
print(message)
# loop
# while message != "You got it correct! Congratulations!":
# display total
print()
print("Number of times too high: ", high)
print("Number of times too low: ", low)
print("Total number of guesses: ", (high + low + win))
main()
Any of the other answers will work, but another check you can do for the loop is 'not win', which will stop the loop for any value of win that isn't zero.
while not win:
# input
userNum = int(input("Please guess a number between 1 and 100: "))
# if/else check
...
import random
def main():
# initialization
high = 0
low = 0
win = 0
number = random.randint(1, 100)
# input
while(True): #Infinite loop until the user guess the number.
userNum = int(input("Please guess a number between 1 and 100: "))
# if/else check
if userNum > number:
message = "Too high, try again."
high += 1
elif userNum == number:
message = "You got it correct! Congratulations!"
win += 1
break #Break out of the infinite loop
else:
message = "Too low, try again."
low += 1
print(message) ##Display the expected message
print()
print(message)
# display total
print()
print("Number of times too high: ", high)
print("Number of times too low: ", low)
print("Total number of guesses: ", (high + low + win))
if __name__ == '__main__':
main()
There's so many ways you can go about this kind of task, it's what makes programming epic.
I have written a little something that answers your question, it even has a simple feel to it!
What i've done is done a for loop to give the user a total of range(10) tries. For every guess the user makes, it adds 1 'tries' to 0. In my if statement, all I'm wanting to know is if the guess is the same as the_number and below the number of tries available, you've done it. Otherwise, higher or lower :)
Hope this helps!
import random
print("\nWelcome to the guessing game 2.0")
print("Example for Stack Overflow!\n")
the_number = random.randint(1, 100)
tries = 0
for tries in range(10):
guess = int(input("Guess a number: "))
tries += 1
if guess == the_number and tries <= 10:
print("\nCongratulations! You've guessed it in", tries, "tries!")
break
elif guess < the_number and tries < 10:
print("Higher...")
tries += 1
elif guess > the_number and tries < 10:
print("Lower...")
tries += 1
elif tries >= 11:
print("\nI'm afraid to haven't got any tries left. You've exceeded the limit.")
import random
def display_title():
return print("Number Guessing Game")
def play_game():
cpu_num = random.randint(1, 10)
user_guess = int(input("Guess a number from 1 to 10:")
while user_guess != cpu_num:
print("Try Again")
user_guess = int(input("Guess a number from 1 to 10:"))
if user_guess == cpu_num:
print("Correct!")
def main():
title = print(display_title())
game = print(play_game())
return title, game
print(main())
Related
I want pc to find the number in my mind with random function "every time"
so i tried something but not sure this is the correct direction and its not working as intended
how am i supposed to tell pc to guess higher than the previous guess
ps:code is not complete just wondering is it possible to do this way
def computer_guess():
myguess = int(input("Please enter your guess: "))
pcguess = randint(1, 10)
feedback = ""
print(pcguess)
while myguess != pcguess:
if myguess > pcguess:
feedback = input("was i close?: ")
return feedback, myguess
while feedback == "go higher":
x = pcguess
pcguess2 = randint(x, myguess)
print(pcguess2)
I wrote this a few years ago and it's similar to what you're trying to do except this only asks for user input once then calls random and shrinks the range for the next guess until the computer guess is equal to the user input.
import random
low = 0
high = 100
n = int(input(f'Chose a number between {low} and {high}:'))
count = 0
guess = random.randint(0,100)
lower_guess = low
upper_guess = high
while n != "guess":
count +=1
if guess < n:
lower_guess = guess+1
print(guess)
print("is low")
next_guess = random.randint(lower_guess , upper_guess)
guess = next_guess
elif guess > n:
upper_guess = guess-1
print(guess)
print("is high")
next_guess = random.randint(lower_guess , upper_guess)
guess = next_guess
else:
print("it is " + str(guess) + '. I guessed it in ' + str(count) + ' attempts')
break
I am creating a game in which the computer selects a random number 1-10
Then the user guesses the number until they get it right.
The trouble I am having is that when the users enter the wrong answer the variables high or low should be updated, but it just continues looping until the user does enter the right answer. Which causes high and low to always be at 0.
Any ideas? I know there is probably something wrong with the way I am looping?
Any pushes in the right direction would be great!
# module to generate the random number
import random
def randomNum():
selection = random.randint(0,9)
return selection
# get the users choices
def userGuess():
correct = True
while correct:
try:
userPick = int(input('Please enter a guess 1-10: '))
if userPick < 1 or userPick >10:
raise ValueError
except ValueError:
print('Please only enter a valid number 1 - 10')
continue
return userPick
# define main so we can play the game
def main():
correctNum = randomNum()
guess = userGuess()
high = 0
low = 0
if guess != correctNum:
print('uhoh try again!')
guess=userGuess()
elif guess > correctNum:
print('That guess is too high!')
high = high + 1
elif guess < correctNum:
print('That guess is too low')
low = low + 1
else:
print('You win!')
# the outcome of the game:
print('Guesses too high:', high)
print('Guesses too low:',low)
print('Thank you for playing!')
main()
Try modifying your main function :
def main():
correctNum = randomNum()
guess = userGuess()
high = low = 0 # nifty way to assign the same integer to multiple variables
while guess != correctNum: # repeat until guess is correct
if guess > correctNum:
print('That guess is too high!')
high = high + 1
else:
print('That guess is too low')
low = low + 1
print('Try again!')
guess=userGuess()
print('You win!')
# the outcome of the game:
print('Guesses too high:', high)
print('Guesses too low:',low)
print('Thank you for playing!')
Also, be careful with random.randint(0,9) : this will give a number between 0-9 (including 0 and 9, but never 10)!
You want to be doing random.randint(1, 10)
# module to generate the random number
import random
def get1to10():
selection = random.randint(1,10)
return selection
# get the users choices
def userGuess():
correct = True
while correct:
try:
userPick = int(input('Please enter a guess 1-10: '))
if userPick < 1 or userPick >10:
raise ValueError
except ValueError:
print('Please only enter a valid number 1 - 10')
continue
return userPick
# define main so we can play the game
def main():
correctNum = get1to10()
guess = 0
high = 0
low = 0
# use a while loop to collect user input until their answer is right
while guess != correctNum:
guess = userGuess()
# use if statements to evaluate if it is < or >
if guess > correctNum:
print('This is too high!')
high = high + 1
continue
# use continue to keep going through the loop if these are true
elif guess < correctNum:
print('this is too low!')
low = low + 1
continue
else:
break
# the outcome of the game:
print('----------------------')
print('Guesses too high:', high)
print('Guesses too low:',low)
print('The correct answer was:', '*',correctNum,'*', sep = '' )
print('Thank you for playing!')
print('---------------------')
main()
I found this solution to work well for what I needed!
Thank you everyone who answered this post!
You can try using a dictionary:
guesses = {'Higher': [],
'Lower': [],
'Correct': False,
} # A Dictionary variable
def add_guess(number, correct_number):
if number > correct_number:
guesses['Higher'].append(number)
elif number < correct_number:
guesses['Lower'].append(number)
else:
guesses['Correct'] = True
return guesses
add_guess(number=5, correct_number=3) # Higher
add_guess(10, 3) # Higher
add_guess(2, 3) # Lower
# Correct is False, and higher has the numbers (10, 5) while lower has the numbers (2)
print(guesses)
add_guess(3, 3) # Correct should now be True
print(guesses)
This, of course, isn't the entire code but should point you in the right direction. There is a ton of resources on python dictionaries online.
#Guess the num
import random
def is_valid_num(num):
if num.isdigit() and 1 <= int(num) <= 100:
return True
else:
return False
def main():
number = random.randint(1,100)
guessed_number = False
guess = input('enter a num')
#guess = (input('enter a num'))
num_of_guesses = 0
while not guessed_number:
if not is_valid_num(guess):
#return False
guess = input('i count only digits enter 1<num<100')
continue
else:
num_of_guesses += 1
#break
guess = int(guess)
if guess < number:
print ('entered number is low')
elif guess > number:
print ('entered number is high')
else:
print ('you got in',num_of_guesses, 'guesses')
guessed_number = True
main()
Expected Out
if random number is system is 51 and we pressed 50 it will print too low, then continue this process lets say we gave input 51
output will you got in 2 guesses
isdigit() is a string method, it doesn't work on int inputs.
change this :
guess = int(input('enter a num'))
to this:
guess = input('enter a num')
your code after editing:
#Guess the num
import random
def is_valid_num(num):
if num.isdigit() and 1 <= int(num) <= 100:
return True
else:
return False
def main():
number = random.randint(1,100)
guessed_number = False
guess = input('enter a num')
#guess = (input('enter a num'))
num_of_guesses = 0
while not guessed_number:
if not is_valid_num(guess):
#return False
guess = input('i count only digits enter 1<num<100')
continue
else:
num_of_guesses += 1
break
guess = int(guess)
if guess < number:
print ('entered number is low')
elif guess > number:
print ('entered number is high')
else:
print ('you got in',num_of_guesses, 'guesses')
guessed_number = True
main()
#Thanks Issac Full code is below
#Guess the num
import random
def is_valid_num(num):
if num.isdigit() and 1 <= int(num) <= 100:
return True
else:
return False
def main():
number = random.randint(1,100)
guessed_number = False
guess = input('enter a num')
#guess = (input('enter a num'))
num_of_guesses = 0
while not guessed_number:
if not is_valid_num(guess):
#return False
guess = input('i count only digits enter 1<num<100')
continue
else:
num_of_guesses += 1
#break
guess = int(guess)
if guess < number:
guess = (input('entered number is low try again'))
elif guess > number:
guess = (input('entered number is high try again'))
else:
print ('you got in',num_of_guesses, 'guesses')
guessed_number = True
main()
Output is below
>>enter a num55
entered number is high try again55
entered number is high try again45
entered number is high try again88
entered number is high try again30
entered number is high try again10
entered number is low try again20
entered number is low try again25
entered number is high try again22
entered number is low try again23
you got in 10 guesses
Im getting a syntax error for elif option ==2:. I was wondering what I need to do to fix it. I followed the pseudocode my professor gave us but it still won't run. I'm wondering if I shouldn't have used elif or maybe something about the indentation is off.
import random
print("Welcome to the guess my number program")
while True:
print("1. You guess the number")
print("2. You type a number and see if the computer can guess it")
print("3. Exit")
option = int(input("Please enter your number here: "))
if option ==1:
#generates a random number
mynumber = random.randint(1,11)
#number of guesses
count = 1
while True:
try:
guess = int(input("Guess a number between 1 and 10:"))
while guess < 1 or guess > 10:
guess = int(input("Guess a number between 1 and 10:")) # THIS LINE HERE
except:
print("Numbers Only")
continue
#prints if the number you chose is too low and adds 1 to the counter
if guess < mynumber:
print("The number you chose is too low")
count= count+1
#prints if the number you chose is too high and adds 1 to the counter
elif guess > mynumber:
print("The number you choose is too high")
count = count+1
#If the number you chose is correct it will tell you that you guessed the number and how many attempts it took
elif guess == mynumber:
print("You guessed it in " , count , "attempts")
break
elif option == 2:
number = int(input("Please Enter a Number: "))
count = 1
while True:
randomval = random.randint(1,11)
if (number < randomval):
print("Too high")
elif (number > randomval):
print("Too low")
count = count+1
elif (number==randomval):
print("The computer guessed it in" + count + "attempts. The number was" + randomval)
break
else:
break
The problem is simple. There is no continuity between if option == 1 and elif option == 2, because of the in between while loop. What you have to do is remove the el part of elif option == 2 and just write if option == 2.
I haven't tested the whole program myself. But at a glance, this should rectify the problem.
Please comment if otherwise.
I have the following code for a random number guessing game:
import random
number = random.randint(1,100)
name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")
guess1 = input()
if guess1 == number:
print ("Good job, you got it!")
while guess1 != number:
if guess1 > number:
print ('your guess is too high')
if guess1 < number:
print ('your guess is too low')
which throws the error that > or < cannot be used between str and int.
What should I do so it doesn't trigger that error?
There are two errors in your code.
You need to convert the input for guess1 from a string (by default) to an integer before you can compare it to the number (an integer).
The while loop will never stop since you are not letting the user input another value.
Try this:
import random
number = random.randint(1,100)
name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")
guess1 = int(input()) # convert input from string to integer
while guess1 != number:
if guess1 > number:
print ('your guess is too high. Try again.')
elif guess1 < number:
print ('your guess is too low. Try again.')
guess1 = int(input()) # asks user to take another guess
print("Good job, you got it!")
You can make use of a while loop here - https://www.tutorialspoint.com/python/python_while_loop.htm
The logic should be:
answer_is_correct = False
while not answer_is_correct :
Keep receiving input until answer is correct
I hope this works for you:
import random
myname = input('Hello, what is your name?')
print('Well',myname,'am thinking of a number between 1 and 100')
number = random.randint(1,100)
guess = 0
while guess < 4:
guess_number = int(input('Enter a number:'))
guess += 1
if guess_number < number:
print('Your guess is to low')
if guess_number > number:
print('Your guess is to high')
if guess_number == number:
print('Your guess is correct the number is',number)
break
if guess == 4:
break
print('The number i was thinking of is',number)
from random import randint
print("you wanna guess a number between A to B and time of guess:")
A = int(input("A:"))
B = int(input("B:"))
time = int(input("time:"))
x = randint(1, 10)
print(x)
while time != 0:
num = int(input("Enter: "))
time -= 1
if num == x:
print("BLA BLA BLA")
break
print("NOPE !")
if time == 0:
print("game over")
break
Code in Python 3 for guessing game:
import random
def guessGame():
while True:
while True:
try:
low, high = map(int,input("Enter a lower number and a higher numer for your game.").split())
break
except ValueError:
print("Enter valid numbers please.")
if low > high:
print("The lower number can't be greater then the higher number.")
elif low+10 >= high:
print("At least lower number must be 10 less then the higher number")
else:
break
find_me = random.randint(low,high)
print("You have 6 chances to find the number...")
chances = 6
flag = 0
while chances:
chances-=1
guess = int(input("Enter your guess : "))
if guess<high and guess>low:
if guess < find_me:
print("The number you have entered a number less then the predicted number.",end="//")
print("{0} chances left.".format(chances))
elif guess > find_me:
print("The number you have entered a number greater then the predicted number.",end="//")
print("{0} chances left.".format(chances))
else:
print("Congrats!! you have succesfully guessed the right answer.")
return
else:
print("You must not input number out of range")
print("{0} chances left.".format(chances))
print("The predicted number was {0}".format(find_me))
You can conditions within the while loop to check if its right. It can be done the following way.
import random
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 100)
print('Well, ' + myName + ', I am thinking of a number between 1 and 100.')
inputNumber = int(raw_input('Enter the number')
while inputNumber != number:
print "Sorry wrong number , try again"
inputNumber = int(raw_input('Enter the number')
print "Congrats!"
from random import *
def play_game():
print("Let's play a number guessing game")
# Selecting a random number between 1 and 100
number = randint(1, 100)
choice = int(input("I am thinking of a number between 1 and 100. Could you guess what it is? "))
# Guide the user towards the right guess
# Loop will continue until user guesses the right number
while choice != number:
if choice < number:
choice = int(input("Too low. Can you try again? "))
elif choice > number:
choice = int(input("Too high. Can you try again? "))
continue_game = input("You guessed it right! Would you like to play it again? (Y/N) ")
# Restart the game if user wishes to play again
if continue_game == "Y":
print("--" * 42)
play_game()
else:
print("Thanks for playing :)")
exit(0)
play_game()