码迷,mamicode.com
首页 > 编程语言 > 详细

Python入门小程序(一)

时间:2018-06-21 23:49:42      阅读:304      评论:0      收藏:0      [点我收藏+]

标签:code   wan   循环语句   post   input   ESS   布尔   pytho   语句   

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

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

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

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

###运行结果:
技术分享图片

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("猜对!游戏结束!")

###运行结果:
技术分享图片

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逻辑运算操作符可以将任意表达式连接在一起,并得到一个布尔类型的值。

Python入门小程序(一)

标签:code   wan   循环语句   post   input   ESS   布尔   pytho   语句   

原文地址:http://blog.51cto.com/13820241/2131519

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!