Python猜数字游戏开发求助:实现1-100范围外输入的判断提示功能
Hey there! Let's break down what's going on with your guess-the-number game and fix that out-of-range check you're trying to add.
The Core Problem in Your Code
Your current condition order is preventing the guess > 100 check from ever running. Think about it: if someone enters a number greater than 100, since the random number is always between 1-100, guess > number will always be true first. That means your code hits that elif branch and skips the range check entirely.
Fixed & Improved Version
Here's a revised version of your code that fixes the range issue, plus some quality-of-life tweaks to make the game actually playable (your original code only let users guess once!):
import random running = True while running: attempts = 0 number = random.randint(1, 100) print("gissa talet") print("Du ska nu gissa ett tal mellan 1 och 100, så varsågod...") # Inner loop for repeated guesses until correct while True: print("skriv in ett tal") guess = int(input()) attempts += 1 # First check if input is out of bounds (priority!) if guess < 1 or guess > 100: print("Du måste skriva in ett tal mellan 1 och 100! Försök igen.") continue # Skip rest of the loop, let user try again # Check if guess is correct if guess == number: print(f"Grattis du har vunnit! Du behövde {attempts} försök. Programmet är slut") break # Guess is too small elif guess < number: if (number - guess) < 4: print("Ditt tal är för litet. Gissa på ett större tal! Du är dock nära och det bränns!") else: print("Ditt tal är för litet. Gissa på ett större tal!") # Guess is too large (and within 1-100 range) else: if (guess - number) < 4: print("Ditt tal är för stort. Gissa på ett mindre tal! Du är dock nära och det bränns!") else: print("Ditt tal är för stort. Gissa på ett mindre tal!") # Let user choose to play again play_again = input("Vill du spela igen? (ja/nej): ").lower() if play_again != "ja": running = False print("Tack för att du spelade!")
Key Changes Explained
- Range check first: By putting the
guess < 1 or guess > 100check at the top, we catch invalid inputs immediately before comparing to the target number. - Repeated guesses: Added an inner
while Trueloop so users can keep guessing until they get it right, instead of ending after one attempt. - Attempt counter: Used your unused
attemptsvariable to track how many tries it took the user to win. - Play again option: Added a prompt to let users restart the game without closing the program.
内容的提问来源于stack exchange,提问作者Kent Karlsson




