首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >简单Python:关于代码的结构

简单Python:关于代码的结构
EN

Stack Overflow用户
提问于 2017-11-13 03:21:46
回答 3查看 49关注 0票数 0
代码语言:javascript
运行
复制
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)

这是我的程序代码,该程序应该将用户的二进制数字转换为十进制数。它可以正常工作,但我正在尝试添加一条“other”语句,如果用户输入了0或1以外的数字,它将打印“未识别位”。它可以工作,但是程序打印“未识别位”,即使用户只输入了0和1。这种情况不应该发生。此外,请参阅图片相关。我输入了12343来测试这个程序,它说不被识别的比特是好的,但它也接受了这个数字中的"1“,并将它转换为16,这是不应该发生的,它应该只是说不被识别的位。我认为这两个问题很容易解决,但我只是不确定。谢谢!

图片

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-11-13 03:45:37

两个问题:

  1. 只有当二进制输入的余数为1时,条件才能满足,因为0 == False的计算结果为True。也就是说,如果数字以零结尾(或者实际上包含一个零),(bin%10) == True将计算为False (边点:实际上不需要在右边添加== True )。
  2. 您将factor添加到dec中,而不管您所看到的数字是1还是0;如果遇到零,则不应该添加。

所以您的代码应该如下所示:

代码语言:javascript
运行
复制
while(bin > 0):
    remainder = (bin % 10)
    if remainder in (0,1):
        dec += factor * remainder
        bin //= 10
        factor = factor * 2

    else:
        print("unrecognized bit:")
        break
票数 0
EN

Stack Overflow用户

发布于 2017-11-13 03:38:50

这是一个压痕的问题。不管if matter语句说什么,最后一行都会打印出来。当您到达未识别的符号时,您还希望退出while循环。现在,它打印the语句,但继续循环。

这是一个修正,我在其中添加了一个中断条件以退出where,然后添加了一个布尔值,以查看是否可以输出最后一个print语句:

代码语言:javascript
运行
复制
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)
票数 0
EN

Stack Overflow用户

发布于 2017-11-13 03:57:13

您需要测试您的输入,以确保它是合法的。您可以使用正则表达式来完成这一任务。将bin = int(input())替换为:

代码语言:javascript
运行
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47256632

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档