Certainly! Below is a Python program that implements the guessing game for a specific float, matching your requirements:
def guessing_game(target_float):
print("Welcome to the guessing game!")
print("Try to guess the float (accurate to within 2 decimal places).")
while True:
try:
# Prompt the user for their guess
guess = float(input("Enter a guess: "))
# Compare the guessed value with the target value rounded to 2 decimal places
if round(guess, 2) == round(target_float, 2):
print("Correct!")
break # Exit the loop if the guess is correct
elif guess > target_float:
print("Too high!")
else:
print("Too low!")
except ValueError:
print("Invalid input. Please enter a floating point number.")
if __name__ == "__main__":
# You can change this float value to test different scenarios
target_number = 3.3312
guessing_game(target_number)
Explanation of the Code:
- We define a function
guessing_game
that takes a floating-point number (target_float
) as an argument. - Inside the function, we use a
while True:
loop for continuous guessing. - We prompt the user for their guess and attempt to convert it to a float.
- We check if the rounded guess (to 2 decimal places) is equal to the rounded target number:
- If they are equal, print "Correct!" and break out of the loop.
- If the guess is higher than the target, print "Too high!".
- If the guess is lower than the target, print "Too low!".
- We handle invalid inputs with a
try-except
block to catchValueError
exceptions if the user does not enter a valid float. - The game starts in the
if __name__ == "__main__":
block with a predefined target float (which you can modify as needed).
To run the program:
- Simply copy the code into a Python environment and execute it. The program will prompt you to guess the target float until you guess it correctly or provide an invalid input.