前言
python 对于运维人员来说十分重要
实验在pycharm之上完成
重命名:shift + F6
if(单一条件)
-
例
if condition:
success thing
…age = 12 if age >= 18: print('welcome to netbar')
if(if…else…)
-
例
if condition:
success thing
else:
failed thingage = 18 if age >= 18: print('Welcome to netbar') else: print('Please go home and do homework')
if(if…elif…else)
-
例:
if c1:
thing
elif c2:
thing
…
else:
thingholiday_name = 'a1' if holiday_name == 'a2': print('a2') elif holiday_name == 'a3': print('a3') else: print('a4')
if(嵌套)
-
例:
if c1:
thing
if c2:
…
else:
else:have_ticket = True knife_length = 29 if have_ticket: print('Please come in') if knife_length > 20: print('length:%d ;too long,not permitted!' %knife_length) else: print('length: %d;acceptable long,come in' %knife_length) else: print('Please buy ticket')
运行结果
Please come in length:29 is too long not permitted!
if (and,or)
-
例:
and:
condition1 and condition2
True False
or:
condition1 and condition2
True Falsepython_score = 70 c_score = 30 if python_score > 60 and c_score >60: print('pass') else: print('failed') value = input('Value:') if not value: print('Check your input!')
if(练习)
-
例:
“”"
1.从控制台输入要出的拳 —石头(1)/剪刀(2)/布(3)
2.电脑随即出拳–先假定电脑只会出石头,完成整体代码功能
3.比较胜负
石头 胜 剪刀
剪刀 胜 布
布 胜 石头
“”"import random #1.player player = int(input('Your Choice:')) #2.computer computer = random.randint(1,3) print(computer) #3.compare if((player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1)):
其他
random
在python中,要使用随机数,首先需要导入随即数模块 – ‘工具包’
导入模块后,可以直接在模块名称后面敲一个.然后Tab键,会提示该模块中>包含的所有函数
-
例:
import random
random.randint(a,b),返回[a b]之间的整数,包含a和brandom.randint(12,20):生成随机数n: 12 <= n <= 20 random.randint(20,20): 结果永远是20 random.randint(20,12):结果会报错:下限必须小于上限