You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python while循环条件问题:实现分数格式输入校验循环

How to Validate "Score/Max" Input in a Python While Loop

Hey there! Let's sort out that input validation for your score format. Your current code's loop condition isn't doing any actual format checking—let's fix that step by step.

The Problem with Your Current Code

Your loop checks if num1 != '?/?', which doesn't make sense for real user input. It won't validate whether the input follows the score/max format, so it'll keep looping even if someone enters something like "abc" or "100".

A Robust Solution

We need to check three key things for valid input:

  • The input contains exactly one / to split into two parts
  • Both parts are valid integers
  • The max score is positive, and the score is within a reasonable range (0 to max score)

Here's the full code with explanations:

while True:
    score_input = input("Please enter your score in the form score/max (eg. 30/50): ")
    # Split the input using '/' as the separator
    parts = score_input.split('/')
    
    # Check if we have exactly two parts after splitting
    if len(parts) != 2:
        print("Oops! Invalid format. Make sure to use 'score/max' like 30/50.")
        continue  # Skip to the next loop iteration
    
    # Try converting both parts to integers (strip handles accidental spaces)
    try:
        score = int(parts[0].strip())
        max_score = int(parts[1].strip())
    except ValueError:
        print("Hmm, both score and max need to be whole numbers. Try again!")
        continue
    
    # Add extra checks for logical validity
    if max_score <= 0:
        print("Max score can't be zero or negative—that doesn't make sense!")
        continue
    if score < 0 or score > max_score:
        print(f"Score has to be between 0 and {max_score}. Let's try again.")
        continue
    
    # If we get here, input is valid!
    print(f"Perfect! Your score is {score} out of {max_score}.")
    break  # Exit the loop

Breakdown of the Logic

  1. while True: Creates an infinite loop that only exits when we hit the break statement (after valid input).
  2. split('/'): Splits the input string into a list. For valid input, this list will have exactly two elements.
  3. try-except Block: Safely converts the split parts to integers. If either part isn't a number, it catches the ValueError and prompts the user again.
  4. Extra Validation: Ensures the max score is positive and the score isn't negative or higher than the max (you can remove these if you don't need them, but they make the program more user-friendly).

This way, the loop will keep asking for input until the user enters something that matches the required format and makes logical sense.

内容的提问来源于stack exchange,提问作者Ububtunoob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:55:08