首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >停止python的最后一条语句

停止python的最后一条语句
EN

Stack Overflow用户
提问于 2013-11-07 17:23:14
回答 4查看 120关注 0票数 0

我目前正在编写一个程序来解决毕达哥拉斯定理。然而,我在程序中有一个bug。每当我输入一个长度为a或b的负数时,它就会打印出"A不能小于零“,然后继续对C进行求解,并打印出C的长度,即使用户还没有输入b。如果用户输入一个负数,它就会打印出语句"A不能小于零“,然后再循环输入边的长度,而不是在打印出重定向到末尾的语句之后,它现在的位置如何?

这是我的代码:

代码语言:javascript
运行
复制
 import math
    print"This program will solve the pythagorean theorem for you"
    unit=raw_input('Enter the unit you will be using')
    a=float(raw_input('Enter the length of side a'))
    if a<=0:
      print"A cannot be less than zero"
    else:
        b=float(raw_input('Enter the length of side b'))
    if b<=0:
      print"B cannot be less than zero"
    else:
        c2=(a**2)+(b**2)
        c=math.sqrt(c2)
        c=str(c)
        print "The length of side C is: "+ c + " " + unit + "."
EN

Stack Overflow用户

发布于 2013-11-07 17:48:58

免责声明:我使用的是Python的不同版本,所以里程数可能会有所不同

代码语言:javascript
运行
复制
import math

a = 0
b = 0

def py_theorem(a, b):
    return(a**2 + b**2)


unit = raw_input('Enter the unit you will be using: ')

while a <= 0:
a = float(raw_input('Enter the length of side A: '))
if a <= 0:
    print('A cannot be less than 0.')

while b <= 0:
b = float(raw_input('Enter the length of side B: '))
if b <= 0:
    print('B cannot be less than 0.')

print('The length of the 3rd side C is %d %s') % (py_theorem(a,b), unit)

现在,如果您看我的代码a,b最初是0,这样您就可以执行while循环(否则您会得到一个错误,解释器直到那时还不知道a,b)。然后重复分别要求a、b的语句,直到得到有效的输入(在一般意义上是有效的,我们没有错误检查,如果使用字符串怎么办??>.<),现在打印有点古怪,我肯定会查看Python,看看%d %s等等是什么。然后,我们将方法的返回(见顶部的def py_theorem )与一个单元一起传递给字符串。注意,该函数分别采用两个参数a、b。

票数 0
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19842500

复制
相关文章

相似问题

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