Study python_02
Posted 千纪
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Study python_02相关的知识,希望对你有一定的参考价值。
分支结构
简单的使用if语句
使用if-else
import random
# 调用一个随机数包(只看if的情况可忽略) n1 = random.randrange(100) n2 = random.randrange(100) print(n1,n2) jg = int(input()) if jg == (n1 + n2): print(‘结果为真‘) else: print(‘结果为假‘)
简单的使用if语句
使用if-elif-else
a,b,c = map(float,input("Enter a,b,c : ").split())# 连续输入三个数字 i = b * b - (4 * a * c) if i >0 : r1 = (-b + (b * b - (4 * a * c))** 0.5) / 2 * a r2 = (-b - (b * b - (4 * a * c))** 0.5) / 2 * a print("The roots are {} and {}",r1,r2) elif i == 0 :# 使用elif再次判断 print(-b / 2 * a) else :# 使用else进行最后的输出 print("The equation has no real roots")
循环结构
简单的使用for语句
password = input(‘passward:‘)# 输入一串字符,必须包括数字,大小写字母 count1,count2,count3 = False,False,False for i in password:# 从第一个字母开始判断 if i <= ‘Z‘ and i >=‘A‘: count1 = True if i <= ‘z‘ and i >=‘a‘: count2 = True if i <= ‘9‘ and i >=‘0‘: count3 = True if count1 and count2 and count3: print(‘ok‘) else: print(‘必须包含大小写和数字‘)
简单的使用while语句
i = 0 while i<10: print(‘我是大牛‘) i += 1
有点头疼的for和if-elif
import numpy as np A = ‘石头‘ B = ‘剪刀‘ C = ‘布‘ for i in range(6):# 循环6次 res = np.random.choice([A,B,C]) res1 = np.random.choice([A,B,C]) print(‘电脑出的:‘,res,‘你出的‘,res1) if (res == A) and (res1 == B): print(‘你输了‘) elif (res == A) and (res1 == C): print(‘你赢了‘) elif (res == B) and (res1 == C): print(‘你输了‘) elif (res == B) and (res1 == A): print(‘你赢了‘) elif (res == C) and (res1 == A): print(‘你输了‘) elif (res == C) and (res1 == B): print(‘你赢了‘) elif (res == A) and (res1 == A): print(‘平局‘) elif (res == B) and (res1 == B): print(‘平局‘) elif (res == C) and (res1 == C): print(‘平局‘)
以上是关于Study python_02的主要内容,如果未能解决你的问题,请参考以下文章