zoukankan      html  css  js  c++  java
  • python基础汇总(三)

    想成为一个优秀的python程序员,从而走上全栈前端工程师的职位,阅读能力是一个必备的能力。

    以现在的水平,你还不具备完全理解你找到代码的能力,不过通过接触这些代码,你可以熟悉真正的变成项目是什么样子的。

    我将列举一些适合看python代码的网址,很简单,直接看.py结尾的文件都可以。(setup.py的文件就忽略吧)

    1.bitbucket.org

    2.launchpad.net

    3.sourceforge.net

    4.freecode.com

    大胆阅读吧,人生苦短,我用python。

    在开始本期正题之前,我们需要知道逻辑关系的重要性,这即将和我们要学到的if判断语句有关:

    and 与
    or 或
    not 非
    != 不等于
    == 等于
    >= 大于等于
    <= 小于等于
    True 真
    False 假

    例子: 3!=4 and not("testing" != ="test"  or  "python" =="python")

    解析: True  and False

    答案:False

    那么,我还是直接点,贴出一段if和else函数的代码:

    people=int(input('pepple:'))
    cars= int(input('cars:'))
    buses=int(input('buses:'))

    if cars > people:
        print("We should take the cars.")
    elif cars < people :
        print("We should not take the cars.")
    else:
        print("We can't decide.")

    if buses > cars:
        print("That's top many buses.")
    elif buses < cars:
        print("Maybe we could take the buses.")
    else:
        print("We still can't decide.")

    if people < buses:
        print("Alright, let's just take the buses.")
    else:
        print("Fine,let's stay home then.")
     
    不要忘了,input输入的东西都是字符串格式噢,所以在后面if的比较数字大小之前,需要将输入的转换成int。
    那么我输入三个数据如下:

    pepple:30
    cars:20
    buses:40

    输出结果:
    We should not take the cars.
    That's top many buses.
    Alright, let's just take the buses.

    基本就是这段代码按着你输入的数据,选择语句打印出来。那么,elif是什么呢?

    想必大家也看出来了,其实就是python中的将if  else 缩写成了elif:,这就很符合python的特点了:优美简洁。

    那么我想问三个问题:

    ①你认为if对它的下一行代码做了什么了?

    ②为什么if语句的下一行需要四个空格的缩进,不缩进会怎么样?

    ③如果多个elif块都是True,Python会如何处理?

    大家心里有答案了吗?

    ①if语句为代码创建了一个所谓的分支。if语句告诉你的脚本:如果这个布尔表达式为真,就运行分支的内容,否则就跳过。

    ②行尾的冒号的作用就是告诉Python接下来你要创建一个新的代码块。如果没有缩进,就会报错。因为Python的规则里,只要一行以冒号(:)结尾,接下来的内容就必须缩进。

    ③Python只会运行遇到的第一个True块,余下的直接跳过。

    那么,大家学了了上面,应该有能力写出更加有趣的程序出来了,熟练使用if,else,elif创建包含条件判断的脚本了,不妨花点时间试试写一段程序。

    在这儿我要罗嗦一下,你可以在if语句内部再放一个if语句,这是一个很强大的功能,可以用来创造嵌套的决定,其中一个的分支引向另一个分支的子分支。

    有人会问,如果想实现4个以上的判断呢?很简单,多写几个elif块就行了。

    小弟不才,我也写了一个一段家庭情况调查的代码,这段代码我大概讲一下:

    首先要你输入爸妈的姓名,然后问你有没有兄弟姐妹,如果有的话,要你输入爸妈和兄弟姐妹的年龄。如果没有,要你输入爸妈的年龄。

    print("Today,You'll introduce your family members to you.")
    print("Please write down your information about your family.")
    father=input("What's your father name?>")
    mother=input("What's your mother name?>")
    other_people=input("Do you have brother or sister?which?>")
    if other_people == 'brother' or other_people == 'sister':
     
        other_people_name=input("What's your %s name?>"%other_people)
        print("Right,your family has four members now, father:%s mother:%s %s:%s and you. "
        %(father,mother,other_people,other_people_name))
        father_age=int(input("Please write down your father age:"))
        mother_age=int(input("Please write down your mother age:"))
        other_people_age=int(input("Please write down your %s age:"%other_people))

            if (father_age >mother_age) and (mother_age > other_people_age) and (father_age > other_people_age):
                print("Well,your family is very harmonious. ")
            elif (father_age < mother_age) and (mother_age>other_people_age)and (father_age>other_people_age):
                print("Oh,your mother may be a family leader. ")
            else:
                print("What the fuck?you may write wrongly. ")

    else:
        print("Right,your family has there members now, father:%s mother:%s and you. "
        %(father,mother))
        father_age=int(input("Please write down your father age:"))
        mother_age=int(input("Please write down your mother age:"))
     
            if father_age >mother_age:
               print("Well,your family is very harmonious. ")
            else:
               print("Oh,your mother may be a family leader. ")

    print("Thanks for your time.")
     
    输出结果是这样的:

    Today,You'll introduce your family members to you.
    Please write down your information about your family.
    What's your father name?>master
    What's your mother name?>paopao
    Do you have brother or sister?which?>brother
    What's your brother name?>didi
    Right,your family has four members now,
    father:master
    mother:paopao
    brother:didi
    and you.

    Please write down your father age:50
    Please write down your mother age:45
    Please write down your brother age:10
    Well,your family is very harmonious.

    Thanks for your time.

    当然了,加粗的内容部分是我键入回答问题的内容,怎么样,我写的这段程序还可以吧?

    如果你输入的兄弟姐妹的年龄大于你的爸妈,这个程序会反馈你:What the fuck?you may write wrongly.

    有兴趣的,可以复制过去自己运行试试噢,嘿嘿。

    不过,不要太过于对自己的代码盲目,时刻对自己的程序有一个批判的态度,我写出来的程序并非最佳的程序,问题还是很多:

    ①只能支持一个兄弟姐妹的情况,有些人家里有两个哥哥姐姐,在这段程序中无法得到反馈。

    ②代码有太多重复的地方,不知道如何去最简化。

    ③妈妈的年龄不一定一定要比兄弟姐妹年龄大,有些父亲可以找年轻的后妈啊,比自己的儿女年轻……咳咳,扯远了,大家忽略这一条。

    总之,你们看到这儿,你们最好也去尝试写一段if/elif/else代码,锻炼自己的动手能力,写完之后审视一下自己写的程序有哪些不足。

    好了,我们接下来来介绍一下列表和while的知识:

    while循环,顾名思义,会一直执行它下面的代码块,直到它对应的布尔表达式为False时才会停下来。

    和if语句不一样的是,它下面的代码块不是只被运行一次,而是运行完后再跳回到while所在的位置,如此重复进行,直到while表达式为False为止。

    那么我直接贴出列表和while的程序:

    elements=[]
    for i in range(0,5):
        print("This one is %d"%i)
        elements.append(i)
        print("The element:",elements)
        print(" ")

    print("Now,the elements:",elements)

    输出结果:

    This one is 0
    The element: [0]

    This one is 1
    The element: [0, 1]

    This one is 2
    The element: [0, 1, 2]

    This one is 3
    The element: [0, 1, 2, 3]

    This one is 4
    The element: [0, 1, 2, 3, 4]

    Now,the elements: [0, 1, 2, 3, 4]

    相信大家都能看得懂这段代码和运行结果,这儿就简单说一下吧:

    append()到底是什呢?

    它的功能是在列表的尾部追加元素。

    for循环和while循环有什么不同?

    for循环只能对一些的集合进行循环,while循环可以对任何对象进行循环,然而,while循环比起来更难弄,一般的任务用for循环更容易一些。

    访问列表的元素到底是个什么情况呢?

    这就是涉及到基数和序数了,扯概念的话估计也不懂,我用英语举例子,one,first。能理解了吗?一和第一的区别。只是在python列表中第一个基数是以0开始的,但它对应的是序数第一。

    好了,现在已经到了一个激动人心的时刻了,本篇文章迈入一个高潮的时刻,前方高能,请备好纸巾。

    我将放出一个游戏的代码程序,大家试着花时间去理解这个游戏:

    from sys import exit #从sys功能包调用exit功能

    def gold_room():
        print("This room is full of gold. How much do you take? ")

        next=int(input("> ")) #经过优化过的代码
        if next >= 0:
        # next =input("> ") #这代码欠缺优化
        # if "0" in next or "1" in next:
            how_much=int(next)
        else:
            dead("Man,learn to type a number. ")

        if how_much <50:
           print("Nice,you're not greedy,you win!")
           exit(0) #exit(0)表示程序正常退出。在本段程序中,就是一个死亡的意思,游戏失败。
        else:
           dead("You greedy bastard!")

    def bear_room():
        print("There is a bear here.")
        print("The bear has a bunch of honey.")
        print("The fat bear is in front of another door.")
        print("How are you going to move the bear?")
        print("take honey or taunt bear? ")
        bear_moved = False

        while True: #创建一个无限循环。
            next=input("> ")

            if next == "take honey":
                dead("The bear looks at you then slaps your face off.")
            elif next =="taunt bear" and not bear_moved:
                print("The bear has moved from the door. You can go through it now.")
                bear_moved =True
                print("open door or taunt bear again? ")
            elif next == "taunt bear again" and bear_moved:
                dead("The bear gets pissed off and chews your leg off.")
            elif next== "open door" and bear_moved:
                gold_room()
           else:
                print("I got no idea what that means.")

    def cthulhu_room():
        print("Here you see the great evil Cthulhu.")
        print("He, it, whatever stares at you and you go insane.")
        print("Do you flee for your life or eat your head? ")

        next =input("> ")

        if "flee" in next:
            start()
        elif "head" in next:
            dead("Well that was tasty!")
        else:
            cthulhu_room()

    def dead(why):
        print(why,"Good,job!")
        exit(0)

    def start():
        print("You are in a dark room.")
        print("There is a door to your right and left.")
        print("Which one do you take? ")

        next=input("> ")

        if next=="left":
            bear_room()
        elif next == "right":
            cthulhu_room()
        else:
            dead("You stumble around the room until you starve.")

    start()

    我会给你们时间消化这段代码,并让它成功运行出来。然后问你们五个问题:

    ①开头的时候,我优化了以下两行代码:

     next =input("> ") 
     if "0" in next or "1" in next:
    请问,如果按这两行在里面运行,你们会遇到什么BUG?
    优化成下面这两行代码过后,问题得到解决了?
     next=int(input("> ")) 
     if next >= 0:
    ②你能把这游戏的地图画出来吗?并把自己的路线也画出来。
    ③为什么会加入while True的无限循环?有什么意义?
    ④去查询一下exit(0)有什么意义?
    ⑤dead()到底是什么原理,在程序中有什么作用?
     
    给大家一定的时间去解答一下这四个问题,停止向下浏览吧。
    ①如果按原代码运行,如果你要键入9,这段代码就会报错,因为它的要求就是要你输入含有0或1的数字,很显然这不合规矩。
    所以优化之后,你输入的任何数字都转换为整数形式,符合用户输入的需求。
    ②我大概画了一个比较好看的地图,不喜勿喷,我觉得我画得很好。
    然后我说一下我成功的路线吧,就是右转进入恶魔室,忽然反悔,安全回到了起点,左转进入大熊室,我选择了嘲讽大熊,
    这时候熊让开了,我进去了黄金室,拿了49个黄金,被表扬不贪婪,游戏成功。

    You are in a dark room.
    There is a door to your right and left.
    Which one do you take?

    > right
    Here you see the great evil Cthulhu.
    He, it, whatever stares at you and you go insane.
    Do you flee for your life or eat your head?

    > flee
    You are in a dark room.
    There is a door to your right and left.
    Which one do you take?

    > left
    There is a bear here.
    The bear has a bunch of honey.
    The fat bear is in front of another door.
    How are you going to move the bear?
    take honey or taunt bear?

    > taunt bear
    The bear has moved from the door. You can go through it now.
    open door or taunt bear again?

    > open door
    This room is full of gold. How much do you take?

    > 49
    Nice,you're not greedy,you win!

    当然了,老规矩,加粗的自然是键入的数据。
    但是这世界不缺作死的人,嘲讽大熊还不够,想要继续得瑟,会再次回到选择门,直奔熊而去。

    You are in a dark room.
    There is a door to your right and left.
    Which one do you take?

    > left
    There is a bear here.
    The bear has a bunch of honey.
    The fat bear is in front of another door.
    How are you going to move the bear?
    take honey or taunt bear?

    > taunt bwar
    I got no idea what that means.

    > taunt bear
    The bear has moved from the door. You can go through it now.
    open door or taunt bear again?

    > taunt bear again
    The bear gets pissed off and chews your leg off. Good,job!

    很显然,愤怒的大熊受不了你的再次嘲讽,选择了卸掉了你的腿,游戏失败。
    当然,有人可能注意到了,我输错了一次,又回到了选择的阶段,不影响本次代码的继续运行,那么这就是第三个问题了,也就是While True。
    ③While True的意义当然很大了,你也看到了,我输错了之后,这段代码块并没有报错,而是打印了一条消息又经While True无限循环回到了开始选择门的阶段。
    还有一个重要的作用就是,选择之后还有选择,就像你嘲讽大熊成功之后,后面还有一个开门进入黄金屋的选择啊。
    如果你没有While True的话,你嘲讽大熊成功之后,这个if/elif/else的代码块就结束了,游戏也就结束了。就不会有后面开门进入黄金屋通关游戏的选择了。
    当然了,如果恶魔屋输错了怎么办,我们可以看到恶魔屋的else的语句就是为输错而准备的,会反复让你停留在恶魔屋,直到你输入对了为止。
    那么有人就会找茬,黄金屋不输入数字怎么办?
    emm……这段代码会直接报错,玩游戏还是要遵守规则。不过你直接输入-50的话就不会报错了,会判定你死亡噢!
    ④exit(0)可以说是核心了,我们先来看看作用,在很多类型的操作系统里,exit(0)可以中止某个程序,可以表示正常退出程序。
    当然了,你可以用不同的数字参数表示不一样的错误,比如exit(1)和exit(100)是不同的错误。要使用exit()首先就得从sys模块引入。
    回到正题,exit(0)就是dead函数的核心,我们来看下一题。
    ⑤做一个有成功和失败的游戏程序,创造dead函数是不可避免的,定义一个dead函数里面,打印出死亡的原因,然后用exit(0)结束这代码,表示游戏的结束。
     
    永远都不要害怕看懂长长的代码,我的推荐方法就是拆开来看,然后再又贯通起来,画一张地图,就可以慢慢去理解这段代码了。
    那么,你们试过把加粗的字体反过来看吗?
    画一张地图,确定各部分之间的联系,然后拆开各部分写程序,最后连起来。
    没错,我布置的任务就是要你制作一个不同类型的游戏,运用本章的知识点,结合上一行加粗的字体的方法,再看看下面:
    1.每一条if语句必须包含一个else。不为什么,就是为输错的情况而准备的。
    2.如果else不被使用,那将没有任何意义,你要么加个While True再给用户机会,要么就dead安排用户出局。
    3.使用if/elif/else使应当耐心,将它们看成一个个段落。每个段落之间适当用一个空行隔开,增加代码的可读性。
    4.如果if后面的布尔测算句子很复杂,可以尝试先赋予到一个取好名字的变量里面,也是增加代码可读性。
     
    祝你能够成功写出一个游戏!
     
  • 相关阅读:
    JAVA面试——设计模式
    CSS清除浮动
    CSS外边距
    baidu-ife
    笔记一则
    Atom
    校园网认证
    四月甘九-省
    Python sys.argv[]用法
    Python模块导入的方法
  • 原文地址:https://www.cnblogs.com/Masterpaopao/p/10035513.html
Copyright © 2011-2022 走看看