How to use function in another function? Python - python

I am trying to make a game and I am really stuck. The problem is that I cant figur out how to use object oriented programming correctly. The program should launch gameboard function
everytime when the number doesnt equal to arv. It should return the new board with one "O"
less.
from random import randint
import time
class Game():
def __init__(self):
pass
def beginning(self):
print("How are you, and why are you playing my game?")
bla = str(input())
time.sleep(2)
print("Hello," + bla + ", I am glad to see you!")
time.sleep(2)
print("Anyways, the you have to guess a number from 1-20")
def gameboard(self):
self.__board = ["O","O","O","O","O"]
print(self.__board)
self.__board.pop()
return self.__board
def game(self):
number = randint(1,20)
print(number)
x = 1
arv = input()
self.arv__ = arv
while 5 > x:
if arv == number:
print("Lucky")
break
elif arv != number:
print ("haha, try again")
print("one life gone")
return gameboard()
print(self.board())
x += 1
def Main():
math = Game()
math.beginning()
math.game()
Main()

Using object-oriented programming when you only ever need one instance of the object tends to overcomplicate the program. I suggest having only one main function.
Nevertheless, I fixed your program. Try to find the changes yourself because I am too lazy to explain them, sorry.
from random import randint
import time
class Game():
def __init__(self):
pass
def beginning(self):
print("How are you, and why are you playing my game?")
bla = str(input())
time.sleep(2)
print("Hello," + bla + ", I am glad to see you!")
time.sleep(2)
print("Anyways, the you have to guess a number from 1-20")
self.__board = ["O","O","O","O","O"]
def gameboard(self):
print(self.__board)
self.__board.pop()
return self.__board
def game(self):
number = randint(1,20)
print(number)
x = 1
while 5 > x:
arv = input()
self.arv__ = arv
if arv == number:
print("Lucky")
break
elif arv != number:
print ("haha, try again")
print("one life gone")
self.gameboard()
print(self.__board)
x += 1
def Main():
math = Game()
math.beginning()
math.game()
Main()
Here is a version of your program that avoids OO and is much more simplified:
from random import randint
lives = 5
print("Guess a number from 1 to 20")
number = randint(1, 20)
while (lives > 1 and number != int(input())):
print("incorrect")
print("lives: " + "O" * lives)
lives -= 1
if lives == 0:
print("The number was actually " + str(number))
else:
print("You were right")

Related

Repeated prints from loop

I am trying to create a program similar to the game Mastermind. I am having an issue in my while loop where it constantly prints "You got " + str(correct) + " correct!"
import random
import replit
def useranswer(input):
userinput.append(input)
return input
number = 0
answer = 0
guesses = 0
correct = 0
x = 0
userinput = []
generation = []
c = []
replit.clear()
for i in range(0,4):
num = random.randrange(1,9)
generation.append(num)
for i in range(0,4):
answer = str(input('Give me a number: '))
useranswer(answer)
print(generation)
while userinput != generation:
guesses += 1
for i in range(0,4):
if generation[i] == userinput[i]:
correct += 1
print("You got " + str(correct) + " correct! ")
correct = 0
if guesses==1:
print("Good job! You became the MASTERMIND in one turn!")
else:
print("You have become the MASTERMIND in " + str(guesses) + " tries!")
If you want it to exit the while loop after printing the line print("You got " + str(correct) + " correct! ") then you'll need to do something within the while loop to make the check not true.
Right now if userinput != generation is true then it will loop forever because nothing in the loop ever changes that to be false.
You need to get the player's input within the while loop if you want it to keep looping until something happens, otherwise an if statement might be better.
Ive made couple of changes to your code. Take a look at it
Removed def userinput().
Moved userinput inside the while loop.
import random
import replit
number = 0
answer = 0
guesses = 0
x = 0
userinput = []
generation = []
c = []
replit.clear()
for i in range(0,4):
num = random.randrange(1,9)
generation.append(num)
while userinput != generation:
guesses += 1
correct = 0
userinput = []
for i in range(0,4):
answer = int(input('Give me a number: '))
userinput.append(answer)
for i in range(0,4):
if generation[i] == userinput[i]:
correct += 1
print("You got ",correct, " correct! ")
if guesses==1:
print("Good job! You became the MASTERMIND in one turn!")
else:
print("You have become the MASTERMIND in " ,guesses, " tries!")

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.

There's an issue somewhere in my Python code.. I can't find where it's at

