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
Falseimmediately. If all pass, returnTrue.
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 stringloop 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 returnFalse(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 returnTrue.
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
相关产品推荐
相关产品推荐

