python基础,一些代码

 参考:https://zhuanlan.zhihu.com/c_1216656665569013760

----------------------------------------------------------
for num in range(100,1000): # 水仙花数
    low = num%10
    mid = num // 10 % 10
    high = num //100
    if ( num == (low ** 3 + mid ** 3 + high ** 3)):
        print(num)


正整数的反转
num = int (input ('num='))
reversed_num = 0
while (num > 0):
    reversed_num = reversed_num*10 + num%10
    num//=
print (reversed_num)



from random import randint

money = 100
while (money > 0):
    print(f'你的总资产为:{money}元')
    go_on = False
    # 下注金额限定
    while True:
        debt = int(input('请下注'))
        if 0 < debt <=money:
            break
    first = randint(1,6) + randint(1,6)
    print(f'\n玩家摇出了{first}点')
    if first ==7 or first == 11:
        print('玩家胜!\n')
        money+=debt
    elif first == 2 or first == 3 or first ==12:
        print('庄家胜!\n')
        money-=debt
    else:
        go_on=True


import random # 一个生成指定长度验证码的函数
ALL_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
def gengerate_code(code_len=4):
    code = ''
    for _ in range(code_len):
        index = random.randrange(0,len(ALL_CHARS))
        code += ALL_CHARS[index]
    return code
for _ in range(0,10):
    print(gengerate_code(10))


返回给定文件的文件后缀名
def get_suffix(filename):
    pos = filename.rfind('.') # 逆向查找
    return filename[pos+1:] if pos > 0 else ''
print(get_suffix('abc.txt'))
print(get_suffix('asas.pdf'))
print(get_suffix('.readme'))
print(get_suffix('readme.'))


from os.path import splitext
 ???

def get_suffix(filename):
    return splitext(filename)[1][1:]



回马灯
import os
import time

content = '北 京 欢 迎 你 为 你 开 天 辟 地           '
i = int(0)
while True:
    # Windows清除屏幕上的输出
    # os.system('cls')
    # macOS清除屏幕上的输出
    os.system('clr')
    print(content)
    # 休眠0.2秒(200毫秒)
    time.sleep(0.2)
    content = content[1:] + content[0]
    i +=1
    if (i==50):
        break


from random import randint
a1 = 0  # 笨重的筛子计数
a2 = 0
a3 = 0
a4 = 0
a5 = 0
a6 = 0
for i in range(1,6001):
    a = randint(1,7)

    if (a==1):
        a1 += 1
    elif (a==2):
        a2 +=1
    elif (a==3):
        a3 += 1
    elif (a==4):
        a4 +=1
    elif (a==5):
        a5 +=1
    else:
        a6 +=1
print('a1=%06d'%a1)
print('a2=%06d'%a2)
print('a3=%06d'%a3)
print('a4=%06d'%a4)



list_1 = [1,2,3,1,2,2,3,3442,313,131313,44,23245]
print(list_1)
list_2 = list(range(1,10))
print(list_2)
list_3 = list('shit!!')
print(list_3)

list_a = ['apple','tree','list']
for index in range(len(list_a)):
    print(list_a[index])



import random  # 筛子
c = [0]*6
for _ in range(6000):
    a = random.randint(1,6)
    c[a-1] += 1
for i in range(0,6):
    print(c[i])






笔记:
1 .   r'xxx'  f'xxx'
https://www.cnblogs.com/poloyy/p/12444579.html
https://www.runoob.com/python/att-string-format.html
例子:1-1 print(r' xx{1}xx{2}------{0} '.format("hhh","222222222","3ccc3"))
     1-2 print ('myqq={myqq},myVX={myvx}'.format(myqq="23121235",myvx="FACKYOU"))
     1-3 通过字典设置参数
         site = {"name":"比起古","qq":"110"} # dict == 字典
         print("姓名:{name},qq:{qq}".format(**site))
     1-4 this_list = ['高手教程','不言而喻','一目了然']
         print('{0[1]}.....{0[0]}......{0[2]}'.format(this_list))
