当前位置 : 主页 > 编程语言 > python >

Python自动化--6. 写一个python程序

来源:互联网 收集:自由互联 发布时间:2022-06-15
​​Python自动化--1.Python环境安装-linux ​​ ​​Python自动化--2.Python变量 ​​ ​​Python自动化--3.Python数据类型​​ ​​Python自动化--4.python类型转换​​ ​​Python自动化--5. if判断语句

​​Python自动化--1.Python环境安装-linux ​​ 

​​Python自动化--2.Python变量 ​​ 

​​Python自动化--3.Python数据类型​​  

​​Python自动化--4.python类型转换​​  

​​Python自动化--5. if判断语句 ​​ 

​​Python自动化--6. 写一个python程序​​​

​​Python自动化--7. 函数的定义和调用​​


6. python程序

6.1 使用vim写python程序

生产环境中,我们会将程序的代码写成一个文件,这个文件就成为一个python程序文件,文件名以 .py 为结尾。

#猜数字

vim test1_gustnu.py

#!/usr/bin/env python3

#file name test1_gustnu.py 猜数字

print("猜数字游戏开始")

n = input("请输入一个数字:")

n = int(n)

if n == 18:
print("猜对了!")
elif n > 18:
print("大了!")
else:
print("小了!")

执行python文件

python3 test1_gustnu.py
#或
chmod +x test1_gustnu.py
./test1_gustnu.py

6.2 while 循环

语法:

while 条件表达式:
条件表达式为真,就执行代码,必须缩进 4个空格
多行代码需保持缩进一致

条件表达式可以是:

True #布尔值的True

1 < 11 #凡是在if语句中使用的判断表达式,都可以使用

猜数字优化版

#!/usr/bin/env python3

#file name test1_gustnu.py 猜数字

print("猜数字游戏开始")
while True:
n = input("请输入一个数字:")
if not n:
continue #拒绝,回到上一步
if n == 'q':
print("程序退出")
break #输入q退出
n = int(n)

if n == 18:
print("猜对了!")
break #猜对跳出循环
elif n > 18:
print("大了!")
else:
print("小了!")
exit("退出程序")
上一篇:#yyds干货盘点#python传入参数
下一篇:没有了
网友评论