简单的Python:关于代码结构

时间:2017-11-13 03:21:47

标签: python if-statement structure

print ("This program reads an unsigned binary number of arbitrary length 
\nand tries to compute the decimal equivalent. The program reports an error 
\nif the input number contains characters other than 0 and 1.")
dec = 0
bin = 0
factor = 1

print ("Enter the binary number: ")
bin = int(input())

while(bin > 0):

    if((bin % 10) == True):
        dec += factor
        bin //= 10
        factor = factor * 2


    else:
        print("unrecognized bit:")


print ("I think your binary number in decimal form is: " ,dec)

这是我的程序代码,该程序应该将用户的二进制数转换为十进制数。它工作正常,但我正在尝试添加一个“else”语句,如果用户输入的数字不是0或1,将打印“无法识别的位”。它的类型有效,但程序打印“无法识别的位”即使用户只输入0和1。这不应该发生。另外,请参阅相关图片。我已经输入了12343来测试程序,并且它表示无法识别的位是好的,但它也取该数字中的“1”并将其转换为16,这不应该发生,它应该只是说无法识别的位。我认为这两个问题很容易解决,但我不确定。谢谢!

picture

3 个答案:

答案 0 :(得分:0)

这是一个缩进的问题。无论if else声明说什么,你的最后一行都会打印出来。当您到达无法识别的符号时,您还希望退出while循环。现在它打印else语句但保持循环。

这是一个修复,我添加了一个中断条件来退出else,然后添加了一个布尔值,看看我们是否可以输出最后一个print语句:

print ("This program reads an unsigned binary number of arbitrary length tries to compute the decimal equivalent. The program reports an error if the input number contains characters other than 0 and 1.")
dec = 0
bin = 0
factor = 1
success = 1

print ("Enter the binary number: ")
bin = int(input())

while(bin > 0):

  if((bin % 10) == True):
      dec += factor
      bin //= 10
      factor = factor * 2


  else:
      print("unrecognized bit:")
      success = 0
      break

if(success):
  print ("I think your binary number in decimal form is: " ,dec)

答案 1 :(得分:0)

两个问题:

  1. 只有当二进制输入的余数为1时才满足条件,因为0 == False的计算结果为True。也就是说,如果您的号码以零结尾(或实际上包含为零),(bin%10) == True将评估为False(侧点:那里'实际上没有必要在右边添加== True

  2. 无论您正在查看的数字是factor还是dec,您都会1添加0。如果遇到零,你就不应该加入。

  3. 所以你的代码应该是这样的:

    while(bin > 0):
        remainder = (bin % 10)
        if remainder in (0,1):
            dec += factor * remainder
            bin //= 10
            factor = factor * 2
    
        else:
            print("unrecognized bit:")
            break
    

答案 2 :(得分:0)

您需要测试输入以确保其合法。您可以使用正则表达式执行此操作。将bin = int(input())替换为:

import re    
inp = input()
if re.match('.*[^01]+.*', inp) is not None:
    print("illegal character in input, must be ones and/or zeros")
    exit()

bin = int(inp)

如果输入包含除1或0以外的任何内容,则会打印非法字符消息。