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

 使用break

import random
c = random.randrange(1000,9999)
print('验证码:',c)
for i in range(3):
    b = int(input('请输入验证码:'))# 结果不要应该有四次输出,懒得改
    if b == c:
        print('输入正确')
        break
    else:
        print('输入错误,请重试')
else:
    print('请退出账号重试')

有点头疼的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('平局')

作者: 千纪

出处: https://www.cnblogs.com/diyudewudao/

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, https://www.cnblogs.com/diyudewudao/ 如有问题, 可邮件(diyudewudao@qq.com).

注:不要在意标题,在某些情况下名字都只是个代号不是。

原文地址:https://www.cnblogs.com/diyudewudao/p/11279000.html