如果程序要中途退出执行应该怎么办?

软件和网站开发以及相关技术探讨
回复
头像
九天星
帖子: 1440
注册时间: 2007-07-14 20:45

如果程序要中途退出执行应该怎么办?

#1

帖子 九天星 » 2016-10-21 13:08

代码: 全选

address = raw_input('请输入您要刷的网址:')
if address.isdigit():
	print "您输入的网址有误,程序将退出。"
	break                                                                            #问一:我的原意是如果输入的是数字,这里就中断整个程序的执行,退出。
b = int(raw_input('请输入您要刷博的次数:')) - 1
c = 0
while c <= b:
	web.open_new_tab(r'https://'+(address))
	c = c + 1
	time.sleep(1)
else:
	os.system('killall chrome')
	print ('刷博成功完成!')
可是,使用break后,这里会出现语法错误。问二:break只能中断循环吗?
头像
vickycq
帖子: 4507
注册时间: 2011-03-20 13:12
系统: Debian
来自: 山东省寿光县
联系:

Re: 如果程序要中途退出执行应该怎么办?

#2

帖子 vickycq » 2016-10-21 14:06

九天星 写了:break #问一:我的原意是如果输入的是数字,这里就中断整个程序的执行,退出
可用 exit(), sys.exit() 或 quit()
九天星 写了:可是,使用break后,这里会出现语法错误。问二:break只能中断循环吗?
break may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop.It terminates the nearest enclosing loop, skipping the optional else clause if the loop has one.
参考 https://docs.python.org/2/reference/sim ... html#break
Debian 中文论坛 - forums.debiancn.org
欢迎所有 Debian GNU/Linux 用户
头像
九天星
帖子: 1440
注册时间: 2007-07-14 20:45

Re: 如果程序要中途退出执行应该怎么办?

#3

帖子 九天星 » 2016-10-21 14:39

python函数的手册有没有中文版的?
头像
vickycq
帖子: 4507
注册时间: 2011-03-20 13:12
系统: Debian
来自: 山东省寿光县
联系:

Re: 如果程序要中途退出执行应该怎么办?

#4

帖子 vickycq » 2016-10-21 15:02

Debian 中文论坛 - forums.debiancn.org
欢迎所有 Debian GNU/Linux 用户
头像
九天星
帖子: 1440
注册时间: 2007-07-14 20:45

Re: 如果程序要中途退出执行应该怎么办?

#5

帖子 九天星 » 2016-10-21 16:17


哈哈,你找到很多啊。

我就不开贴了,再请教你一个问题。

代码: 全选

address = raw_input('请输入您要刷的网址:')
if address.isdigit():
	print "您输入的网址有误,程序将退出。"
	exit()
b = raw_input('请输入您要刷博的次数:')                       #定义的变量b
if b.isdigit():
	print "刷博中,请等待。。。。。。"
else:
	print "您输入的次数非数字,程序将退出。"
	exit()
e = int(b) - 1                                            #问一:这里我对定义的这个变量e进行减法运算,如果不指定b为int类型,会报错的原因是什么?
c = 0
while c <= e:
	web.open_new_tab(r'https://'+(address))
	c = c + 1
	time.sleep(1)
else:
	os.system('killall chrome')
	print ('刷博成功完成!')

说明: e = b -1 会报错。程序似乎没将b做为一个变量引入。
头像
vickycq
帖子: 4507
注册时间: 2011-03-20 13:12
系统: Debian
来自: 山东省寿光县
联系:

Re: 如果程序要中途退出执行应该怎么办?

#6

帖子 vickycq » 2016-10-21 16:28

代码: 全选

>>> b = raw_input('请输入您要刷博的次数:')
请输入您要刷博的次数:12
>>> b
'12'
>>> type(b)
<type 'str'>
>>> b-1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'int'
>>> 
九天星 写了:#问一:这里我对定义的这个变量e进行减法运算,如果不指定b为int类型,会报错的原因是什么?
变量类型不符无法运算
TypeError: unsupported operand type(s) for -: 'str' and 'int'
九天星 写了:说明: e = b -1 会报错。程序似乎没将b做为一个变量引入。
5楼代码中未见 "e = b -1" 字样
Debian 中文论坛 - forums.debiancn.org
欢迎所有 Debian GNU/Linux 用户
头像
九天星
帖子: 1440
注册时间: 2007-07-14 20:45

Re: 如果程序要中途退出执行应该怎么办?

#7

帖子 九天星 » 2016-10-21 16:42

vickycq 写了:5楼代码中未见 "e = b -1" 字样




未见e = b - 1是因为有报错我改了。虽然改了,没明白是怎么回事,所以请教你的。


现在我明白了,即使输入的是数字也会被认为是str类型的。。。

谢谢你!
回复