2 随机数
from random import randint
a =  randint(1,6) + randint(1,6)

3 常用的内置函数:
a = abs(-12.23) # 返回绝对值
print(a)
a = bin(123) # 转换为以0b开头的二进制字符串
print(a)
chr--orf  hex  oct
a = pow(2,3) # 求幂运算
a = round(1.23546798,3) # 按指定精度进行四舍五入
a = sum(range(1,101)) # 对一个序列从头到尾进行求和

4 字符串
4-1 : print函数中的end=''表示输出后不换行,即将默认的结束符\n(换行符)更换为''(空字符)。
      例子 :print('123',end='')
            print('456')
            #--> 123456
4-2:
    a = '''
        你是一只狗
    `   ,你是一只猪,
        你 喜欢睡觉
    '''
    print(a)
4-3 : a = '1213'
      b = a[:]
      print(b)
4-4 : a = 'abcdefg'   # 负向索引
      print(a[0],a[-2])

      a = '123456789'
      b = a[:]
       c = a[::-1]
      print(c)
4-5 :1  循环  1  s = 'fuck you !!!'
              for index in range(len(s)):
              print(s[index],end='')
             2 s = 'fuck you !!!'
               for ch in s:
               print(ch)
     2 字符串的方法
     2-1
      s1 = 'hello world'
      print(s.capitalize()) # 使首字母大写
      print(s.title()) # 使得每个单词首字母大写
      print(s.upper()) # 使得全部大写
      s2 = 'abcdeee'
      print(s2.lower()) # 使得全部变小写
     2-2  查找
          s = 'i will kill you'  # s.find('xxx',5) 从5开始查找
          print(s.find('kill'))  # s.rfind()    s.rindex() 倒着查找
          print(s[7])
          print(s.index('kill'))
          print(s.find('zzzz'))
          print(s.find('l'))
          print(s.index('zz'))
     2-3..开头/结尾 ,由..组成
          s = 'i love china'
            print(s.startswith('ss'))
            print(s.startswith('i'))
            print(s.endswith('xxx'))
            print(s.endswith('a'))
            s1 = 'abc88888'
            print(s1.isdigit()) # 是否由数字组成
            print(s1.isalpha()) # 字母
            print(s1.isalnum()) # 数字和字母
     2-4 对齐
            s1 = 'i have an apple'     # **i have an apple***
            print(s1.center(20,'*'))
            print(s1.rjust(20))
            print(s1.ljust(20),'~~')
     2-5 保留小数
            a = 3.15656
            print('%12.2f'%a)
            +.2f 带符号保留二位
            .0f 不带小数
            b = 456
            b = str(b)
            print(b.rjust(6,'0')) # https://blog.csdn.net/qq_39609993/article/details/107006122?fps=1&locationNum=2
            b = int(b)
            print('%06d'%b)

     2-6 修剪操作
            e_m = '   [email protected]   \n\t'
            print(e_m.strip())
            print(e_m.lstrip())
            print(e_m.rstrip())
5 列表
       5-1 插入,添加,删除
            item = ['we','are','the']
            item.append('children') # 添加
            item.insert(1,'two') # 插入
            item.remove('the')
            item.pop()
            del item[1]
            print(item)
      5-2 : 查找出现次数
            item = ['techno','edm','trance','trance']
            print(item.index('trance'))
            print(item.index('edm',1))
            print(item.count('techno'))
      5-3 : 排序,反转
            items = ['who','are','you','bay']
            items.sort()
            print(items)
            items.reverse()
            print(items)
      5-4 : 列表生成
            items = [x for x in range(1,10)]
            items_2 = [x for x in 'i dont know english' if x not in 'abc']
            print(items)
            print(items_2)
      5-5 : 嵌套列表
            嵌套的正确做法-->
            scores = [[0]*3 for _ in range(5)]
            scores[0][0] = 95
            print(scores) # -->[[95, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
 6 元祖
            tuple_1 = (1,2,3,4,2,2)
            print(type(tuple_1))
            tuple_2 = ('yuanzu',2,'really?','4')
            print(type(tuple_2))
            print(tuple_2)
            tuple_2 +=tuple_1
            print('-------',tuple_2)
            print(tuple_1[2:])
        用途 : 打包,解包
            a = 1,10,100
            print(a,type(a))
            z,x,c=a
            print(z+x+c)
            print(type(z))
            b = z,x,c
            print(type(b))
        其他 ;
            a = (1,10,12,14,13,12412,123123)
            z,x,*c = a # 星号表达式
            print(c)

            a = 3
            b = 2
            a,b = b,a # 交换运算
            print(a,b)
        让函数返回多个值
            def find_max_min(items):
                max_ = items[0]
                min_ = items[0]
                for item in items:

                    if max_ < item :
                        max_ = item
                    if min_ > item :
                        min_ = item
                return max_,min_
            items = [22,43,13,12,23,13,32424,13,13,13,24]
            a = find_max_min(items)
            print(a)
