Python 入门的60个基础练习

慈云数据 2024-04-23 技术支持 149 0

文章目录

  • 01-Hello World
  • 02-print 函数
  • 03-基本运算
  • 04-input
  • 05-输入输出基础练习
  • 06-字符串使用基础
  • 07-列表基础
  • 08-元组基础
  • 09-字典基础
  • 10-基本判断
  • 11-条件表达式、三元运算符
  • 12-判断练习:用户名和密码是否正确
  • 13-猜数:基础实现
  • 14-成绩分类 1
  • 15-成绩分类 2
  • 16-石头剪刀布
  • 17-改进的石头剪刀布
  • 18-猜数,直到猜对
  • 19-猜数,5 次机会
  • 20-while 循环,累加至 100
  • 21-while-break
  • 22-while-continue
  • 23-for 循环遍历数据对象
  • 24-range 用法及数字累加
  • 25-列表实现斐波那契数列
  • 26-九九乘法表
  • 27-逐步实现列表解析
  • 28-三局两胜的石头剪刀布
  • 29-文件对象基础操作
  • 30-拷贝文件
  • 31-拷贝文件
  • 32-位置参数
  • 33-函数应用-斐波那契数列
  • 34-函数-拷贝文件
  • 35-函数-九九乘法表
  • 36-模块基础
  • 37-生成密码/验证码
  • 38-序列对象方法
  • 39-序列对象方法 2
  • 40-字符串方法
  • 41-字符串格式化
  • 42-shutil 模块常用方法
  • 43-练习:生成文本文件
  • 44-列表方法
  • 45-检查合法标识符
  • 46-创建用户,设置随机密码
  • 47-列表练习:模拟栈操作
  • 48-实现 Linux 系统中 unix2dos 功能
  • 49-动画程序:@从一行#中穿过
  • 50-字典基础用法
  • 51-字典常用方法
  • 52-集合常用方法
  • 53-集合实例:取出第二个文件有,第一个文件没有的行
  • 54-字典练习:模拟注册/登陆
  • 55-计算千万次加法运算时间
  • 56-时间相关模块常用方法
  • 57-os 模块常用方法
  • 58-pickle 存储器
  • 59-异常处理基础
  • 60-异常处理完整语法

    01-Hello World

    python 的语法逻辑完全靠缩进,建议缩进 4 个空格。 如果是顶级代码,那么必须顶格书写,哪怕只有一个空格也会有语法错误。 下面示例中,满足 if 条件要输出两行内容,这两行内容必须都缩进,而且具有相同的缩进级别。

    print('hello world!')
    if 3 > 0:
        print('OK')
        print('yes')
    x = 3; y = 4   # 不推荐,还是应该写成两行
    print(x + y)
    

    02-print 函数

    print('hello world!')
    print('hello', 'world!')  # 逗号自动添加默认的分隔符:空格 hello world!
    print('hello' + 'world!')  # 加号表示字符拼接 helloworld!
    print('hello', 'world', sep='***')  # 单词间用***分隔 hello***world
    print('#' * 50)  # *号表示重复 50 遍
    print('how are you?', end='')  # 默认 print 会打印回车,end=''表示不要回车
    

    03-基本运算

    • 运算符可以分为:算术运算符、比较运算符和逻辑运算符。优先级是:算术运算符>比较运算符>逻辑运算符。最好使用括号,增加了代码的可读性
      print(5 / 2)  # 2.5
      print(5 // 2)  # 丢弃余数,只保留商
      print(5 % 2)  # 求余数
      print(5 ** 3)  # 5 的 3 次方
      print(5 > 3)  # 返回 True
      print(3 > 5)  # 返回 False
      print(20 > 10 > 5)  # python 支持连续比较
      print(20 > 10 and 10 > 5)  # 与上面相同含义
      print(not 20 > 10)  # False
      

      04-input

      number = input("请输入数字:")  # input 用于获取键盘输入
      print(number)
      print(type(number))  # input 获得的数据是字符型
      print(number + 10)  # 报错,不能把字符和数字做运算
      print(int(number) + 10)  # int 可将字符串 10 转换成数字 10
      print(number + str(10))  # str 将 10 转换为字符串后实现字符串拼接
      

      05-输入输出基础练习

      username = input('username: ')
      print('welcome', username)   # print 各项间默认以空格作为分隔符
      print('welcome ' + username)  # 注意引号内最后的空格
      

      06-字符串使用基础

      python 中,单双引号没有区别,表示一样的含义

      sentence = 'tom\'s pet is a cat'  # 单引号中间还有单引号,可以转义
      sentence2 = "tom's pet is a cat"  # 也可以用双引号包含单引号
      sentence3 = "tom said:\"hello world!\""
      sentence4 = 'tom said:"hello world"'
      # 三个连续的单引号或双引号,可以保存输入格式,允许输入多行字符串
      words = """
      hello
      world
      abcd"""
      print(words)
      py_str = 'python'
      len(py_str)  # 取长度
      py_str[0]  # 第一个字符
      'python'[0]
      py_str[-1]  # 最后一个字符
      # py_str[6]  # 错误,下标超出范围
      py_str[2:4]  # 切片,起始下标包含,结束下标不包含
      py_str[2:]  # 从下标为 2 的字符取到结尾
      py_str[:2]  # 从开头取到下标是 2 之前的字符
      py_str[:]  # 取全部
      py_str[::2]  # 步长值为 2,默认是 1
      py_str[1::2]  # 取出 yhn
      py_str[::-1]  # 步长为负,表示自右向左取
      py_str + ' is good'  # 简单的拼接到一起
      py_str * 3  # 把字符串重复 3 遍
      't' in py_str  # True
      'th' in py_str  # True
      'to' in py_str  # False
      'to' not in py_str  # True
      

      07-列表基础

      列表也是序列对象,但它是容器类型,列表中可以包含各种数据

      alist = [10, 20, 30, 'bob', 'alice', [1,2,3]]
      len(alist)
      alist[-1]  # 取出最后一项
      alist[-1][-1]  # 因为最后一项是列表,列表还可以继续取下标
      [1,2,3][-1]  # [1,2,3] 是列表,[-1] 表示列表最后一项
      alist[-2][2]  # 列表倒数第 2 项是字符串,再取出字符下标为 2 的字符
      alist[3:5]   # ['bob', 'alice']
      10 in alist  # True
      'o' in alist  # False
      100 not in alist # True
      alist[-1] = 100  # 修改最后一项的值
      alist.append(200)  # 向**列表中追加一项
      

      08-元组基础

      元组与列表基本上是一样的,只是元组不可变,列表可变。

      atuple = (10, 20, 30, 'bob', 'alice', [1,2,3])
      len(atuple)
      10 in atuple
      atuple[2]
      atuple[3:5]
      # atuple[-1] = 100  # 错误,元组是不可变的
      

      09-字典基础

       # 字典是 key-value(键-值)对形式的,没有顺序,通过键取出值
       adict = {'name': 'bob', 'age': 23}
       len(adict)
       'bob' in adict  # False
       'name' in adict  # True
       adict['email'] = 'bob@tedu.cn'  # 字典中没有 key,则添加新项目
       adict['age'] = 25  # 字典中已有 key,修改对应的 value
      

      10-基本判断

      单个的数据也可作为判断条件。 任何值为 0 的数字、空对象都是 False,任何非 0 数字、非空对象都是 True。

      if 3 > 0:
          print('yes')
          print('ok')
      if 10 in [10, 20, 30]:
          print('ok')
      if -0.0:
          print('yes')  # 任何值为 0 的数字都是 False
      if [1, 2]:
          print('yes')  # 非空对象都是 True
      if ' ':
          print('yes')  # 空格字符也是字符,条件为 True
      

      11-条件表达式、三元运算符

      a = 10
      b = 20
      if a  
      

      12-判断练习:用户名和密码是否正确

      import getpass  # 导入模块
      username = input('username: ')
      # getpass 模块中,有一个方法也叫 getpass
      password = getpass.getpass('password: ')
      if username == 'bob' and password == '123456':
          print('Login successful')
      else:
          print('Login incorrect')
      

      13-猜数:基础实现

      import random
      num = random.randint(1, 10) # 随机生成 1-10 之间的数字
      answer = int(input('guess a number: '))  # 将用户输入的字符转成整数
      if answer > num:
          print('猜大了')
      elif answer  
      

      14-成绩分类 1

      score = int(input('分数:'))
      if score >= 90:
          print('优秀')
      elif score >= 80:
          print('好')
      elif score >= 70:
          print('良')
      elif score >= 60:
          print('及格')
      else:
          print('你要努力了')
      

      15-成绩分类 2

      score = int(input('分数:'))
      if score >= 60 and score  
      

      19-猜数,5 次机会

      import random
      num = random.randint(1, 10)
      counter = 0
      while counter  num:
              print('猜大了')
          elif answer  
      

      20-while 循环,累加至 100

      因为循环次数是已知的,实际使用时,建议用 for 循环

      sum100 = 0
      counter = 1
      while counter  
      

      21-while-break

      break 是结束循环,break 之后、循环体内代码不再执行。

      while True:
          yn = input('Continue(y/n): ')
          if yn in ['n', 'N']:
              break
          print('running...')
      

      22-while-continue

      计算 100 以内偶数之和。

      continue 是跳过本次循环剩余部分,回到循环条件处。

      sum100 = 0
      counter = 0
      while counter  
      

      23-for 循环遍历数据对象

      astr = 'hello'
      alist = [10, 20, 30]
      atuple = ('bob', 'tom', 'alice')
      adict = {'name': 'john', 'age': 23}
      for ch in astr:
          print(ch)
      for i in alist:
          print(i)
      for name in atuple:
          print(name)
      for key in adict:
          print('%s: %s' % (key, adict[key]))
      

      24-range 用法及数字累加

      # range(10)  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
      # >>> list(range(10))
      # range(6, 11)  # [6, 7, 8, 9, 10]
      # range(1, 10, 2)  # [1, 3, 5, 7, 9]
      # range(10, 0, -1)  # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
      sum100 = 0
      for i in range(1, 101):
          sum100 += i
      print(sum100)
      

      25-列表实现斐波那契数列

      列表中先给定两个数字,后面的数字总是前两个数字之和。

      fib = [0, 1]
      for i in range(8):
          fib.append(fib[-1] + fib[-2])
      print(fib)
      

      26-九九乘法表

      for i in range(1, 10):
          for j in range(1, i + 1):
              print('%s*%s=%s' % (j, i, i * j), end=' ')
          print()
      # i=1 ->j: [1]
      # i=2 ->j: [1,2]
      # i=3 ->j: [1,2,3]
      # 由用户指定相乘到多少
      n = int(input('number: '))
      for i in range(1, n + 1):
          for j in range(1, i + 1):
              print('%s*%s=%s' % (j, i, i * j), end=' ')
          print()
      

      27-逐步实现列表解析

      # 10+5 的结果放到列表中
      [10 + 5]
      # 10+5 这个表达式计算 10 次
      [10 + 5 for i in range(10)]
      # 10+i 的 i 来自于循环
      [10 + i for i in range(10)]
      [10 + i for i in range(1, 11)]
      # 通过 if 过滤,满足 if 条件的才参与 10+i 的运算
      [10 + i for i in range(1, 11) if i % 2 == 1]
      [10 + i for i in range(1, 11) if i % 2]
      # 生成 IP 地址列表
      ['192.168.1.%s' % i for i in range(1, 255)]
      

      28-三局两胜的石头剪刀布

      import random
      all_choices = ['石头', '剪刀', '布']
      win_list = [['石头', '剪刀'], ['剪刀', '布'], ['布', '石头']]
      prompt = """(0) 石头
      (1) 剪刀
      (2) 布
      请选择 (0/1/2): """
      cwin = 0
      pwin = 0
      while cwin  
      

      29-文件对象基础操作

      # 文件操作的三个步骤:打开、读写、关闭
      # cp /etc/passwd /tmp
      f = open('/tmp/passwd')  # 默认以 r 的方式打开纯文本文件
      data = f.read()  # read() 把所有内容读取出来
      print(data)
      data = f.read()  # 随着读写的进行,文件指针向后移动。
      # 因为第一个 f.read() 已经把文件指针移动到结尾了,所以再读就没有数据了
      # 所以 data 是空字符串
      f.close()
      f = open('/tmp/passwd')
      data = f.read(4)  # 读 4 字节
      f.readline()  # 读到换行符、n 结束
      f.readlines()  # 把每一行数据读出来放到列表中
      f.close()
      ################################
      f = open('/tmp/passwd')
      for line in f:
          print(line, end='')
      f.close()
      ##############################
      f = open('图片地址', 'rb')  # 打开非文本文件要加参数 b
      f.read(4096)
      f.close()
      ##################################
      f = open('/tmp/myfile', 'w')  # 'w'打开文件,如果文件不存在则创建
      f.write('hello world!\n')
      f.flush()  # 立即将缓存中的数据同步到磁盘
      f.writelines(['2nd line.\n', 'new line.\n'])
      f.close()  # 关闭文件的时候,数据保存到磁盘
      ##############################
      with open('/tmp/passwd') as f:
          print(f.readline())
      #########################
      f = open('/tmp/passwd')
      f.tell()  # 查看文件指针的位置
      f.readline()
      f.tell()
      f.seek(0, 0)  # 第一个数字是偏移量,第 2 位是数字是相对位置。
                    # 相对位置 0 表示开头,1 表示当前,2 表示结尾
      f.tell()
      f.close()
      

      30-拷贝文件

      拷贝文件就是以 r 的方式打开源文件,以 w 的方式打开目标文件,将源文件数据读出后,写到目标文件。

      以下是【不推荐】的方式,但是可以工作:

      f1 = open('/bin/ls', 'rb')
      f2 = open('/root/ls', 'wb')
      data = f1.read()
      f2.write(data)
      f1.close()
      f2.close()
      

      31-拷贝文件

      每次读取 4K,读完为止:

      src_fname = '/bin/ls'
      dst_fname = '/root/ls'
      src_fobj = open(src_fname, 'rb')
      dst_fobj = open(dst_fname, 'wb')
      while True:
          data = src_fobj.read(4096)  # 每次读取 4K
          if not data:
              break
          dst_fobj.write(data)
      src_fobj.close()
      dst_fobj.close()
      

      32-位置参数

      注意:位置参数中的数字是字符形式的

      import sys
      print(sys.argv)  # sys.argv 是 sys 模块里的 argv 列表
      # python3 position_args.py
      # python3 position_args.py 10
      # python3 position_args.py 10 bob
      

      33-函数应用-斐波那契数列

      def gen_fib(l):
          fib = [0, 1]
          for i in range(l - len(fib)):
              fib.append(fib[-1] + fib[-2])
          return fib  # 返回列表,不返回变量 fib
      a = gen_fib(10)
      print(a)
      print('-' * 50)
      n = int(input("length: "))
      print(gen_fib(n))  # 不会把变量 n 传入,是把 n 代表的值赋值给形参
      

      34-函数-拷贝文件

      import sys
      def copy(src_fname, dst_fname):
          src_fobj = open(src_fname, 'rb')
          dst_fobj = open(dst_fname, 'wb')
          while True:
              data = src_fobj.read(4096)
              if not data:
                  break
              dst_fobj.write(data)
          src_fobj.close()
          dst_fobj.close()
      copy(sys.argv[1], sys.argv[2])
      # 执行方式
      # cp_func.py /etc/hosts /tmp/zhuji.txt
      

      35-函数-九九乘法表

      def mtable(n):
          for i in range(1, n + 1):
              for j in range(1, i + 1):
                  print('%s*%s=%s' % (j, i, i * j), end=' ')
              print()
      mtable(6)
      mtable(9)
      

      36-模块基础

      每一个以 py 作为扩展名的文件都是一个模块。

      • star.py:
        hi = 'hello world!'
        def pstar(n=50):
            print('*' * n)
        if __name__ == '__main__':
            pstar()
            pstar(30)
        
        • 在 call_star.py 中调用 star 模块:
          import star
          print(star.hi)
          star.pstar()
          star.pstar(30)
          

          37-生成密码/验证码

          此文件名为:randpass.py

          思路:

          1、设置一个用于随机取出字符的基础字符串,本例使用大小写字母加数字

          2、循环 n 次,每次随机取出一个字符

          3、将各个字符拼接起来,保存到变量 result 中

          from random import choice
          import string
          all_chs = string.ascii_letters + string.digits  # 大小写字母加数字
          def gen_pass(n=8):
              result = ''
              for i in range(n):
                  ch = choice(all_chs)
                  result += ch
              return result
          if __name__ == '__main__':
              print(gen_pass())
              print(gen_pass(4))
              print(gen_pass(10))
          

          38-序列对象方法

          from random import randint
          alist = list()  # []
          list('hello')  # ['h', 'e', 'l', 'l', 'o']
          list((10, 20, 30))  # [10, 20, 30]  元组转列表
          astr = str()  # ''
          str(10)  # '10'
          str(['h', 'e', 'l', 'l', 'o'])  # 将列表转成字符串
          atuple = tuple()  # ()
          tuple('hello')  # ('h', 'e', 'l', 'l', 'o')
          num_list = [randint(1, 100) for i in range(10)]
          max(num_list)
          min(num_list)
          

          39-序列对象方法 2

          alist = [10, 'john']
          # list(enumerate(alist))  # [(0, 10), (1, 'john')]
          # a, b = 0, 10   # a->0  ->10
          for ind in range(len(alist)):
              print('%s: %s' % (ind, alist[ind]))
          for item in enumerate(alist):
              print('%s: %s' % (item[0], item[1]))
          for ind, val in enumerate(alist):
              print('%s: %s' % (ind, val))
          atuple = (96, 97, 40, 75, 58, 34, 69, 29, 66, 90)
          sorted(atuple)
          sorted('hello')
          for i in reversed(atuple):
              print(i, end=',')
          

          40-字符串方法

          py_str = 'hello world!'
          py_str.capitalize()
          py_str.title()
          py_str.center(50)
          py_str.center(50, '#')
          py_str.ljust(50, '*')
          py_str.rjust(50, '*')
          py_str.count('l')  # 统计 l 出现的次数
          py_str.count('lo')
          py_str.endswith('!')  # 以!结尾吗?
          py_str.endswith('d!')
          py_str.startswith('a')  # 以 a 开头吗?
          py_str.islower()  # 字母都是小写的?其他字符不考虑
          py_str.isupper()  # 字母都是大写的?其他字符不考虑
          'Hao123'.isdigit()  # 所有字符都是数字吗?
          'Hao123'.isalnum()  # 所有字符都是字母数字?
          '  hello\t    '.strip()  # 去除两端空白字符,常用
          '  hello\t    '.lstrip()
          '  hello\t    '.rstrip()
          'how are you?'.split()
          'hello.tar.gz'.split('.')
          '.'.join(['hello', 'tar', 'gz'])
          '-'.join(['hello', 'tar', 'gz'])
          

          41-字符串格式化

          "%s is %s years old" % ('bob', 23)  # 常用
          "%s is %d years old" % ('bob', 23)  # 常用
          "%s is %d years old" % ('bob', 23.5)  # %d 是整数 常用
          "%s is %f years old" % ('bob', 23.5)
          "%s is %5.2f years old" % ('bob', 23.5)  # %5.2f 是宽度为 5,2 位小数
          "97 is %c" % 97
          "11 is %#o" % 11  # %#o 表示有前缀的 8 进制
          "11 is %#x" % 11
          "%10s%5s" % ('name', 'age')  # %10s 表示总宽度为 10,右对齐,常用
          "%10s%5s" % ('bob', 25)
          "%10s%5s" % ('alice', 23)
          "%-10s%-5s" % ('name', 'age')  # %-10s 表示左对齐,常用
          "%-10s%-5s" % ('bob', 25)
          "%10d" % 123
          "%010d" % 123
          "{} is {} years old".format('bob', 25)
          "{1} is {0} years old".format(25, 'bob')
          "{:
微信扫一扫加客服

微信扫一扫加客服

点击启动AI问答
Draggable Icon