def p_parameter(p):
if p < 10 or p > 100:
int(input("Please try again: "))
newp = p
return newp
else:
newp <10 or newp >100
input("Good bye")
bye()
def main():
speed(0)
R=100
r=4
p=int(input("Please enter a number between 10 and 100: "))
p_parameter(p)
t_iter(R,r,p)
Xcord(R,r,p,t_iter(R,r,p))
Ycord(R,r,p,t_iter(R,r,p))
input("Hit enter to close porgram")
bye()
main()
这是我为一个绘制螺旋图的程序编写的代码。程序运行良好,但是我在这里发布的是我试图让用户为p
输入一个介于10-100之间的值。在
我要做的是检查p
是<;10还是p
>;100。如果是,那么给用户一个机会重新输入一个新的值p
,只要它符合允许的限制就使用它。在第二次检查用户是否仍然输入了不正确的值p
之后,我希望程序关闭。在
问题是它检查“p”,然后再次请求p
,但它只接受第一个“p”值,而不执行第二个检查或给p
新值。在
你应该在函数中提示一下。这是编写此类验证的标准习惯用法:
这是你可以建造一个很好的装饰工的东西之一
^{pr2}$解决方案的问题和更正:
再次向用户请求
p
,但不要将这个新值赋给newp
变量,如下所示:您的
else
语句正在检查newp
变量范围之外的newp
上的条件,该变量位于if
语句内。您应该将检查newp
变量封装在if
语句中,如下所示:当程序没有输入
if
语句时,p_parameter()
函数中没有return
语句。所以应该是这样的:对您的问题的建议解决方案:
while True:
无限循环和break
语句退出。在使用}块和{}
try
、except
和{要关闭程序,您可以:
ctrl+c
(我的个人偏好)、或while
循环的次数,然后使用sys.exit(0)
来强制程序退出,如果达到了一个限制(注意:首先您需要import sys
才能使用它;我认为您的bye()
就是这样做的)。在把它们放在一起:
在
main()
函数中,删除input()
语句,只调用p_parameter()
函数,如下所示: p=p_参数()按如下方式定义
p_parameter()
函数:相关问题 更多 >
编程相关推荐