I don't know what's wrong with it.. I run it and I'm able to input a number but then it stops working. It says, "TypeError: play_game() missing 1 required positional argument: 'limit.' But I'm not sure what's missing there??
#!/usr/bin/env python3
import random
def display_title():
print("Guess the number!")
print()
def get_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
count += 1
elif guess >= number:
print("Too high.")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
def main():
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game()
again = input("Play again? (y/n): ")
print()
print("Bye!")
# if started as the main module, call the main function
if __name__ == "__main__":
main()
You have defined your play_game function to take limit as a parameter, but when you call this function in your main loop, you don't supply a value in the brackets of play_game().
You could either try adding that limit value that you've specified by calling it like
play_game(25)
Or, based on your code, since you're asking the user to provide a limit, call it like:
play_game(limit)
Or, if you want to be able to call play_game() without setting a limit, then change your play_game definition line to something like:
def play_game(limit=25):
Which will set a default value of 25 whenever that function is called without supplying the limit value.
Yes, play_game() needs the parameter limit. I've done a quick check on your code, and there is some additional problem
the count variable isn't initialized
you calculate the random number in every step
guess > number should be used instead of guess >= number
Here is the fixed code, it works for me. I hope it will be usefull:
import random
count = 0
number = -1
def display_title():
print("Guess the number!")
print()
def get_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
global number, count
if number == -1:
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
count += 1
elif guess > number:
print("Too high.")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game(limit)
again = input("Play again? (y/n): ")
print()
print("Bye!")
In your main you are calling playgame() without providing a limit as an argument.
Your main should look something like
def main():
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game(10)
again = input("Play again? (y/n): ")
print()
print("Bye!")

Program not exiting after multiple games?

