zoukankan      html  css  js  c++  java
  • python基础--程序交互、格式化输出、流程控制、break、continue

    在此申明一下,博客参照了https://www.cnblogs.com/jin-xin/,自己做了部分的改动


    (1) 程序交互

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # 将用户输入的内容赋值给 name 变量
    name = input("请输入用户名:")
    # 执行脚本就会发现,程序会等待你输入姓名后再往下继续走。
    # 打印输入的内容
    print(name)
    
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # 可以让用户输入多个信息,如下
    name = input("What is your name?")
    age = input("How old are you?")
    hometown = input("Where is your hometown?")
    print("Hello ",name , "your are ", age , "years old, you came from",hometown)
    

    (2)格式化输出

    现有一练习需求,问用户的姓名、年龄、工作、爱好 ,然后打印成以下格式

    '''
    ------------ info of 周乾  -----------
    Name  : 周乾
    Age   : 23
    job   : Student
    Hobbie: girl
    ------------- end -----------------
    '''
    

    你怎么实现呢?你会发现,用字符拼接的方式还难实现这种格式的输出,所以一起来学一下新姿势

    只需要把要打印的格式先准备好, 由于里面的 一些信息是需要用户输入的,你没办法预设知道,因此可以先放置个占位符,再把字符串里的占位符与外部的变量做个映射关系就好啦

    name = input("Name:")
    age = input("Age:")
    job = input("Job:")
    hobbie = input("Hobbie:")
    info = '''
    ------------ info of %s ----------- #这里的每个%s就是一个占位符,本行的代表 后面拓号里的 name 
    Name  : %s  #代表 name 
    Age   : %s  #代表 age  
    job   : %s  #代表 job 
    Hobbie: %s  #代表 hobbie 
    ------------- end -----------------
    ''' %(name,name,age,job,hobbie)  # 这行的 % 号就是 把前面的字符串 与拓号 后面的 变量 关联起来 
    print(info)
    

    %s就是代表字符串占位符,除此之外,还有%d,是数字占位符, 如果把上面的age后面的换成%d,就代表你必须只能输入数字啦

    # age:%d
    

    我们运行一下,但是发现出错了。。。img

    说%d需要一个数字,而不是str, what? 我们明明输入的是数字呀,22,22呀。

    不用担心 ,不要相信你的眼睛我们调试一下,看看输入的到底是不是数字呢?怎么看呢?查看数据类型的方法是什么来着?type()

    name = input("Name:")
    age = input("Age:")
    print(type(age))
    

    执行输出是

    # Name:Alex
    # Age:22
    # <class 'str'> #怎么会是str
    # Job:IT
    

    让我大声告诉你,input接收的所有输入默认都是字符串格式!

    要想程序不出错,那怎么办呢?简单,你可以把str转成int

    age = int(  input("Age:")  )
    print(type(age))
    

    肯定没问题了。相反,能不能把字符串转成数字呢?必然可以,str( yourStr )

    问题:现在有这么行代码

    msg = "我是%s,年龄%d,目前学习进度为80%"%('周乾',18)
    print(msg)
    

    这样会报错的,因为在格式化输出里,你出现%默认为就是占位符的%,但是我想在上面一条语句中最后的80%就是表示80%而不是占位符,怎么办?

    msg = "我是%s,年龄%d,目前学习进度为80%%"%('周乾',18)
    print(msg)
    

    这样就可以了,第一个%是对第二个%的转译,告诉Python解释器这只是一个单纯的%,而不是占位符。

    (3)流程控制之--if

    • 假如把写程序比做走路,那我们到现在为止,一直走的都是直路,还没遇到过分叉口,想象现实中,你遇到了分叉口,然后你决定往哪拐必然是有所动机的。你要判断那条岔路是你真正要走的路,如果我们想让程序也能处理这样的判断怎么办? 很简单,只需要在程序里预设一些条件判断语句,满足哪个条件,就走哪条岔路。这个过程就叫流程控制。

    • if...else 语句

      1.单分支

      if 条件:
          #满足条件后要执行的代码
      # 例子1:
      age = 19
      #if age大于或者等于18:
      if age >= 18:
          print("成年.可以去网吧....")
      
      # 例子2
      you = input("你去么?") # 去或者不去
      yourWife = input("你老婆去么?") #去或者不去
      #if you=="去" 或者 yourWife=="去":
      if you=="去" or yourWife=="去":
          print("可以成功的办好某件事情....")
          
      # 例子3
      you = input("你去么?") # 去或者不去
      yourWife = input("你老婆去么?") #去或者不去
      #if you=="去" 并且 yourWife=="去":
      if you=="去" and yourWife=="去":
          print("可以成功的办好某件事情....")
      

      2.双分支

      """
      if 条件:
          满足条件执行代码
      else:
          if条件不满足就走这段
      """
      # 例子1
      AgeOfStudent = 48
      if AgeOfStudent > 50 :
          print("Too old, time to retire..")
      else:
          print("还能折腾几年!")
      
      # 例子2
      color = input("你白么?") #白 或者 黄
      money = int(input("请输入你的财产总和:")) #输入1000
      beautiful = input("你美么?")#美 或者 普通
      #if 白 并且 富 并且 美:
      #if 白 and 富 and 美:
      if color=="白" and money>1000000 and beautiful=="美":
          print("白富美....")
      else:
          print("矮矬穷....")
      

      3.缩进

      你会发现,上面的if代码里,每个条件的下一行都缩进了4个空格,这是为什么呢?这就是Python的一大特色,强制缩进,目的是为了让程序知道,每段代码依赖哪个条件,如果不通过缩进来区分,程序怎么会知道,当你的条件成立后,去执行哪些代码呢?

      在其它的语言里,大多通过{}来确定代码块,比如C,C++,Java,Javascript都是这样,看一个JavaScript代码的例子

      var age = 56
      if ( age < 50){
        console.log("还能折腾")
          console.log('可以执行多行代码')
      }else{
         console.log('太老了')
      }
      # not的使用,not不是的意思
      a = 30
      if not (a>0 and a<=50):
          print("在0到50之间....")
      

      在有{}来区分代码块的情况下,缩进的作用就只剩下让代码变的整洁了。

      Python是门超级简洁的语言,发明者定是觉得用{}太丑了,所以索性直接不用它,那怎么能区分代码块呢?答案就是强制缩进。

      Python的缩进有以下几个原则:

      1. 顶级代码必须顶行写,即如果一行代码本身不依赖于任何条件,那它必须不能进行任何缩进
      2. 同一级别的代码,缩进必须一致
      3. 官方建议缩进用4个空格,当然你也可以用2个,如果你想被人笑话的话。

      4.多分支

      回到流程控制上来,if...else ...可以有多个分支条件

      if 条件:
          pass
          # 满足条件执行代码
      elif 条件:
          pass
          # 上面的条件不满足就走这个
      elif 条件:
          pass
          # 上面的条件不满足就走这个
      elif 条件:
          pass
          # 上面的条件不满足就走这个    
      else:
          pass
          # 上面所有的条件不满足就走这段
      # 这里每一个条件只要满足其中一个就直接执行后面的代码。执行了一个条件满足后的代码,那么就会推出这个多分支。
      

      5.我们一块写几个例题

      # 例子1
      age_of_student = 48
      guess = int(input(">>:"))
      if guess > age_of_student :
          print("猜的太大了,往小里试试...")
      elif guess < age_of_student :
          print("猜的太小了,往大里试试...")
      else:
          print("恭喜你,猜对了...")
      
      # 例子2
      sex = input("请输入你的性别:")
      if sex == "男":
          print("你是男性,可以留胡子....")
      elif sex == "女":
          print("你是女性,可以留长头发....")
      #elif sex == "中性":
      else:
          print("你是第3中 性别,想干啥就干啥.....")
          
      # 例子3
      #1. 获取用户的输入
      num = int(input("请输入一个数字(1~7):"))
      #2. 判断用户的数据,并且显示对应的信息
      if num==1:
          print("星期1")
      elif num==2:
          print("星期2")
      elif num==3:
          print("星期3")
      elif num==4:
          print("星期4")
      elif num==5:
          print("星期5")
      elif num==6:
          print("星期6")
      elif num==7:
          print("星期7")
      else:
          print("你输入的数据有误....")
      

      上面的例子,根据你输入的值不同,会最多得到3种不同的结果

      再来个匹配成绩的小程序吧,成绩有ABCDE5个等级,与分数的对应关系如下

      # A    90-100
      # B    80-89
      # C    60-79
      # D    40-59
      # E    0-39
      

      要求用户输入0-100的数字后,你能正确打印他的对应成绩

      score = int(input("输入分数:"))
      if score > 100:
          print("我擦,最高分才100...")
      elif score >= 90:
          print("A")
      elif score >= 80:
          print("B")
      elif score >= 60:
          print("C")
      elif score >= 40:
          print("D")
      else:
          print("太笨了...E")
      # 用户只要满足其中一个条件,那么就会执行后面的代码。当执行了某一个条件时,就会执行对应代码。当执行结束后,# 就会退出这个多分支
      

      这里有个问题,就是当我输入95的时候 ,它打印的结果是A,但是95 明明也大于第二个条件elif score >=80:呀, 为什么不打印B呢?这是因为代码是从上到下依次判断,只要满足一个,就不会再往下走啦,这一点一定要清楚呀!

      例题:

      # 例子1
      ticket = 1#1表示有车票  0表示没有车票
      knifeLenght = 48#cm
      #先判断是否有车票
      if ticket==1:
          print("通过了车票的检测,进入到了车站,接下来要安检了")
          #判断刀的长度是否合法
          if knifeLenght<=10:
              print("通过了安检,进入到了候车厅")
              print("马上就要见到TA了,很开心.....")
          else:
              print("安检没有通过,等待公安处理....")
      else:
          print("兄弟 你还没有买票了,先去买票 才能进站....")
      
      # 例子2
      import random
      #1. 提示并获取用户的输入
      player = int(input("请输入 0剪刀 1石头 2布:"))
      #2. 让电脑出一个
      computer = random.randint(0,2)
      #2. 判断用户的输入,然后显示对应的结果
      #if 玩家获胜的条件:
      if (player==0 and computer==2) or (player==1 and computer==0) or (player==2 and computer==1):
          print("赢了,,,,可以去买奶粉了.....")
      #elif 玩家平局的条件:
      elif player==computer:
          print("平局了,,,洗洗手决战到天亮....")
      else:
          print("输了,,,回家拿钱 再来....")
      

    (4)流程控制之--while...else...

    • 与其它语言else 一般只与if 搭配不同,在Python 中还有个while ...else 语句

      i = 1
      while i<=100:
          print("%d"%i) #print(i)
          i = i+1
      

      while 后面的else 作用是指,当while 循环正常执行完,中间没有被break 中止的话,就会执行else后面的语句

      count = 0
      while count <= 5 :
          count += 1
          print("Loop",count)
      else:
          print("循环正常执行完啦")
      print("-----out of while loop ------")
      

      输出

      # Loop 1
      # Loop 2
      # Loop 3
      # Loop 4
      # Loop 5
      # Loop 6
      # 循环正常执行完啦
      # -----out of while loop ------
      

      如果执行过程中被break啦,就不会执行else的语句啦

      count = 0
      while count <= 5 :
          count += 1
          if count == 3:break
          print("Loop",count)
      else:
          print("循环正常执行完啦")
      print("-----out of while loop ------")
      

      输出

      # Loop 1
      # Loop 2
      # -----out of while loop ------
      
      # 例子1:
      i=1
      #用来控制行数
      while i<=5:
          #用来控制每一行中的列数
          j = 1
          while j<=5:
              print("*", end="")
              #j = j+1#c语言中向让j加上1的方式: j++;    ++j;   j+=1;  j=j+1;
              j+=1
          print("")
          i = i+1
      # 输出的结果为:
      # *****
      # *****
      # *****
      # *****
      # *****
      
      # 例子2
      i = 1
      while i<=5:
          '''
          #从键盘中输入一个值,这个值用来控制这行中*的个数
          num = int(input("请输入这个行里的*的个数:"))
          j = 1
          while j<=num:
              print("*", end="")
              j+=1
          '''
          j = 1
          while j<=i:
              print("*", end="")
              j+=1
          print("")
          i+=1
      # 输出的结果为:
      # *
      # **
      # ***
      # ****
      # *****
      
      # 例子3
      i = 1
      while i<=9:
          j = 1
          while j<=i:
              print("%d*%d=%d	"%(j,i,i*j), end="")
              j+=1
          print("")
          i+=1
      # 输出的结果为:
      # 1*1=1	
      # 1*2=2	2*2=4	
      # 1*3=3	2*3=6	3*3=9	
      # 1*4=4	2*4=8	3*4=12	4*4=16	
      # 1*5=5	2*5=10	3*5=15	4*5=20	5*5=25	
      # 1*6=6	2*6=12	3*6=18	4*6=24	5*6=30	6*6=36	
      # 1*7=7	2*7=14	3*7=21	4*7=28	5*7=35	6*7=42	7*7=49	
      # 1*8=8	2*8=16	3*8=24	4*8=32	5*8=40	6*8=48	7*8=56	8*8=64	
      # 1*9=9	2*9=18	3*9=27	4*9=36	5*9=45	6*9=54	7*9=63	8*9=72	9*9=81
      
      # 例子4 打印1-100之间的偶数
      i = 1
      while i<=100:
          #if i是个偶数:
          if i%2==0:
              print(i)
          i+=1
      
      # 例子5 打印1-100之间的前20个偶数
      i = 1
      num = 0
      while i<=100:
          #if i是个偶数:
          if i%2==0:
              print(i)
              num+=1
          if num==20:
              #break的作用 用来结束while循环,
              #即 如果在while执行的过程中,不想循环了,可以用break来做到这个效果0:
              break
          i+=1
      

    (5)流程控制之--for...else...

    # 这里补充一个知识点是in 和not in,见名知意即可
    # in 和 not in 见名知意即可,在或者不在
    # s1 = '学生edu'
    # print('学' in s1)  # True
    # print('学生' in s1)  # True
    # print('学ed' in s1)  # False
    # print('学ed' not in s1)  # True
    
    # for循环的讲解
    s1 = '写博客大师最无聊的人:周乾'
    '''
    写
    博
    客
    大
    师
    '''
    # while循环的使用
    # index = 0
    # while index < len(s1):
    #     print(s1[index])
    #     index += 1
    # for循环的使用
    '''
    for循环是有限循环,可以再有限的循环的步骤里面做完相应的事情
    for 变量 in iterable
        pass
    '''
    length = len(s1)
    print(length) # 输出的是长度
    
    # for循环的使用
    for i in s1:
        print(i)
    # for循环与break 和 continue 结合使用
    # for else : while else:用法是一样的
    
    # for i in 'afdsf':
    #     print(i)
    # break continue
    s1 = 'fadadnasj'
    # for i in s1:
    #     # print(i)
    #     if i == 'a':
    #         continue
    #     print(i)
    # 不打印,但是也循环了,每次continue就跳到下一次循环了
    for i in s1:
        continue
        print(i)
    

    (6)break的用法

    break的用法:break是结束循环。遇见break,我们就退出循环,终止循环。也可以用break语句在循环结构终止本层循环体,从而提前结束本层循环。

    flag = True
    print(111)
    while flag:
        print('痒')
        print('社会摇')
        print('喜洋洋')
        break
        print('我要这铁棒有何用')
    print(222)
    # 输出的结果为:
    # 111
    # 痒
    # 社会摇
    # 喜洋洋
    # 222
    
    i = 1
    while i<=5:
        print("-----")
        if i==3:
           break
        print(i)
        i+=1
    # 输出的结果为:
    # -----
    # 1
    # -----
    # 2
    # -----
    
    count = 0
    while count <= 5 :
        count += 1
        if count == 3:break
        print("Loop",count)
    
    else:
        print("循环正常执行完啦")
    print("-----out of while loop ------")
    

    (7)continue的用法

    continue的用法:continue是循环。遇见continue,我们就,终止本次循环。continue语句的作用是跳过本次循环体中余下尚未执行的语句,立即进行下一次的循环条件判定,可以理解为仅结束本次循环。

    flag = True
    print(111)
    while flag:
        print('痒')
        print('社会摇')
        print('喜洋洋')
        continue
        print('我要这铁棒有何用')
    print(222)
    
    count = 0
    while count < 10:
        count = count + 1
        if count == 7:
            continue
        print(count)
    # 输出的结果为:
    # 1
    # 2
    # 3
    # 4
    # 5
    # 6
    # 8
    # 9
    # 10
    
    count = 0
    while count <= 100 : 
        count += 1
        if count > 5 and count < 95: #只要count在6-94之间,就不走下面的print语句,直接进入下一次loop
            continue 
        print( count)
    # 输出的结果为:
    # 1
    # 2
    # 3
    # 4
    # 5
    # 95
    # 96
    # 97
    # 98
    # 99
    # 100
    # 101
    

    (8)break和continue的区别

    • break:终止循环
    • continue:终止本次循环
    • break和continue的区别:break会跳出当前循环,也就是整个循环都不会执行了。而continue则是提前结束本次循环,直接继续执行下次循环。

    (8)基本运算符

    • 运算符

      计算机可以进行的运算有很多种,可不只加减乘除这么简单,运算按种类可分为算数运算、比较运算、逻辑运算、赋值运算、成员运算、身份运算、位运算,今天我们暂只学习算数运算、比较运算、逻辑运算、赋值运算、成员运算

    • 算数运算

      以下假设变量:a=10,b=20

      a = 10
      b = 20
      print(a+b)
      print(a-b)
      print(a*b)
      print(a**b)
      print(a/b)
      print(a//b)
      # 输出的结果为:
      # 30
      # -10
      # 200
      # 100000000000000000000
      # 0.5
      # 0
      
    • 比较运算

      以下假设变量:a=10,b=20

      a = 10
      b = 20
      print(a == b)
      print(a != b)
      print(a > b)
      print(a < b)
      print(a >= b)
      print(a <= b)
      # 输出的结果为:
      # False
      # True
      # False
      # True
      # False
      # True
      

    img

    • 赋值运算

      以下假设变量:a=10,b=20

      a = 10
      b = 20
      print(a, b)
      # 输出的结果为:10,20
      
    • 逻辑运算

    img

    • 针对逻辑运算的进一步研究:

      1.在没有()的情况下not 优先级高于 and,and优先级高于or,即优先级关系为( )>not>and>or,同一优先级从左往右计算。

      例题:

      判断下列逻辑语句的True,False。

      # 1,3>4 or 4<3 and 1==1
      # 2,1 < 2 and 3 < 4 or 1>2 
      # 3,2 > 1 and 3 < 4 or 4 > 5 and 2 < 1
      # 4,1 > 2 and 3 < 4 or 4 > 5 and 2 > 1 or 9 < 8
      # 5,1 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 66,not 2 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6
      

      2 . x or y , x为真,值就是x,x为假,值是y;

      x and y, x为真,值是y,x为假,值是x。

       img

      例题:求出下列逻辑语句的值。

      # 8 or 4
      # 0 and 3
      # 0 or 4 and 3 or 7 or 9 and 6
      
    • 成员运算

      除了以上的一些运算符之外,Python还支持成员运算符,测试实例中包含了一系列的成员,包括字符串,列表或元组。

      img

      ​ 判断子元素是否在原字符串(字典,列表,集合)中:

      ​ 例如:

      # print('喜欢' in 'dkfljadklf喜欢hfjdkas')
      # print('a' in 'bcvd')
      # print('y' not in 'ofkjdslaf')
      
    • Python运算符优先级

      以下表格列出了从最高到最低优先级的所有运算符:

    运算符 描述
    ** 指数 (最高优先级)
    ~ + - 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@)
    * / % // 乘,除,取模和取整除
    + - 加法减法
    >> << 右移,左移运算符
    & 位 'AND'
    ^ | 位运算符
    <= < > >= 比较运算符
    <> == != 等于运算符
    = %= /= //= -= += *= **= 赋值运算符
    is is not 身份运算符
    in not in 成员运算符
    not and or 逻辑运算符
  • 相关阅读:
    BZOJ_2002_[Hnoi2010]Bounce 弹飞绵羊_LCT
    BZOJ_4154_[Ipsc2015]Generating Synergy_KDTree
    BZOJ_2801_[Poi2012]Minimalist Security_dfs树+特判+乱搞
    BZOJ_3123_[Sdoi2013]森林_主席树+启发式合并
    2019集训队作业做题实况[1](1-30):
    牛客挑战赛33 F 淳平的形态形成场(无向图计数,EGF,多项式求逆)
    【NOIP2019模拟2019.10.07】果实摘取 (约瑟夫环、Mobius反演、类欧、Stern-Brocot Tree)
    CodeChef Max-digit Tree(动态规划)
    骚操作:c++如何用goto便捷地写人工栈?
    Comet OJ
  • 原文地址:https://www.cnblogs.com/stu-zhouqian/p/13140304.html
Copyright © 2011-2022 走看看