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

Python新手技术问询:如何实现判断字符串仅含数字5和6的numberCheck布尔函数

Solution for numberCheck() Function

Hey there! No sweat—let's break this down nice and simple since you're new to Python. The goal is to write a function that checks if every character in the input string is either '5' or '6', right? Here's how to do it step by step.

Core Idea

We need to:

  • Look at every single character in the input string
  • Verify each character is only '5' or '6'
  • If any character fails this check, return False immediately. If all pass, return True.

Code Implementation

def numberCheck(string):
    # Loop through each character in the input string
    for char in string:
        # Check if the character is NOT either '5' or '6'
        if char not in {'5', '6'}:
            return False
    # If we made it through the loop without returning False, all chars are valid
    return True

What's Happening Here?

  • The for char in string loop goes through each character one by one—this lets us validate every part of the input.
  • The char not in {'5', '6'} check is the key: if the current character isn't in our set of allowed characters, we immediately return False (no need to check the rest, which saves a little time!).
  • If the loop finishes without hitting a False, that means every character was either '5' or '6'—so we return True.

Handling Edge Cases (Optional)

If you want to treat an empty string as invalid (since it has no 5s or 6s), just add a quick check at the start:

def numberCheck(string):
    # Return False if the string is empty
    if not string:
        return False
    for char in string:
        if char not in {'5', '6'}:
            return False
    return True

Test It Out!

Try running these examples to make sure it works:

print(numberCheck("5566"))    # Output: True
print(numberCheck("56565"))   # Output: True
print(numberCheck("55a6"))    # Output: False (has an 'a')
print(numberCheck("7"))       # Output: False (has a '7')
print(numberCheck(""))        # Output: False (if you added the empty string check)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:09:11