#python #loops #input
Вопрос:
У меня есть классный проект, в котором я играю в угадайку чисел. У меня есть следующие требования:
#1. A main() function that holds the primary algorithm, but itself only passes information among other functions. main() must have the caller for random_int()
#2. A function called in main() (not nested in main()!) that compares the user's guess to the number from random_int() and lets the user know if it was too high or too low.
#3. A function called in main() that asks the user for a new guess.
#4. A function that prints out a string letting the user know that they won.
#5. Tell the user how many guesses it took them to get the correct answer.
Я изо всех сил пытаюсь определить, как отслеживать количество раз, когда пользователь угадывает, прежде чем они достигнут правильного числа, и отображать это число в строке. В настоящее время у меня есть цикл while в функции main():
def main(random_int, new_guess, user_attempts): #Function that holds the main algorithim and calls all of the functions in the program
r = random_int(size) #Setting parameters to generate a random number between 1 - 1000
n = new_guess() #Assigns the user's input as "guess", and calls the function "new_guess"
while n != r: #While loop to continue until user guesses correct number
if n > r:
print("The number you guessed is too high, guess again.")
elif n < r:
print("The number you guessed is too low, guess again.")
attempts = 1
n = new_guess()
if n == r: #If user guesses correct number, call "win" function
win(random_int, new_guess, user_attempts)
И я пытаюсь взять значение attempts
и сохранить его в функции user_attempts():
, где я могу вызвать его в функции win():
. Я продолжаю получать сообщение об ошибке — TypeError: 'int' object is not callable
Полная программа для контекста:
#Python number guessing game
#Import randrange module
from random import randrange
#Initialize variables
attempts = 0
size = 1000
def random_int(size): #Generates a random integer from given parameters (size)
return randrange(1, size 1)
def new_guess(): #Prompts the user to enter an integer as their guess
guess = int(input("Enter your guess (between 1 - 1000): "))
return guess
def user_attempts():
a = attempts
return a
def win(random_int, new_guess, user_attempts): #Prints that the answer is correct, along with the number of guesses it took
random_int = random_int(size)
a = user_attempts()
if a >= 2: #If it took the user more than 1 attempt, uses "guesses" for proper grammar
print("You guessed the correct number", str(random_int()), ", you win! It took you ", str(user_attempts()), " guesses.")
elif a < 2: #If it took the user only 1 attempt, uses "guess" for proper grammar
print("You guessed the correct number", str(random_int()), ", you win! It took you ", str(user_attempts()), " guess.")
def main(random_int, new_guess, user_attempts): #Function that holds the main algorithim and calls all of the functions in the program
r = random_int(size) #Setting parameters to generate a random number between 1 - 1000
n = new_guess() #Assigns the user's input as "guess", and calls the function "new_guess"
while n != r: #While loop to continue until user guesses correct number
if n > r:
print("The number you guessed is too high, guess again.")
elif n < r:
print("The number you guessed is too low, guess again.")
attempts = 1
n = new_guess()
if n == r: #If user guesses correct number, call "win" function
win(random_int, new_guess, user_attempts)
main(random_int, new_guess, user_attempts) #Calls the "main" function, runs the program
Ответ №1:
Для вашей ошибки « int
объект не может быть вызван» это означает, что вы вызываете целочисленную переменную, как будто это функция. Я думаю, что именно там ты и делаешь:
random_int = random_int(size)
Первый вызов random_int
может сработать, если это функция, но затем вы назначаете локальную переменную, называемую random_int
возвращаемым значением этой функции, которое является целым числом. Поэтому при следующем вызове random_int
это будет целое число , а не функция. Чтобы исправить это, вам следует использовать другое имя переменной , кроме random_int
того, поскольку именно так вы назвали свою функцию.
=
против =
Похоже, у тебя есть:
attempts = 1
Но вы, вероятно, собираетесь поменять
местами и =
:
attempts = 1
attempts = 1
это похоже attempts = 1
на то , где
унарный позитив (например, унарный негатив).