我的验证循环没有正常工作

huangapple go评论63阅读模式
英文:

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(&#39;Enter a binary number between 4 and 12 bits: &#39;)

numberSet = set(binaryNumber)
binary = {&#39;0&#39;,&#39;1&#39;}
while len(binaryNumber) &lt; 4 and len(binaryNumber) &gt; 12:
    while numberSet != binary or numberSet != {&#39;0&#39;} or numberSet != {&#39;1&#39;}: 
        binaryNumber = input(&#39;Invalid entry! Please enter a binary number between 4 and 12 bits: &#39;)

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(&#39;Enter a binary number between 4 and 12 bits: &#39;)

while True:
    numberSet = set(binaryNumber)
    binary = {&#39;0&#39;, &#39;1&#39;}
    if len(binaryNumber) &lt; 4 or len(binaryNumber) &gt; 12 or not numberSet.issubset(binary):
        binaryNumber = input(&#39;Invalid entry! Please enter a binary number between 4 and 12 bits: &#39;)
    else:
        break

huangapple
  • 本文由 发表于 2023年2月24日 10:11:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552045.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定