Python random number game - python

I'm trying to write a program that will generate a random number between 1 and 100 and then ask the user for a guess. At that point if the guess is correct it will tell them so and vice-versa if it's wrong.
What I have so far is:
import random
def playGame2():
number = random.randint(1,100)
guess = input("I'm thinking of a number between 1 and 100. Guess what it is: ")
if str(number) == guess:
print("That is correct!")
else:
print("Nope, I was thinking of" +str(number))
When I run the program it just gives me <function playGame2 at 0x0000000002D3D2F0>.
Why is it doing that?

You have to execute the function, your output implies you did something like
print(playGame2)
instead of
playGame2()

def playGame2():
number = random.randrange(1,100)
guess = input("I'm thinking of a number between 1 and 100. Guess what it is: ")
if str(number) == guess:
print("That is correct!")
else:
print("Nope, I was thinking of %s" % number)
Try that. I just ran it worked fine. To use enter playGame2() in Idle or a place where you can access it.

you need to tell python this have a main function
try include this at the end of your code :
if __name__ == "__main__":
playGame2()
and put this at the beginning :
# -*- coding: UTF-8 -*-
at the top of your code, for the way of specifying the encoding of a Python file that you use. see http://www.python.org/dev/peps/pep-0263/
wish it will help you.

import random
guess=99
count=0
no = random.randint(1,100)
print("Welcome to the guessing game!")
while guess != no :
guess = int(input("Guess a number: "))
if guess < no :
print("Higher")
count+=1
if guess > no :
print("Lower")
count+=1
if (guess==no):
print("You win, the number was indeed:",no)
print("It took you a total of:",count,"tries")

import random #import modules
import time
x = random.randint(1,100)#This is the random number
while True:
try:
while True: #Make a loop
y = input('Enter a number: ')
if int(y) == x:
print('You won!')
time.sleep(5)
exit()
if int(y) > x:
print('The input is too high')
continue #restart the loop
if int(y) < x:
print('The input is too low')
continue
except:
print('Only numbers')
continue

Related

How to loop a simple game to continue until user stops it not using a break?

