if语句---分支结构
#用户身份验证 username = input("username:") password = input("password:") if username == "admin" and password == "123": print("Login") else: print("Error!")
x = float(input("请输入变量:")) fx = 0.0 if ( x > 1): fx = 3 * x - 5 elif ( x >= -1) and ( x <= 1): fx = x + 2 elif ( x < -1 ): fx = 5 * x + 3 print(fx)
x = float(input('x = ')) if x > 1: y = 3 * x - 5 else: if x >= -1: y = x + 2 else: y = 5 * x + 3 print('f(%.2f) = %.2f' % (x, y))
if语句练习
练习1
必须含有大写,数字,小写的注册
username = input("username:") password = input("password:") A = 'QWERTYUIOPASDFGHJKLZXCVBNM' B = 'zxcvbnmasdfghjklqwertyuiop' C = '1234567890' count1,count2,count3 = False,False,False for i in password: if i in A: count1 = True if i in B: count2 = True if i in C: count3 = True if count1 and count2 and count3: print("ok") else: print("error")
练习2计算器
num1,num2 = map(input("请输入两个数字,例如[1,2]:").split(",")) char_ = input("选择运算,[+,-,*,/]:") if char_ in "+-*/": if char_ == "+": print("%.2f + %.2f = %.2f"%(num1,num2,num1+num2)) if char_ == "-": print("%.2f + %.2f = %.2f"%(num1,num2,num1-num2)) if char_ == "*": print("%.2f + %.2f = %.2f"%(num1,num2,num1*num2)) else: print("%.2f + %.2f = %.2f"%(num1,num2,num1/num2)) else: raise KeyError ('Only choose [+,-,*,/]')
for语句----循环结构
sum = 0 for x in range(101): sum += x print(sum)
需要说明的是上面代码中的range
类型,range
可以用来产生一个不变的数值序列,而且这个序列通常都是用在循环中的,例如:
-
range(101)
-
range(1, 100)
可以产生一个1到99的整数序列。 -
range(1, 100, 2)
可以产生一个1到99的奇数序列,其中的2是步长,即数值序列的增量。
知道了这一点,我们可以用下面的代码来实现1~100之间的偶数求和。
sum = 0 for x in range(2, 101, 2): sum += x print(sum)
练习:随机生成验证码
import random count = 0 for j in range(3): res='' ma='' for i in range(6): n=random.randint(1,2) if (n==1): res = chr(random.randrange(ord("a"),ord("z"))) ma += res else: res = str(random.randrange(0,9)) ma += res print(ma) if(count >0): print("请重试") password = input("请输入验证码:") if (ma == password): print("ok") break else: count += 1 continue if(count >= 3): raise KeyError("error,获取次数过多")
while语句---循环结构
import random answer = random.randint(1, 100) counter = 0 while True: counter += 1 number = int(input('请输入: ')) if number < answer: print('大一点') elif number > answer: print('小一点') else: print('恭喜你猜对了!') break print('你总共猜了%d次' % counter) if counter > 7: print('你的智商余额明显不足')