python如何学习(三)

发布时间:2019-06-23 08:43:10编辑:auto阅读(1192)

    最近开始整理python的资料,博主建立了一个qq群,希望给大家提供一个交流的同平台 78486745 。

    一、第一个Python程序--HelloWorld

    python的第一个程序也从hello world开始吧:

    #!/usr/bin/env python
    #! -*- coding:utf-8 -*-
    print("Hello world!")

    执行结果:

    "C:\Program Files\Python37\python.exe" D:/python/Day1/test/HelloWorld.py
    Hello world!
    
    Process finished with exit code 0
    a

    二、If-else判断

    2.1 If-else语法规范

    以下是if-else判断的语法结构规范:

    if condition1:
        command_layer1_1
        if condition2:
            command_layer2_2
        else:
            command_layer2_2
    else:
        command_layer1_2  

    2.2 示例程序

    以下为一个演示两层if-else循环的程序:

    #!/usr/bin/env python                                         #顶格编写
    #! -*- coding:utf-8 -*-
    user_input = input("Please input you username:")
    if user_input == "Bob":                                       #注意这里的冒号结尾
        passwd_input = input("Please input your password:")       #注意从这里开始,第一个if条件为真时需要执行的动作语句均需要左缩进4个空格
        if passwd_input == "password":                            #第一个if下的第二个if,仍然要左缩进4个空格,同时冒号结尾
            print("Welcome login,%s!" %user_input)                #第二层if条件为真时执行的动作语句,需要在第一层语句基础上再缩进4个空格,因此需要缩进8个空格
        else:                                                     #第二层if-else中的else,因此需要与第二层if对齐,缩进4个空格
            print("Invalid username or password, please check your input") #第二层if-else条件为假时执行的动作语句,同样需要与第二层if一样缩进8个空格
    else:                                                         #第一层if-else中的else关键字,顶格冒号结尾
        print("Invalid username or password, please check your input") #第一层if-else判断条件为假时执行的动作,与第一层if一样需要缩进4个空格

    说明:该示例程序仅为演示多层if-else的语法结构,程序本身的设计存在漏洞;空格缩进在pycharm IDE环境中会被自动处理,但在普通文件编辑器中需要手动设置。
    以下为改良版示例程序,通过引入对if的多条件判断来避免上述程序的漏洞:

    #!/usr/bin/env python
    #! -*- coding:utf-8 -*-
    username=input("Please input you username:\n")
    passwd=input("Please input you password:\n")
    if username == "Bob" and passwd == "password":
        print("Welcome login, %s!" %username)
    else:
        print("Invalid username or password, please check your input!")

    此时只有用户名和密码同时输入正确了才会给出相应提示,否则均提示口令无效,避免暴力破解。

    2.3 if-elif-else扩展

    上述判断均为单一式的if-else判断,以下为if-elif-else的判断扩展:
    语法结构:

    if condition1:
        command1
    elif condition2:
        command2
    elif condition3:
        command3
    else condition4:
        command4

    不过这种结构仅仅适用于单一条件存在多种case情况下,语法结构看起来还是比较简单,当然顶格、左缩进4个空格和冒号这些规范一样要遵循。
    还是来一个示例程序加深理解:

    #!/usr/bin/env python
    #! -*- coding:utf-8 -*-
    age=int(input("Please input your age\n"))
    if age >= 18:
        print("Oh, you're an adult\n")
    elif age >=6:
        print("Ha, you're a teenager\n")
    else:
        print("Come on, little kid!\n")

    三、For循环

    最近开始整理python的资料,博主建立了一个qq群,希望给大家提供一个交流的同平台 78486745 。

    3.1 for循环语法规范

    For循环的基本语法规范是:

    for variable in XXX:
        loop command

    其中variable表示命名的变量,一般程序中使用i,j等等,XXX表示变化的范围,可以是list列表,一般会考虑使用range函数,来表示一个整数序列,如range(5)就表示小于5的整数序列,即0-4。 语法规范中同样需要for语句后面的结尾冒号,以及循环体中的4个空格的左缩进。

    3.2 示例程序

    猜数字游戏,通过系统生成一个随机数作为预设年龄,对用户提供3次猜的机会,前两次如果没有猜中给出数字范围大小的提示,如果第3次还没有猜中则给予鼓励提示,同时打印出这个预设的数字,当然三次当中有任何一次猜中会给用户猜中提示的:

    #!/usr/bin/env python
    #! -*- coding:utf-8 -*-
    import random #导入随机数模块
    Age=random.randrange(10)#随机生成一个小于10的整数(0-9,不包括负数),并赋值给Age
    for i in range(3):
        if i < 2:
            guess_number=int(input("Please input the age of my dog you guess:\n"))
            if guess_number > Age:
                print("The age you guess is a little big, think smaller!\n")
            elif guess_number < Age:
                print("The age you guess is a little small, think bigger!\n")
            else:
                print("Bingo, you got the number,congratulations!\n")
                break
        else:
            guess_number=int(input("Please input the age of my dog you guess:\n"))
            if guess_number == Age:
                print("Bingo, you got the number,congratulations!\n")
            else:
                print("Oh,you just got bad luck, come to try again, you can do it! The actual age of my dog is %d...\n"% Age)

    注意:

    1. 为便于程序调试可先对Age赋值固定的数字
    2. 前两次如果猜中了就需要退出循环,这里使用了break关键字,意思是跳出整个循环,与之相对应的还有continue关键字,用于跳出当次循环,二者的使用区别在于是否执行完整个集合

    OK,现在来改进下程序, 当用户连续三次猜错后继续给机会,让用户选择是继续猜还是直接退出,如果继续则再一次获得三次猜的机会,如此循环下去。还是用for循环吧:

    #!/usr/bin/env python
    #! -*- coding:utf-8 -*-
    Age=22
    counter=0
    for i in range(10):
        if counter < 3:
            guess_number=int(input("Plese input your guess number:\n"))
            if guess_number == Age:
                print("You got the number, congratulations!")
                break
            elif guess_number > Age:
                print("The number you guessed is too big, guess a smaller one\n")
            else:
                print("The number you guessed is too small, guess a bigger one\n")
            counter += 1
        elif counter == 3:
            continue_flag=input("Do you want to continue? Please type Y to continue or N to quit:\n ")
            if continue_flag == "Y":
                counter = 0
            else:
                print("Bye")
                break
        else:
            print("You've tried too many times.")

    这里为了保证每一个轮回中的第四次(上述程序中的第四次和第八次)能让程序继续循环,引入了另外一个变量来进行计数并重置。把for循环换作while循环看起来差不多:

    #!/usr/bin/env python
    #! -*- coding:utf-8 -*-
    Age=22
    i=0
    counter=0
    while counter < 10:
        if i < 3:
            guess_number=int(input("Plese input your guess number:\n"))
            if guess_number == Age:
                print("You got the number, congratulations!")
                break
            elif guess_number > Age:
                print("The number you guessed is too big, guess a smaller one\n")
            else:
                print("The number you guessed is too small, guess a bigger one\n")
            i += 1
        else:
            continue_flag=input("Do you want to continue? Please type Y to continue or N to quit:\n ")
            if continue_flag == "Y":
                i = 0
            else:
                print("Bye")
                break
        counter +=1

    小结

    1. Python是一门主流且发展迅猛的开发语言,目前存在2.x和3.x两个版本分支,前端后端都能胜任,功能强大,在互利网公司应用广泛,值得托付;
    2. Python程序的开发需要安装解释器和IDE,建议使用pycharm,2.x和3.x下的默认字符编码不同,永远推荐使用utf-8编码,包括程序编码和解释的编码两个层面;
    3. 系统自带模块和自定义编写的模块均可以通过import导入使用;
    4. 在进行python程序开发时,注意代码需要分层体现,第一层代码顶格编写,第二层(用在第一次出现的流程控制语句中的代码块)左缩进4个空格;
    5. input用于接收用户输入,默认输入的数据类型是字符串,可通过int关键字转换为整数。print可进行简单输出,如要格式化输出则需要借助%s %d %f等来实现,具体视数据类型而定;
    6. 流程控制语句if-else判断和for、while循环都需要注意代码书写格式,流程控制语句关键字一定是以冒号结尾,具体的流程控制代码块则需要左缩进处理,第一层左缩进4个空格,第二层8个空格,以此类推;
    7. continue和break可分别用于退出当前(当次)流程控制和整个循环,课堂上演示了在for循环中的使用,在if-else判断中不能使用。

    【搜索圆方圆,获得“python教程”,“python下载”,“python入门”类相关信息。】

关键字