def set_number():
import random
return random.randint(1,500)
#This function plays the game
def number_guessing_game(number):
guess_counter = 0
guess = int(input("Enter a number between 1 and 500."))
while guess != number:
guess_counter += 1
if guess > number:
print(f"You guessed too high. Try Again!")
guess = int(input("Enter a number between 1 and 500."))
elif guess < number:
print(f"You guessed too low. Try Again!")
guess = int(input("Enter a number between 1 and 500."))
if guess == number:
print(f"You guessed the number! Good Job.!")
again = str(input("would you like to play again? Enter 'y' for yes or 'n' to close the game."))
def main():
print(f"Welcome to the Number Guessing Game!\n" +
f"You will have unlimited guesses. The number is between 1 and 500.\n" +
f"Good Luck!")
number = set_number()
guess_count = number_guessing_game(number)
main()
I am working on a simple game project for my coding class. I am not good at coding at all. I came up with this part of the program, I just cannot figure out how to loop the entire number_guessing_game function until the user enters 'n' to stop it, I can't use a break because we did not learn it in the class and I will receive a 0 if I use a break.
I tried nesting a while loop inside of the function but I know I did it wrong.
Instead of using break use return.
def main():
print(f"Welcome to the Number Guessing Game!\n" +
f"You will have unlimited guesses. The number is between 1 and 500.\n" +
f"Good Luck!")
while True:
number = set_number()
number_guessing_game(number)
again = input("would you like to play again? Enter 'y' for yes or 'n' to close the game.")
if again == 'n':
return
main()
You will probably want to remove the last line of the number_guessing_game function if you use this approach
First, your code is assuming the return of input is an integer that can be converted with int(). If you were to give it 'n' your program will crash.
Instead you could use the string class method isdigit() to see if the input was an integer value and then make a logical decision about it. Also note you do not need to convert the return from input to a str() as it is already a str type. You can confirm this with a print(type(input("give me something")))
guess = input("Enter a number between 1 and 500. 'n' to quit"))
if guess.isdigit():
[your code to check the value]
elif ('n' == guess):
return
else:
print(f"You entered an invalid entry: {guess}. Please re-enter a valid value")
If you dont like the idea of using 'return' you could change your while loop to look something like:
while(('n' != guess) or (guess != number)):
If you want the function body looping continuously you could have some code like:
def number_guessing_game(number):
exit_game = False
guess_counter = 0
while(exit_game != True):
guess = input("Enter a number between 1 and 500.))
guess_counter += 1
if guess.isdigit():
if int(guess) > number:
print("You guessed too high. Try Again!")
elif int(guess) < number:
print("You guessed too low. Try Again!")
elif int(guess) == number:
print("You guessed the number! Good Job.!")
again = input("would you like to play again? Enter 'y' for yes or 'n' to close)
if ('n' == again):
exit_game = True
else:
print("Error, please enter a valid value")

How to create a loop within this game successfully?

I'm fairly new to Python so I'm not sure how to go about this. I have created this random number guessing game, and I have it down except for the fact that the game is supposed to never end. Once the user guesses the number, the game should start over. Here is my code.
import random
num = random.randint(1, 100)
def main():
guess_num = 0
guess = int(input("Enter an integer from 1 to 100: "))
while num != guess:
if guess < num:
print("Too low, try again.")
guess = int(input("Enter an integer from 1 to 100: "))
guess_num+=1
elif guess > num:
print("Too high, try again.")
guess = int(input("Enter an integer from 1 to 100: "))
guess_num+=1
else:
print("Congratulations, that's correct!")
guess_num = guess_num+1
print("You guessed "+str(guess_num)+" times!")
break
main()
main()
while True:
main()
This makes your main method run until you stop it.
You put a break statement in your else. If you remove it it will work. But you also have to put your num statement inside your main.
This should do the job:
def main():
num = random.randint(1, 100)
guess_num = 0
guess = int(input("Enter an integer from 1 to 100: "))
while num != "guess":
if guess < num:
print("Too low, try again.")
guess = int(input("Enter an integer from 1 to 100: "))
guess_num+=1
elif guess > num:
print("Too high, try again.")
guess = int(input("Enter an integer from 1 to 100: "))
guess_num+=1
else:
print("Congratulations, that's correct!")
guess_num = guess_num+1
print("You guessed "+str(guess_num)+" times!")
main()
main()
All lines down from def main(): must be indented four spaces. Maybe it's just a problem with the copy paste, but I find myself really uncomfortable looking at improperly indented Python code.
Remove the print statement right after while num != "guess": not sure what it does
Remove the quotes around guess as right now you're checking a number against a string
Now, to implement your functionality, you should move the num = random.randint(1, 100) line into the function to choose a new number. Then, call the function while true:
while True:
main()

Using system.exit

I am trying to add a sys.exit to my code now, but I want it to display the print messages before quitting. Can I do this? Also, at the end of my code, I would like to give the user the option to quit or start again, but when they type quit after finishing the first game, it just uses quit as their name.
import random
import sys
def system_exit(exitCode):
sys.exit()
# uses randrange instead of randint for better results in Python 3.7
# randrange stops just before the upper range, use (1, 11) for 1-10
num = random.randrange(1, 11)
name = input("What is your name? Or if you would rather quit, type quit at
any time. " "\n")
i = name
while i != "quit":
print('Hello', name,'!')
while i.lower() == 'quit':
print ("Sorry, you did not select a number in the range or
selected to quit. Good bye.")
system_exit(4)
your_guess = input('Enter a number between 1 and 10.' '\n')
if (your_guess.lower() == "quit"):
print ("Sorry, you did not select a number in the range or
selected to quit. Good bye.") #this isn't showing up before closing
your_guess = int(your_guess)
# display the number guessed
print("Your number is", your_guess)
while num != your_guess:
if your_guess < num:
print("Your guess is too low.")
your_guess = int(input("Guess another number from
1 to 10: " '\n'))
elif your_guess > num:
print("Your guess is too high")
your_guess = int(input("Guess another number from
1 to 10: " '\n'))
else:
print ("Sorry, you did not select a number in the
range or selected to quit. Good bye.") #this isn't showing up before
closing
system_exit(4)
print("The correct number was", num)
print("***************************************************************")
name = input("What is your name? Or if you would rather quit, type
quit. ")
num = random.randrange(1, 11)
print("Thank you for playing!") #this isn't showing up before closing
system_exit(0)
Replace the following line of code:
your_guess = int(input('Enter a number between 1 and 10.'))
with the code below:
your_guess = input('Enter a number between 1 and 10.')
if (your_guess.lower() == 'quit'):
#print some break message
your_guess = int(your_guess)

In my guess the number it tells me my Number variable isnt defined

With my guess the number program, when I try to run it tells me the the variable "number" is not defined. I would appreciate it and be thankful if someone came to my aid in this!
import random
guesses = 0
def higher(guesses):
print("Lower")
guesses = guesses + 1
def lower(guesses):
print("Higher")
guesses = guesses + 1
def correct(guesses):
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_(guesses):
print("Welcome to guess the number")
number = random.randint(1, 100)
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher(guesses)
elif guess < number:
lower(guesses)
elif guess == number:
correct(guesses)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
break
elif answer == "N":
exit()
else:
exit()
_main_(guesses)
Your problem is that number is not defined in the function correct. number is defined in _main_. When you call correct in _main_, it does not get access to number.
This is the fixed version of your code:
import random
guesses = 0
number = random.randint(1, 100)
def higher(guesses):
print("Lower")
guesses = guesses + 1
def lower(guesses):
print("Higher")
guesses = guesses + 1
def correct(guesses):
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_(guesses):
print("Welcome to guess the number")
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher(guesses)
elif guess < number:
lower(guesses)
elif guess == number:
correct(guesses)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
break
elif answer == "N":
exit()
else:
exit()
_main_(guesses)
What I changed is I moved the definition of number to the top, which allowed it to be accessed by all functions in the module.
Also, your code style is not very good. Firstly, do not name your main function _main_, instead use main. Additionally, you don't need a function to print out 'lower' and 'higher.' Here is some improved code:
import random
def main():
number = random.randint(1, 100)
guesses = 0
while True:
guessed_num = int(input('Guess the number: '))
guesses += 1
if guessed_num > number:
print('Guess lower!')
elif guessed_num < number:
print('Guess higher!')
else:
print('Correct!')
print('The number was {}'.format(number))
print('It took you {} guesses.'.format(guesses))
break
main()
Your specific problem is that the variable number is not defined in function correct(). It can be solved by passing number as an argument to correct().
But even if you correct that problem, your program has another major issue. You have defined guesses globally, but you still pass guesses as an argument to lower(), higher() and correct(). This creates a duplicate variable guesses inside the scope of these functions and each time you call either of these functions, it is this duplicate variable that is being incremented and not the one you created globally. So no matter how many guesses the user takes, it will always print
You took 1 guesses.
Solution:
Define the functions lower() and higher() with no arguments. Tell those functions thatSo ultimately this code should work:
import random
guesses = 0
def higher():
global guesses
print("Lower")
guesses = guesses + 1
def lower():
global guesses
print("Higher")
guesses = guesses + 1
def correct(number):
global guesses
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_():
print("Welcome to guess the number")
guesses = 0
number = random.randint(1, 100)
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher()
elif guess < number:
lower()
elif guess == number:
correct(number)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
_main_()
elif answer == "N":
exit()
else:
exit()
_main_()

Guessing game: matching user input with randomly generated number

def var (guess):
return guess
guess = int(input("Guess a number 1 through 10: "))
import random
num = (random.randint(1,10))
while True:
try:
guess = num
print("you guessed the right number!")
break
except:
print("try again")
break
So for this program I am trying to figure out how to have the user input a number and to guess what number (1 through 10) the program generated. It seems that every time I input a value it always gives me the "you guess the right number!" string even if I input a value higher than 10.
EDIT: Why would someone downvote my question o_o
You need to get user's input inside while loop so that user's input got updated with each iteration.
import random
num = (random.randint(1,10))
while True:
try:
guess = int(input("Guess a number 1 through 10: "))
if guess == num:
print("you guessed the right number!")
break
else:
print("try again")
except:
print('Invalid Input')
try/except is for exception handling, Not matching values. What you are looking for is if statments, For example:
guess = int(input("Guess a number 1 through 10: "))
import random
num = (random.randint(1,10))
if guess == num:
print("You guessed the right number!")
else:
print("Try again")
I think you may have intended to continue looping until the right number is guessed, In which case, This will work:
import random
num = (random.randint(1,10))
while True:
guess = int(input("Guess a number 1 through 10: "))
if guess == num:
print("You guessed the right number!")
break
else:
print("Try again")

Categories

Resources