python语法详解(自动化运维-1)
一、变量
变量定义的规则:
- 变量名只能是 字母、数字或下划线的任意组合
- 变量名的第一个字符不能是数字
- 以下关键字不能声明为变量名
 ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
二、注释
当行注视:# 被注释内容
多行注释:""" 被注释内容 """
多行注释可以赋值给变量,请看以下示例
msg = ''' 这是一个寂寞的天,下着有些伤心的雨, This is a nice day, work hard for more money. ''' print(msg) #结果 这是一个寂寞的天,下着有些伤心的雨, This is a nice day, work hard for more money.
三、用户输入
使用input函数,注意:input函数无论接受什么类型,统一转换为字符串类型
name = input("please enter your name:")
age = input("please enter you age:")
print(name,age)
print(type(age)) #type 函数检查数据类型
#结果
please enter your name:bushaoxun
please enter you age:33
bushaoxun 33
<class 'str'>
四、数据类型
先简要介绍一下数据类型,以后会深入介绍如何操作数据类型
-  int(整型)long(长整型)float(浮点型) # python3 中没有 long 这种类型了,统一为 int.  python2 中超出 int 范围自动改为 long 类型
- 布尔值(真或假,1 或 0)
- 字符串 “hello bushaoxun”
- 列表 [1,2,3,4]
- 元组 (1,2,3) #不可变列表
- 字典 {“name”:bushaoxun,"age":33} # 无序的
- 集合 {1,2,3,4} # 无序的,天生去重,不支持索引
五、表达式语句
if ..... elif .... else # 示例很简单,但是说明了逻辑
user = "bushaoxun"
passwd = "123456"
username = input("please enter your username:")
password = input("please enter your password:")
if user == username:
    print("your username is %s" % username)
elif passwd == password:
    print("your password is %s" % password)
else:
    print("invalid username and password")
while loop # 两个示例
count = 0
while count < 5:
    print(count)
    count += 1
import time
count = 0
while count < 3:
    print(count)
    count += 1
    time.sleep(1)
else:
    print("the num is bigger than ",count-1)
for loop # 同时介绍 break 和 continue 语法
for 循环用法
for i in range(10):
    print("数字:",i)
for i in range(0,10,3):  #按照步长打印
    print("数字:",i)
break # 跳出循环并结束程序
for i in range(0,10,3):  #按照步长打印
    if i > 5:
        break
    print("数字:", i)
else:
    print("end")
#结果
数字: 0
数字: 3
continue # 跳出本次循环,继续执行下一次循环
for i in range(0,10,3):  #按照步长打印
    if i > 5:
        continue
    print("数字:", i)
else:
    print("end")
# 结果
数字: 0
数字: 3
end
六、三元运算
result = 值1 if 条件 else 值2如果条件为真:result = 值1
如果条件为假:result = 值2
如果条件为假:result = 值2
a,b,c = [4,5,6] d = a if a > b else c print(d) # 结果 6
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号