变量的类型转换—if-while循环语句

  1. 类型转换

    eval的使用

    res='print('hello')'
    
    #eval可以把字符串里的语句执行
    
    eval(res)
  2. float和round保留小数的区别
n=3.1415
#float保留两位小数
f=float('%.2f'%n)
#round保留两位小数,四舍五入法
f_f=round(2,n)

运算符

  1. 字符串的赋值方法

    a,b,c,d='spam'
    
    #等价于
    
    a,b,c,d='s','p','a','m'
  2. 匹配赋值,*表示属于的数据

    a,*b='spam'
    print(a)#输出's'
    print(b)#输出'pam'
  3. 算术运算符

    m=-12.5
    print(int(m))#取整数,输出-12
    print(round(m))#四舍五入取整。输出-13
    print(m//1)#向下取整,输出-13
  4. 关系运算符

    字符串的比较方法:比较首字符数字的大小或者首字母的先后顺序

    
    #下面三种方法结果相等
    
    print(0<age<120)
    print(age>0 and age<120)
    print(age<0 or age>120)
  5. 取字符串里的首字符或末字符的方法

    str='hello'
    opt,*opts=str    #opt='h'首字符
    *opts,opt=str    #opt='o'末字符
  6. or的使用方法

    n=java
    m=n or 'python'
    
    #等价于
    
    if n:
        m='java'
    else:
        m='python'

    字符串输出方法

n='13'
print('你的年龄是%s岁'%n)
print('你的年龄是'+n+'岁')
  • in用来判断字符串是否有这个子串
    例:判断邮箱是否合法
email='[email protected]'
if '@'in email and '.' in email:
    print('is email')
else:
    print('not email')

isdigit判断字符串是否只含有数字

  • if循环语句

    ```
     if 条件:
         #条件满足时执行的代码
     else:
         #条件不满足时的代码
     ```
    
  • 三元运算符
a=True if a>0 else False
  • while循环的使用
#1.循环变量初始化
i=0
#2.循环条件
while i<10000:
#3.循环体
    print('i am sorry')
#4.改变循环变量的值
    i+=1
else:
    # 寿终正寝:正常结束时执行
    print(i)
  • 嵌套循环语句,其本质是:外部循环执行一次,内部循环执行一轮
    例:输出1到100之间所有的素数
i=2
while i<100:
    j=2
    while j<=i//2:
        if i%j==0:
            break #不是素数,跳出循环
        else:
            j+=1 #接着判断
    else:
        print(i)  #输出正常跳出的i值
    i+=1

猜你喜欢

转载自blog.csdn.net/qq_42650983/article/details/81088181