from random import random
# This function handles the number guessing and number formatting
def run_game():
# rand is declared by grabbing a number between 0 and 1, multiplying it by 100, and rounds to nearest integer
rand = round(random() * 100, 0)
print("Guess the number [0 - 100]")
guesses = 0
while True:
# Assigns the 'answer' variable by grabbing user input from console
answer = input()
# Checks if the input from the console is a number, and if not, asks the user to enter a valid number
if answer.isdigit():
n = int(answer)
if n > int(rand):
print("Number is less than " + str(n))
guesses = guesses + 1
elif n < int(rand):
print("Number is greater than " + str(n))
guesses = guesses + 1
else:
guesses = guesses + 1
print("It took you " + str(guesses) + " guesses to guess the right number!")
reply = play_again()
if reply is False:
break
else:
run_game()
else:
print("Please enter a number")
def play_again():
while True:
reply = input("Play again? (y/n)\n")
if reply.lower() == "y":
return True
elif reply.lower() == "n":
return False
else:
print("Enter 'y' or 'n'")
if __name__ == "__main__":
run_game()
So when I run this program, it runs fine. Once guessing the number, I can type y or n to play again. If I have only played once, it works fine. But if I select y, and play again, entering n after playing the second game does nothing
Your main issue is that you're using recursion to start a new game, but after the recursive call returns (assuming it does), you just keep on going in the original game.
There are a few ways you could fix that. The simplest would be to change the code that handles checking the user's choice to play again so that it always breaks:
if reply:
run_game()
break
A better approach would be to get rid of the recursion. There are a few ways you could do that. One simple idea is to simply reset the appropriate variables and keep right on going with your game loop when the user wants to play again:
reply = play_again()
if reply:
rand = round(random() * 100, 0)
print("Guess the number [0 - 100]")
guesses = 0
else:
break
Another way to avoid recursion would be to add another loop. Here's one way you could do it with a separate function:
def run_game():
rand = round(random() * 100, 0)
print("Guess the number [0 - 100]")
guesses = 0
while True:
answer = input()
if answer.isdigit():
n = int(answer)
if n > int(rand):
print("Number is less than " + str(n))
guesses = guesses + 1
elif n < int(rand):
print("Number is greater than " + str(n))
guesses = guesses + 1
else:
guesses = guesses + 1
print("It took you " + str(guesses) + " guesses to guess the right number!")
break # unconditionally break here!
def run_many_games():
again = True
while again:
run_game()
again = play_again()
One thing you may note that I've changed in all of the code above is how I test if the return value from play_again is True or False. There's no need for an extra comparison step when you have a bool value already. Just do if reply (or if not reply if you're testing for False). You can also do this in a while loop condition, as I do with again in my last code block.
Heres a good way to solve this problem. In your code you never actually exit the while loop because run game never exits, and there is no system variable returned to break it. Using sys.exit(0) also works, but its a bad habit to get into for these kinds of programs.
from random import random
# This function handles the number guessing and number formatting
def run_game():
# rand is declared by grabbing a number between 0 and 1, multiplying it by 100, and rounds to nearest integer
rand = round(random() * 100, 0)
print("Guess the number [0 - 100]")
guesses = 0
while True:
answer = input()
if type(answer) == int:
n = int(answer)
if n > int(rand):
print("Number is less than " + str(n))
guesses = guesses + 1
elif n < int(rand):
print("Number is greater than " + str(n))
guesses = guesses + 1
else:
guesses = guesses + 1
print("It took you " + str(guesses) + " guesses to guess the right number!")
break
reply = play_again()
if reply:
run_game()
else:
print 'Thank you for playing'
def play_again():
while True:
reply = raw_input("Play again? (y/n)\n")
if reply.lower() == "y":
return True
elif reply.lower() == "n":
return False
else:
print("Enter 'y' or 'n'")
if __name__ == "__main__":
run_game()
The reason this is happening is because run_game ends up calling itself recursively. Instead of restarting the game when the user chooses to play again it effectively creates a new instance of the game. Then when the user chooses to stop playing it returns back to the old session instead of exiting the program.
You can even prove this to yourself by remembering the solution before choosing to play again, and then choosing not to play again after the second session. You'll then be playing the previous session again and entering the solution you remembered or wrote down.
Now you can solve this problem by using sys.exit() instead of break to force the program to close, but that doesn't seem like good practice. If somebody chooses to play again too many times they can cause the program to run out of stack space and crash. Instead it's probably better to move that check out of run_game like this
if __name__ == "__main__":
while True:
run_game()
if not play_again():
break
And modify the else block in run_game to this
else:
guesses = guesses + 1
print("It took you " + str(guesses) + " guesses to guess the right number!")
break
There's no point in returning True or False according to the user input, you can work from there directly.
import sys
from random import random
# This function handles the number guessing and number formatting
def run_game():
# rand is declared by grabbing a number between 0 and 1, multiplying it by 100, and rounds to nearest integer
rand = round(random() * 100, 0)
print("Guess the number [0 - 100]")
guesses = 0
while True:
# Assigns the 'answer' variable by grabbing user input from console
answer = input()
# Checks if the input from the console is a number, and if not, asks the user to enter a valid number
if answer.isdigit():
n = int(answer)
if n > int(rand):
print("Number is less than " + str(n))
guesses = guesses + 1
elif n < int(rand):
print("Number is greater than " + str(n))
guesses = guesses + 1
else:
guesses = guesses + 1
print("It took you " + str(guesses) + " guesses to guess the right number!")
play_again()
else:
print("Please enter a number")
def play_again():
while True:
reply = input("Play again? (y/n)\n")
if reply.lower() == "y":
run_game()
elif reply.lower() == "n":
sys.exit(0)
else:
print("Enter 'y' or 'n'")
if __name__ == "__main__":
run_game()
This way the code is somewhat cleaner and fixes your problem. There's no point in passing "flags" around when you can do things directly.
Since your game is from 0 to 100 you should also verify if the user doesn't put a number that's bigger than 100, since lower than 0 doesn't pass the isdigit check.

4 Digit Guessing Game Python

Im trying to make a 4 digit numbers guessing game in Python 3. It should work by generating a random number between 1000 and 10000 (random.range(1000,10000)) and then by the user guessing and it should return after each guess how many numbers you have got right. My code doesn't exactly work and, I can't think why it doesn't so help is appreciated.
import random as r
guessing = True
real_ans = r.randrange(1000, 10000, 2)
real_ans_str = str(real_ans)
correct = 0
class Player():
def __init__(self):
self.player_guess = input("Enter a guess")
self.evaluate(correct)
def evaluate(self, correct):
for n in range(3):
if self.player_guess[n] == real_ans_str[n]:
correct += 1
if not correct == 4:
print(str(correct)," was correct")
correct = 0
else:
print("You guessed it! ")
guessing = False
while guessing:
Player()
There are several issues in your code:
You're creating a new instance of Player class inside the main loop. It works, but it's not the best approach IMHO.
You're using guessing to stop the main loop. In Python, all variables are local by default. In order to reference a global variable, you must identify it as global:
def evaluate(self, correct):
**global guessing**
for n in range(3):
if self.player_guess[n] == real_ans_str[n]:
correct += 1
if not correct == 4:
print(str(correct)," was correct")
correct = 0
else:
print("You guessed it! ")
guessing = False
However using global variables could lead to a messy code.
range provides values from the minimum (0 by default) inclusive and the maximum exclusive. That range(3) will provide the numbers 0, 1 and 2 (3 numbers total), which is not what you want.
Since you're using a class, I'd try the following:
Create a single instance of Player
Create a new method called guess
Change the evaluate method to return how many digits the player guessed right
Create a new method called run, that will call guess and evaluate
import random as r
class Player():
def __init__(self):
self.real_ans = str(r.randrange(1000,100000,2))
def guess(self):
self.player_guess = raw_input("Enter a guess")
def evaluate(self):
correct = 0
for n in range(4):
if self.player_guess[n] == self.real_ans[n]:
correct += 1
return correct
def run(self):
while True:
self.guess()
correct = self.evaluate()
if not correct == 4:
print(str(correct)," was correct")
else:
print("You guessed it! ")
break
Player().run()
#Digit Guessing Game by Deniz
#python 3.5.1 - Please note that from Python version 2.7 "Tkinter" has been renamed tkinter, with a lowercase "t".
import tkinter
import random
computer_guess = random.randint(1,10)
def check():
user_guess = int(txt_guess.get())
if user_guess < computer_guess:
msg = "Higher!"
elif user_guess > computer_guess:
msg = "Lower!"
elif user_guess == computer_guess:
msg = "Correct!"
else:
msg = "Houston we have a problem!..."
lbl_result["text"] = msg
txt_guess.delete(0, 5)
def reset():
global computer_guess
computer_guess = random.randint(1,10)
lbl_result["text"] = "Game reset. Guess again!"
root = tkinter.Tk()
root.configure(bg="white")
root.title("Guess the correct number!")
root.geometry("280x75")
lbl_title = tkinter.Label(root, text="Welcome to Deniz's guessing Game!", bg="White")
lbl_title.pack()
lbl_result = tkinter.Label(root, text="Good Luck!", bg="White")
lbl_result.pack()
btn_check = tkinter.Button(root, text="Check", fg="blue", bg="White", command=check)
btn_check.pack(side="left")
btn_reset = tkinter.Button(root, text="Reset", fg="red", bg="White", command=reset)
btn_reset.pack(side="right")
txt_guess = tkinter.Entry(root, width=7)
txt_guess.pack()
root.mainloop()
root.destroy()
After reading your comments, I think what you need is this:
class Player():
def __init__(self):
self.player_guess = input("Enter a guess")
self.evaluate(correct)
def evaluate(self, correct):
for n in range(4):
if self.player_guess[n] == real_ans_str[n]:
correct += 1
else:
print(str(correct)," was correct")
correct = 0
break
if correct == 4:
print("You guessed it! ")
guessing = False
You can integrate it along with #Robson's answer to end the loop.
Use range(4), range(3) has the values [0, 1, 2] so 3 is missing:
for n in range(4):
if self.player_guess[n] == real_ans_str[n]:
correct += 1
The global guessing is not available inside the class method, so the loop never ends after guessing it right.
And working but ugly solution would be:
print("You guessed it! ")
global guessing
guessing = False
Here is a non infinite loop version without a class. I assumed you wanted to input one number at a time? If not, that could be changed.
Also, the 2 on the end of the randrange only included even numbers, so that wasn't necessary
import random as r
debug = True
real_ans = str(r.randrange(1000, 10000))
if debug:
print(real_ans)
correct = 0
for i in range(len(real_ans)):
player_guess = input("Enter a guess: ")
if str(player_guess) == real_ans[i]:
correct += 1
if correct == 4:
print('You guessed it!')
correct = 0
else:
print('Sorry!', real_ans, 'was correct')
Sample run (Correct)
9692
Enter a guess: 9
Enter a guess: 6
Enter a guess: 9
Enter a guess: 2
You guessed it!
Sample run (Incorrect)
4667
Enter a guess: 5
Enter a guess: 5
Enter a guess: 5
Enter a guess: 5
Sorry! 4667 was correct
import random
from Tools.scripts.treesync import raw_input
x= random.randint(1000,9999)
num=0
while num < 1000 or num > 9999:
num = int(raw_input("Please enter a 4 digit number: "))
if num < 1000 or num > 9999:
print("///wrong input////")
print("system generated number is ",x)
print("The number you entered is ",num)
if num == x:
print("Congrats you win")
else:
rabbit=0
tortose=0
unum = str(num)
snum = str(x)
c1=0enter code here
for i in unum:
c1=c1+1
c2 = 0
for j in snum:
c2=c2+1
if(i==j):
if(c1==c2):
rabbit=1
else:
tortose=1
if rabbit==1:
print("you got rabbit")
elif rabbit==0 and tortose==1:
print("you got tortose")
else:
print("Bad Luck you dont have any match")
enter code here
what i did was just change n from n in range(3) to n in range(4) in line 14
import random as r
guessing = True
real_ans = r.randrange(1000, 10000, 2)
real_ans_str = str(real_ans)
correct = 0
class Player():
def __init__(self):
self.player_guess = input("Enter a guess")
self.evaluate(correct)
def evaluate(self, correct):
for n in range(4):
if self.player_guess[n] == real_ans_str[n]:
correct += 1
if not correct == 4:
print(str(correct)," was correct")
correct = 0
else:
print("You guessed it! ")
guessing = False
while guessing:
Player()

Categories