Reputation:
Okay, I'm working on a project for class, and I'm stuck on this logic error. I've noted the rest of the original errors after I fixed them in my code...and I feel like I know where the logic error is. I'm just unsure how to fix it. Can I get some help?
Thanks in advance.
import random
def display_title():
print("Guess the number!")
print()
def set_limit():
print("Enter the upper limit for the range of numbers: ")
limit = int(input())
return limit
def count(): ## had to add count being defined as below it was unrecognized by python.
count +=1
def play_game(limit):
global count
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 ## See def count
elif guess >= number:
print("Too high. ")
count ## See def count
elif guess == number: ## Pretty sure my logic error is here <----
print("You guessed it in " + str(count) + " tries.\n")
return
def main(): ## syntax error, no : was here
display_title()
again = "y"
while again.lower() == "y":
limit = set_limit()
play_game(limit) ## limit wasn't set inside, causing a missing positional argument
again = input("Play again? (y/n): ")
print()
print("Bye!")
if __name__ == "__main__":
main()
Upvotes: 1
Views: 118
Reputation: 22370
print()
to print an empty line.input
no need to have a separate print
statement before.count
can be defined within play_game
and it should initialized to 1
rather than the default 0
because even if the user guesses on the first try they had 1 guess.elif guess >= number:
needs to be changed to elif guess > number:
answer
converted to lowercase equals y
you can call main()
again to restart the game. I fixed the above issues in the code below:
import random
def display_title():
print("Guess the number!\n")
def set_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
count = 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")
break
def main():
display_title()
limit = set_limit()
play_game(limit)
again = input("Play again? (y/n): ")
if again[0].lower() == 'y':
main()
else:
print("Bye!")
if __name__ == "__main__":
main()
Try it here!
Upvotes: 0
Reputation: 648
I have an idea. Try changing the >= sign 3 lines above to just > number. Because otherwise it will never get to the "if guess == number" because it will stop for "if guess >= number" every time even if the guess is right.
This is because >= means greater than or equal to. I really hope this helps.
Upvotes: 1