英文:
My validation loops are not working properly
问题
我正在尝试验证用户输入的代码是否为一个二进制字符串,长度在4到12个字符之间。目前的代码无法验证是否为二进制字符串,也无法验证长度是否在4到12个字符之间。
以下是我所指的代码部分:
binaryNumber = input('Enter a binary number between 4 and 12 bits: ')
numberSet = set(binaryNumber)
binary = {'0','1'}
while len(binaryNumber) < 4 and len(binaryNumber) > 12:
while numberSet != binary or numberSet != {'0'} or numberSet != {'1'}:
binaryNumber = input('Invalid entry! Please enter a binary number between 4 and 12 bits: ')
请告诉我需要进行哪些修改,以使其正常工作?提前感谢您!
我尝试了数字1。我尝试了除0和1以外的数字。
英文:
I am trying to validate that code inputted by a user is a binary string that is between 4 and 12 characters long. As it is now, it does not validate that it is a binary string or between 4 and 12 characters long
Here's the section of my code that I am referring to:
binaryNumber = input('Enter a binary number between 4 and 12 bits: ')
numberSet = set(binaryNumber)
binary = {'0','1'}
while len(binaryNumber) < 4 and len(binaryNumber) > 12:
while numberSet != binary or numberSet != {'0'} or numberSet != {'1'}:
binaryNumber = input('Invalid entry! Please enter a binary number between 4 and 12 bits: ')
Could you tell me what I need to revise, so that I can make it work? Thank you in advance!
I tried the number 1. I tried using numbers besides 0 and 1.
答案1
得分: 0
第一个while循环中的条件应该是"或"而不是"和",因为二进制数的长度不会同时小于4且大于12。
对于你的代码,我做了一些修改,使结构更清晰(主观),并在输入正确时添加了一个else: break
(可选):
binaryNumber = input('输入一个4到12位的二进制数字:')
while True:
numberSet = set(binaryNumber)
binary = {'0', '1'}
if len(binaryNumber) < 4 or len(binaryNumber) > 12 or not numberSet.issubset(binary):
binaryNumber = input('无效输入!请再次输入一个4到12位的二进制数字:')
else:
break
英文:
The condition in the first while loop should be "or" instead, not "and", as the length of the binary number will not be both less than 4 and greater than 12 at the same time.
Some edits to your code, with a cleaner structure (subjectively) and a else: break
when the input is correct (optional):
binaryNumber = input('Enter a binary number between 4 and 12 bits: ')
while True:
numberSet = set(binaryNumber)
binary = {'0', '1'}
if len(binaryNumber) < 4 or len(binaryNumber) > 12 or not numberSet.issubset(binary):
binaryNumber = input('Invalid entry! Please enter a binary number between 4 and 12 bits: ')
else:
break
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论