2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > python中for else举例_Python 中for...esle和while...else语法

python中for else举例_Python 中for...esle和while...else语法

时间:2023-12-01 08:29:07

相关推荐

python中for else举例_Python 中for...esle和while...else语法

lucky_num = 19

#首先定义一个幸运数字,这样条理比较清晰

#action = True

guess_count = 0

while guess_count < 3:

#限制用户输入

input_num = int(input("Input the guess num: "))

#if lucky_num == input_num:

#print("Bingo!")

#action = False

#break强制终端循环语句,避免陷入死循环之中

if input_num > lucky_num:

print("The real number is smalller!")

elif input_num < lucky_num:

print("The real number is bigger...")

else:

print("Bjngo!...")

break

guess_count += 1

else:

print("Too many retrys!")

首先我们执行三次没有测对的情况如下:

Input the guess num: 1

The real number is bigger...

Input the guess num: 2

The real number is bigger...

Input the guess num: 100

The real number is smalller!

Too many retrys!

从结果上可以看出,最后执行了else分支语句(Too many retrys!),提示用户输入过多的次数,正常情况下是执行else语句的。下面我们来看

一下非正常退出情况下:

用户猜测正确:

Input the guess num: 1

The real number is bigger...

Input the guess num: 19

Bjngo!...

从上面结果我们可以看出,当用户猜对数字后,break了一下,推出了while...else语句,else语句没有正常执行。

2.return情况#首先定义一个幸运数字,这样条理比较清晰

#action = True

#限制用户输入,如果三次没有猜对则退出循环

def count():

lucky_num = 19

guess_count = 0

while guess_count < 3:

input_num = int(input("Input the guess num: "))

#if lucky_num == input_num:

#print("Bingo!")

#action = False

#break强制终端循环语句,避免陷入死循环之中

if input_num > lucky_num:

print("The real number is smalller!")

elif input_num < lucky_num:

print("The real number is bigger...")

else:

print("Bjngo!...")

return guess_count

guess_count += 1

else:

print("Too many retrys!")

numbers = count()print(numbers)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。