zoukankan      html  css  js  c++  java
  • python基础知识

    输入输出

    基本的输入和输出:

    输入:input()

    输出:print() 打印

    username=input('Please input your name:')
    passwd=input('Please input your password:')
    print(username)
    print(passwd)
    View Code
    # !/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import getpass
    # 将用户输入的内容赋值给 name 变量
    pwd = getpass.getpass("请输入密码:")
    # 打印输入的内容
    print(pwd)
    不显示密码

    格式化输入输出**:

    name='egon'
    print('my name is '+name)
    '''
    my name is egon
    '''
    +号 少用
    name='egon'
    print('my name is ',name)
    '''
    my name is  egon
    '''
    逗号 ,
    name='alex'
    age='25'
    print('my name is %s ,my age is %s ' %(name,age))
    '''
    my name is alex ,my age is 25
    '''
    '''
    字符串是 % s;
    整数 % d;
    浮点数 % f
    '''
    
    #例2
    users=[
        {'username':'alex','age':18,'job':'teacher','hobble':'girl'},
        {'username':'egon','age':28,'job':'teacher','hobble':'boy'},
    ]
    
    msg='''
    ------------info of %s-------------
    Name    : %s
    Age     : %s
    Job     : %s
    Hobbile : %s
    -------------end--------------------
    ''' %(users[1]['username'],users[1]['username'],users[1]['age'],users[1]['job'],users[1]['hobble'])
    print(msg)
    
    '''
    打印结果:
    ------------info of egon-------------
    Name    : egon
    Age     : 28
    Job     : teacher
    Hobbile : boy
    -------------end--------------------
    '''
    占位符 %s 常用 记住
    ##字符串格式化 format
    ##2种方式
    ##索引的方式
    # user_info='我叫{0},今年{1}'
    # v=user_info.format('alex',23)
    # print(v)
    ##传参数
    # user_info='我叫{name},今年{age}'
    # v=user_info.format(name='alex',age=23)
    # print(v)
    ##format_map 传值是字典形式
    # user_info = '我叫{name},今年{age}'
    # v = user_info.format_map({'name':'alex','age':23})
    # print(v)
    format

    运算符

    算数运算:

    比较运算:

    赋值运算:

    逻辑运算:

    成员运算:

    身份运算:

    位运算:

     

    *按位取反运算规则(按位取反再加1)   详解http://blog.csdn.net/wenxinwukui234/article/details/42119265

    运算符优先级:

    条件和循环语句

    条件语句if

    基本格式

    '''
    单分支
    if 条件:
        满足条件后需要执行的代码
    '''
    age=int(input('you age:'))
    if age > 18:
        print('nianqing')
    
    '''
    双分支
    if 条件:
        满足条件后需要执行的代码
    else:
         条件不满后执行的代码
    '''
    age=int(input('you age:'))
    if age > 18:
        print('nianqing')
    
    '''
    多分支
    if 条件1:
        满足条件1后需要执行的代码
    elif 条件2:
        满足条件3后需要执行的代码
    elif条件3:
        满足条件3后需要执行的代码
    else:
        以上条件都不满后执行的代码
    '''
    age=int(input('you age:'))
    if age < 18:
        print('little')
    elif age > 20 and age < 30:
        print('haixing')
    elif age > 31 and age < 50:
        print('old')
    else:
        print('died')
    单分支 双分支 多分支
    #成绩范围对应的级别
    # A 90-100
    # B 80-89
    # C 60-79
    # D 40-59
    # E 0-39
    
    
    score=int(input('please your score:'))
    
    if score > 90 and  score <= 100:
        print('AA')
    elif score > 80 and score < 89:
        print('BB')
    elif score > 60 and score < 79:
        print('CC')
    elif score > 40 and score < 59:
        print('DD')
    elif score > 0 and score < 39:
        print('EE')
    练习

    循环语句while

    基本格式

    while 条件:
        执行代码。。。
    View Code
    #打印100个数
    # count=0
    # while count <= 100:
    #     print(count)
    #     count+=1
    
    #只打印1-49个数,到50的时候就终止打印
    # count=1
    # while count <= 100:
    #     if count == 50:
    #         break #跳出循环(只有一层就跳出本层,多层就都跳出)
    #     print(count)
    #     count += 1
    
    ##对比continue和break
    #continue
    # count=0
    # while count < 5:
    #     if count == 3:
    #         count+=1
    #         continue #跳出本次循环
    #     print(count)
    #     count+=1
    '''
    0
    1
    2
    4
    '''
    #break
    # count=0
    # while count < 5:
    #     if count == 3:
    #         count+=1
    #         break
    #     print(count)
    #     count+=1
    # '''
    # 0
    # 1
    # 2
    # '''
    
    #打印出0-100的偶数
    # count=1
    # while count <=100:
    #     if count % 2 == 0: #偶数  奇数:if count % 2 == 0
    #         print(count)
    #     count+=1
    
    
    
    #重复输入命令
    # while True: #无限循环
    #     cmd=input('>>:')
    #     if cmd == 'q':
    #         break
    小练习
    #2、求1-100的所有数的和
    
    i = 0
    i_sum = 0
    while i < 100:
        i += 1
        i_sum += i
    print(i_sum)
    
    
    
    #5、求1-2+3-4+5 ... 99的所有数的和
    num=0
    for i in range(100):
        if i%2 == 0:
            num=num-i
        else:
            num=num+i
    print(num)
    求和 常练习
    #用户输入用户名和密码 如果超过三次就退出
    #如果用户名和密码和正确 就循环输入命令 exit退出
    #这是一种方式
    count=1
    while count <= 3:
        username = input('username>>:') #需要循环输入
        passwd = input('password>>:')
        if username=='alex' and passwd=='123':
            print('欢迎进入')
            while True:
                cmd=input('cmd>>:')
                if cmd == 'exit':
                    break
            break
        else:
            print('用户名或密码错误,请重新登录')
            count +=1
            if count > 3:
                print('超过三次登录,强制退出')
                break
    #第二种方式
    count=1
    while True:
        if count > 3:
            print('超过三次登录,强制退出')
            break
        username = input('username>>:') #需要循环输入
        passwd = input('password>>:')
        if username=='alex' and passwd=='123':
            print('欢迎进入')
            while True:
                cmd=input('cmd>>:')
                if cmd == 'exit':
                    break
            break
        else:
            print('用户名或密码错误,请重新登录')
            count +=1
    
    #第三种方式
    count=1
    tag=True
    while tag:
        if count > 3:
            print('超过三次登录,强制退出')
            break
        username = input('username>>:') #需要循环输入
        passwd = input('password>>:')
        if username=='alex' and passwd=='123':
            print('欢迎进入')
            while tag:
                cmd=input('cmd>>:')
                if cmd == 'exit':
                    tag=False
            break
        else:
            print('用户名或密码错误,请重新登录')
            count +=1
    用户三次登录 常练习
    #猜年龄 次数限制为3
    age=50
    
    count=1
    while count <= 3: #while True: 是无限循环
        age_input = int(input('please age:'))
        if age_input == age:
            print('猜对了呢')
            break
        elif age_input < age:
            print('too small')
        elif age_input > age:
            print('too big')
        else:
            print('什么鬼')
        count+=1
    
    
    #猜年龄游戏的升级版 超过三次后提问是否还猜 如果还猜就重新开始继续有三次机会
    age=50
    count=1
    while True:
        while count <= 3:
            age_input = int(input('please age:'))
            if age_input == age:
                print('猜对了呢')
                break
            elif age_input < age:
                print('too small')
            elif age_input > age:
                print('too big')
            else:
                print('什么鬼')
            count+=1
        choice=input('还猜吗,回答y和n')
        if choice=='y':
            count=1
        else:
            break
    猜年龄游戏 常练习

     作业:

    编写登陆接口

    基础需求:

    • 让用户输入用户名密码
    • 认证成功后显示欢迎信息
    • 输错三次后退出程序

    升级需求:

    • 可以支持多个用户登录 (提示,通过列表存多个账户信息)
    • 用户3次认证失败后,退出程序,再次启动程序尝试登录时,还是锁定状态(提示:需把用户锁定的状态存到文件里)
    #!/usr/bin/python
    #!-*-coding:utf-8 -*-
    
    #db.txt 的内容 egon1|egon2|
    '''
    重点  user_locks=f.read().split('|') 可以将文件里的内容编程列表
          if name not in dic:  这样就可以判断 name变量对应的值 是否是字典的key里  看来默认是在key里找
    '''
    
    dic={
        'egon1':{'password':'123','count':0},
        'egon2':{'password':'123','count':0},
        'egon3':{'password':'123','count':4},
        'egon4':{'password':'123','count':0},
    }
    
    count=0
    while True:
        #开始针对用户名做一系列的判断
        name=input('name>>:')
        if name not in dic:
            print('用户不存在,请重新登录')
            continue
        with open('db.txt','r') as f:
            lock_user=f.read().split('|')
            if name in lock_user:
                print('%s 已经锁定!' %name)
                break
        #开始针对登录次数做判定
        if dic[name]['count'] > 3:
            print('登录次数太多,强制退出!')
            with open('db.txt','a') as f: #将超过登录次数的用户加入db.txt文件
                f.write('%s|' %name)
            break
        #开始对密码做判定
        passwd=input('password>>:')
        if passwd==dic[name]['password']:
            print('恭喜,登录成功!')
            break
        else:
            print('错误的用户名或者密码')
            dic[name]['count']+=1
    重量级作业 用户三次登录锁定

    循环语句for

    最简单的循环10次

    #_*_coding:utf-8_*_
    __author__ = 'Alex Li'
    for i in range(10):
        print("loop:", i )
    #输出
    loop: 0
    loop: 1
    loop: 2
    loop: 3
    loop: 4
    loop: 5
    loop: 6
    loop: 7
    loop: 8
    loop: 9
    View Code

    需求一:还是上面的程序,但是遇到小于5的循环次数就不走了,直接跳入下一次循环

    for i in range(10):
        if i<5:
            continue #不往下走了,直接进入下一次loop
        print("loop:", i )
    View Code

    需求二:还是上面的程序,但是遇到大于5的循环次数就不走了,直接退出

    for i in range(10):
        if i>5:
            break #不往下走了,直接跳出整个loop
        print("loop:", i )

    数据类型

     学会数据类型的转换

    age=input('your age:')
    age=int(age)
    print(type(age))
    '''
    your age:18
    <class 'int'>
    '''
    #或者
    age=int(input('your age:'))
    数据类型转换

    字符串 str

    叨逼叨:字符串的各个功能修改不是本身,本身不变,会产生新的值,需要赋值给新的变量来接收

    详细点击我

    常用用法如下

    name = 'alex 	
    '
    v = name.strip()
    print(v)
    print(name.strip()) # 左右
    print(name.rstrip()) #
    print(name.lstrip()) #
    移除空白 strip
    name = 'alexbclexbfelx'
    v = name.split('b') # 以b分
    v0 = name.split('b',1) #
    v1 = name.partition('b')
    print(v)
    print(v0)
    print(v1)
    分割 split 列表 常用来处理文件内容
    name = 'alex'
    v1 = '|'.join(name)
    print(v1)
    '''
    a|l|e|x
    '''
    元素拼接 join
    #2种方式
    #索引的方式
    user_info='我叫{0},今年{1}'
    v=user_info.format('alex',23)
    print(v)
    #传参数
    user_info='我叫{name},今年{age}'
    v=user_info.format(name='alex',age=23)
    print(v)
    #format_map 传值是字典形式
    user_info = '我叫{name},今年{age}'
    v = user_info.format_map({'name':'alex','age':23})
    print(v)
    字符串格式化 format
    #参数1:子序列
    #参数2:区间
    name = 'alex'
    v = name.find('a')
    v1 = name.find('a',1,3) #find 没有找到的话,显示-1不报错
    v2 = name.index('a',1,3) #index 没有找到的话,报错
    print(v)
    print(v1)
    print(v2)
    根据子序列,打印索引位置 find index
    name = 'alex'
    v = name.endswith('x') #判断是否以 x 结尾
    v1 = name.startswith('a') #判断是否以 a 开头
    print(v)
    print(v1)
    判断开始或结束的子序列 startswith endswith
    # 参数1:旧的内容
    # 参数2:新的内容
    # 参数3:替换几个,默认都替换
    name = 'alexericsevenalex'
    v = name.replace('alex','ALEX')
    v1 = name.replace('alex','ALEX',1)
    print(v1)
    print(v)
    '''
    ALEXericsevenalex
    ALEXericsevenALEX
    '''
    替换 replace
    name='AleX'
    v=name.lower() #大写边小写
    v1=name.upper() #小写变大写
    print(v)
    print(v1)
    '''
    alex
    ALEX
    '''
    大小写转换 lower upper

     列表 list

    叨逼叨:列表是可变的,针对列表的改变,变得是列表本身,和字符串区别开来

    详细点我

    常用用法

    # name = ['alex','eric','seven','qiqi']
    # v = name.append('yangyang')
    # print(name)
    # print(v)
    # #执行结果
    # ['alex', 'eric', 'seven', 'qiqi', 'yangyang']
    # None
    追加 append
    #参数1:插入的索引位置
    #参数2:插入的值
    # name = ['alex','eric','seven','qiqi','alex']
    # name.insert(0,'插入')
    # print(name)
    插入 insert
    #参数1:子序列 必选
    #参数2: 区间
    # name = ['alex','eric','seven','qiqi','alex']
    # v = name.index('alex')
    # v1 = name.index('alex',3,5)
    # print(v1)
    # print(v)
    根据子序列判断索引位置 index
    #name = ['alex','eric','seven','qiqi','alex']
    # name.reverse()
    # print(name)
    翻转 reverse
    # num = [11,22,33,44,55,66,23,45,65]
    # num.sort()
    # print(num)
    #反转后 就是从大到小
    # num = [11,22,33,44,55,66,23,45,65]
    # num.sort(reverse=True)
    # print(num)
    排序 默认从小到大
    li = ['alex', 'eric', 'seven', 'qiqi', 'qiqi']
    print(li.index('seven')) #2
    v=li[0]
    print(v)
    a=li[0:2]
    print(a)
    '''
    2
    alex
    ['alex', 'eric']
    '''
    切片

    字典 dict

    叨逼叨:
    #字典 可变类型 意思就是修改的是自己本身
    #可变类型,当修改后,内存里的值也会对应着修改
    #不可变类型,当修改后,会在内存里开启一块新的空间,放新的值
    详细点我
    常用用法
    # name = {
    #     'name':'alex',
    #     'age':23,
    #     'gender':'女'
    # }
    # v = name.get('name') #这个方式以后会常用 没有取值不报错
    # v1 = name['name'] #没有取到  会报错
    # print(v)
    # print(v1)
    根据key 取value的值 get
    
    
    name = {
        'name':'alex',
        'age':23,
        'gender':''
    }
    v = name.items() #键值对
    v1= name.keys() #key
    v2=name.values() #value
    print(v)
    print(v1)
    print(v2)
    '''
    打印结果
    dict_items([('name', 'alex'), ('age', 23), ('gender', '女')])
    dict_keys(['name', 'age', 'gender'])
    dict_values(['alex', 23, '女'])
    '''
    #取出 key和value
    for k,v in name.items():
        print(k,v)
    '''
    name alex
    age 23
    gender 女
    '''
    #单独取出key
    for k in name.keys():
        print(k)
    '''
    name
    age
    gender
    '''
    #单独取出value
    for v in name.values():
        print(v)
    '''
    alex
    23
    女
    '''
    取出 items keys values
    #pop 删除并将删除的值保留
    name = {
        'name':'alex',
        'age':23,
        'gender':''
    }
    v=name.pop('name')
    print(v)
    print(name)
    '''
    alex
    {'age': 23, 'gender': '女'}
    '''
    #del 直接删除值
    del name['age']
    print(name)
    '''
    {'name': 'alex', 'gender': '女'}
    '''
    删除内容 pop del
    #增加修改 setdefault upadte
    
    #setdefault 增加 如果存在  不做操作
    name = {
        'name':'alex',
        'age':23,
        'gender':''
    }
    name.setdefault('name','alex')
    name.setdefault('love','none')
    print(name)
    '''
    {'name': 'alex', 'age': 23, 'gender': '女', 'love': 'none'}
    '''
    
    #update 批量增加或修改
    name.update({'qiiq':'gegege','djfkd':'okok'})
    print(name)
    '''
    {'name': 'alex', 'age': 23, 'gender': '女', 'qiiq': 'gegege', 'djfkd': 'okok'}
    '''
    v={
        'sex':'boy',
        'aihao':'qima'
    }
    name.update(v)
    print(name)
    '''
    {'name': 'alex', 'age': 23, 'gender': '女', 'sex': 'boy', 'aihao': 'qima'}
    '''
    增加修改 setdefault update

    元组 tuple

    叨逼叨:不可变类型 相当于只读的列表,不可被修改,不可被修改哦

    创建元组最后加,最后加, 形成良好的习惯

    详细点我

    常用方法

    tup = ('alex', 'eric', 'seven', 'qiqi', 'qiqi',)
    print(tup.index('seven')) #2
    v=tup[0]
    print(v)
    a=tup[0:2]
    print(a)
    '''
    2
    alex
    ('alex', 'eric')
    '''
    index 切片

    集合 set

    叨逼叨:
    #集合 不可重复的列表 可变类型
    详细点我

    整数 int

    '9'.isdigit() 是否整数

    浮点型 float

    布尔 bool

    0 false 其他是true
    空 false 其他是true

    文件操作

    来点我吧查看详细内容

     

  • 相关阅读:
    Linux下的sleep()和sched_yield()(转)
    各种字符串Hash函数(转)
    linux 实时监控网速脚本(转)
    linux安装chrome及chromedriver(转)
    Couldn't open file /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 解决办法(转)
    linux 运行时限制CPU核数、内存、读写速度
    C语言函数sscanf()的用法-从字符串中读取与指定格式相符的数据(转)
    golang在线学习与编译网站
    电子书转换网站推荐
    入门级网站经典 w3cschool
  • 原文地址:https://www.cnblogs.com/lazyball/p/7279815.html
Copyright © 2011-2022 走看看