Python入门小程序(一)

学习了FishC的Python零基础入门第4节,本次的内容是Python的while循环语句和条件语句。

1. 用一个条件语句实现猜数字的小程序

程序设定一个数字,用户输入一个数字,判断是否猜对。

temp=input("猜猜我心中的数字:")
guess=int(temp)
if guess==8:
    print("猜对!")
else:
    print("猜错了!")
print("游戏结束!")

###运行结果:
image

2. 改进程序猜随机数字

上一个程序中,用户猜错要重新运行程序,嵌套while循环让用户可以一直猜,知道猜对。另外,系统设定的数字不能是静态的,要改为随机生成。

#改进
import random
temp = input("猜猜我心中的数字:")
guess=int(temp)
secret=random.randint(1,10)
while guess!=secret:
if (guess<secret):
print("猜小了!")
else:
print("猜大了!")
temp=input("猜猜我心中的数字:")
guess = int(temp)
print("猜对!游戏结束!")

###运行结果:
image

3. 改进程序限定用户的机会

现在,用户只能有三次机会来猜数字。我们可以修改循环的条件,当用户没猜中并且机会还没用完,就一直执行这个循环体。


import random
temp = input("猜猜我心中的数字:")
guess = int(temp)
secret = random.randint(1,10)
i = 2
while (guess!=secret)and(i):
if (guess < secret):
print("猜小了!")
print("剩余机会次数:",i)
else:
print("猜大了!")
print("剩余机会次数:", i)
temp = input("猜猜我心中的数字:")
guess = int(temp)
i = i - 1

else:
if(i>0):
print("猜对!游戏结束!")
else:
print("你的机会用完!")



###运行结果:
![image](https://raw.githubusercontent.com/wangshujuan/PostImage/master/PythonBasic1/%E6%8D%95%E8%8E%B73.PNG)

## 4. 总结一下要点
*  在 python 中,while … else 在循环条件为 false 时执行 else 语句块。
*  Python中的and逻辑运算操作符可以将任意表达式连接在一起,并得到一个布尔类型的值。

猜你喜欢

转载自blog.51cto.com/13820241/2131519
今日推荐