复习  :  scores = [[0]*3 for _ in range(5)]
names = ['关羽','张飞','赵云','马超','黄忠']
course = ['语文','数学','英语']
scores = [[0]*len(course) for _ in range(len(names))]
for i,name in enumerate(names):
    print(f'请输入{name}的成绩')
    for j,course in enumerate(course):
        scores[i][j] = float(input(f'{course}:'))
     7  集合 (无序性,互异性)
                set1 = {1,2,3,2,3}
                print(set1)
                set2 = set('hello')
                print(set2)
                for i in set1:
                    print(i) # 集合元素遍历
                print(5 in set1) # False
         7-1 交集,并集,差集
                set1 = {1,2,3,4,5,6,7}
                set2 = {1,2,3}
                # 交集
                print(set1 & set2)
                print(set1.intersection(set2))
                # 并集
                print(set1 | set2 )
                print(set1.union(set2))
                # 差集
                print(set1 - set2)
                print(set1.difference(set2))
                # 对称差 : 两集合的并集减去交集
                print(set1 ^ set2)

                set1 = {1, 3, 5}
                set2 = {1, 2, 3, 4, 5}
                set3 = set2
                # <运算符表示真子集,<=运算符表示子集
                print(set1 < set2, set1 <= set2)    # True True
                print(set2 < set3, set2 <= set3)    # False True
                # 通过issubset方法也能进行子集判断
                print(set1.issubset(set2))      # True

                # 反过来可以用issuperset或>运算符进行超集判断
                print(set2.issuperset(set1))    # True
                print(set2 > set1)              # True
 8 字典
                txt = {'name':'van','age':65,'dgree':111}
                txt1 = dict(name = 'van',age = '65')
                txt2 = dict(zip('abcd','1234'))
                txt3 = dict(zip('abcd',range(1,10)))
                # print(txt)
                # print(txt1)
                # print(txt2)
                # print(txt3)
                for i in txt:
                    print(i)
                    print(txt[i])
                    print(f'{i}:{txt[i]}')
                print(len(txt))
     8-1  嵌套的字典
students = {
    6001:{ 'name':'大撒币','age':996,'work':'搬砖' },
    6002:{'name':'二狗子','age':123,'work':'睡觉'},
    6003:{'name':'猴子','age':22,'work':'爬'}
}
print(students.get(6001))
# 获得字典中所有键
print(students.keys())
# 获得字典所有值
print(students.values())
# 获得字典中所有键值对
print(students.items())
对其进行遍历
for key,value in students.items():
    print(key,'--->',value)

使用pop方法删除对应键值对并返回该值
stu2 = students.pop(6002)
使用popitem方法删除字典中最后一组键值对并返回对应的二元组
如果字典中没有元素,调用该方法将引发KeyError异常
key,value = students.popitem

使用setdefault更新
result = students.setdefault(6004,{'name':'fuck'})
print(result)
print(students.get(6004))

updata 更新
others = {
    1002:{'name':'none','age':0},
    6001:{'name':'get out'}
}
students.update(others)
print(students)

你可能感兴趣的:(笔记,python)