美文网首页
Day01 - Python基础1

Day01 - Python基础1

作者: 乘风逐月 | 来源:发表于2016-11-09 23:10 被阅读0次

    Day01的课程要点记录
    详细教程地址:金角大王 - Day1 Python基础1 | 银角大王 - 初始Python

    一、我能学会吗?

    Can I become a great coder?
    Yes - in time. The best coders go through several phases on their programming journey:

    1. The "I know nothing" phase - 起始阶段
      Everything is new, nothing is easy.
    2. The "it's starting to make sense" phase -
      You're written a few programs and are making fewer mistakes.
    3. The "I'm invincible" phase - 第三个月到第五个月
      Your confindence matches your competence. No challenge seems to difficult.
    4. The "I know nothing" phase,part II - 项目实战
      The sudden realization that development is infinitely more complex and you begin to doubt your own abilities.
    5. The "I know a bit and that's OK" phase - 四、五年开发经验
      You have decent coding skills but recognize your limitations and can find solutions to most problems (even if that means hiring another developer).

    二、2与3的选择

    语法区别
    #2.x
    print “hello world”
    
    #3.x
    print("hello")
    
    2.x 汉字需要声明
    #_*_coding:utf-8_*_
    

    三、Python安装

    • Windows
    1、下载安装包
        https://www.python.org/downloads/
    2、安装
        默认安装路径:C:\python27
    3、配置环境变量
        【右键计算机】-->【属性】-->【高级系统设置】-->【高级】-->【环境变量】-->【在第二个内容框中找到 变量名为Path 的一行,双击】 --> 【Python安装目录追加到变值值中,用 ;分割】
        如:原来的值;C:\python27,切记前面有分号
    
    • Linux、Mac
    无需安装,原装Python环境
    ps:如果自带2.6,请更新至2.7
    

    四、Python入门

    • Hello World程序
    print("Hello World!")
    
    • 在Linux下运行
    print("Hello World!")
    print("Hello Again.")
    print("hello again \ntwice") #\n 为换行
    
    #检查是否有可执行权限
    ll hello.py (Mac: ls -slh)
    #添加可执行权限
    chmod +x hello.py #方法1
    chmod 755 hello.py #方法2
    
    #指定解释器 - 在文件第一行添加
    #!/usr/bin/python (不推荐)
    #!/usr/bin/env python (推荐)
    
    • 注意点
    1. 带有引号的(‘ "),无论几个,都代表是字符串。
    2. 命名推荐两种方式:“MyName” or “my_name”

    五、字符编码

    1.指定字符集
    #!/usr/bin/env python #指定解释器
    # -*- coding: utf-8 -*- #指定字符集
     
    print "你好,世界"
    
    2.设置模版

    [Settings] --> [Editor] --> [File and Code Templates] --> [Python Script]

    3.注释

    单行注释:# 被注释内容
    多行注释:""" 被注释内容 """ (三个引号,单引号双引号均可。)

    六、变量

    1.声明变量
    name = "Will"
    

    上述代码声明了一个变量,变量名为: name,变量name的值为:"Will"

    2.变量定义的规则
    • 变量名只能是 字母、数字或下划线的任意组合
    • 变量名的第一个字符不能是数字
    • 以下关键字不能声明为变量名
      ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
    3.变量的赋值
    name = "Will Wang"
    name2 = name #name2指向name所指向的"Will Wang"
    print(name, name2) 
     
    name = "Jack"  #内存中开辟新地址保存为“Jack”
    print(name, name2)
    print("What is the value of name2 now?\n" + name2)
    

    七、用户输入

    1. 输入用户名
    • 2.x
    name = raw_input("Please input your name:")
    print("Welcome," + name)
    
    • 3.x
    name = input("Please input your name:")
    print("Welcome," + name)
    
    2. 格式化字符串
    name = input("Please input your name:")
    age = int(input("Please input your age:")) #convert str to int
    job = input("Please input your job:")
     
    msg = '''
    Information of user %s:
    Name:   %s
    Age :   %d
    Job :   %s
    '''%(name, name, age, job)
    print(msg)
    

    Ctrl + D 复制当前行
    占位符:%s = string 字符,%d = digital 数字,%f = 小数、浮点
    input 默认输入的是字符串,数字需要用int()转换

    3. 常用模块初识
    • getpass 输入密码
    #Pycharm下不可用,仅限于Linux命令行或Windows的CMD
    import getpass
    username = input("username:")
    password = getpass.getpass("password:")
    print(username, password)
    
    • OS 调用系统命令
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
     
    import os
     
    os.system("df -h")  #调用系统命令
    
    import os
    
    os.system("df")
    os.mkdir("yourDir")
    cmd_res = os.popen("df -h").read() #读取内存中的显示值并打印
    
    4. 自己写个模块

    python tab补全模块

    • for Mac
    import sys
    import readline
    import rlcompleter
     
    if sys.platform == 'darwin' and sys.version_info[0] == 2:
        readline.parse_and_bind("bind ^I rl_complete")
    else:
        readline.parse_and_bind("tab: complete")  # linux and python3 on mac
     
    for mac
    
    • for Linux
    #!/usr/bin/env python
    # python startup file
    import sys
    import readline
    import rlcompleter
    import atexit
    import os
    # tab completion
    readline.parse_and_bind('tab: complete')
    # history file 
    histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
    try:
        readline.read_history_file(histfile)
    except IOError:
        pass
    atexit.register(readline.write_history_file, histfile)
    del os, histfile, readline, rlcompleter
     
    for Linux
    

    自己写的tab.py模块只能在当前目录下导入,如果想在系统的任何一个地方都使用,要把这个tab.py放到python全局环境变量目录里。
    一般都放在一个叫Python/2.7/site-packages目录下。
    这个目录在不同的OS里放的位置不一样,用print(sys.path)可以查看python环境变量列表。

    八、表达式if...else

    1. 用户登录验证
    • 判断用户名和密码
    user = "will"
    passwd = "wang1234"
    username = input("username:")
    password = input("password:")
     
    if user == username:
        print("Username is correct...")
        if passwd == password:
            print("Welcome back, %s" %username)
        else:
            print("Password is not invaild...")
    else:
        print("Guess it again, %s" %username)
    
    #优化v1
    user = "will"
    passwd = "wang1234"
    username = input("username:")
    password = input("password:")
     
    if user == username and passwd == password: # 用and同时判断username和password
        print("Welcome back, %s" %username)
    else:
        print("Invalid username or password...")
    
    2. 猜年龄
    age = 31
    guess_num = int(input("Please input the number you guess:"))
    
    if guess_num == age:
        print("Congratulations! You got it!")
    elif guess_num > age:
        print("Think it smaller.")
    else:
        print("Think it bigger.")
    

    九、循环

    1. for循环
    • 最简单的循环10次
    for i in range(10):
        print("loop:", i )
    
    • 年龄游戏
    age = 31
    for i in range(10):
        guess_num = int(input("Please input the number you guess:"))
        if guess_num == age:
            print("Congratulations! You got it!")
            break #停止往后继续走,跳出整个loop
        elif guess_num > age:
            print("Think it smaller.")
        else:
            print("Think it bigger.")
    
    • 年龄游戏(尝试3次)
    age = 31
    for i in range(10):
        if i < 3:
            guess_num = int(input("Please input the number you guess:"))
            if guess_num == age:
                print("Congratulations! You got it!")
                break #停止往后继续走,跳出整个loop
            elif guess_num > age:
                print("Think it smaller.")
            else:
                print("Think it bigger.")
        else:
            print("You have tried too many times, good bye.")
            break
    
    • 年龄游戏(每尝试3次,询问是否继续)
    age = 31
    counter = 0 #自己的计数器
    for i in range(10):
        if counter < 3:
            guess_num = int(input("Please input the number you guess:"))
            if guess_num == age:
                print("Congratulations! You got it!")
                break #停止往后继续走,跳出整个loop
            elif guess_num > age:
                print("Think it smaller.")
            else:
                print("Think it bigger.")
        else:
            continue_confirm = input("Do you want try it again? type y to continue : ")
            if continue_confirm == "y":
                counter = 0
                continue #跳出本次循环
            else:
                print("bye")
                break
        counter += 1
    
    2. while循环
    • 年龄游戏
    age = 31
    
    count = 0
    while True:
        guess_num = int(input('Please input your guees number:'))
        if guess_num == age:
            print('Yes, you got it!')
            break
        elif guess_num < age:
            print('Please think it bigger!')
        else:
            print('Please think it smaller!')
    
    • 年龄游戏(尝试3次)
    age = 31
    
    count = 0
    while count < 3:
        guess_num = int(input('Please input your guess number:'))
        if guess_num == age:
            print('Yes, you got it!')
            break
        elif guess_num < age:
            print('Please think it bigger')
        else:
            print('Please think it smaller!')
        count += 1
    else:
        print('You have trid too many times. Byebye')
    
    • 年龄游戏(每尝试3次,询问是否继续)
    age = 31
    
    count = 0
    while count < 3:
        guess_num = int(input('Please input your guess number:'))
        if guess_num == age:
            print('Yes, you got it!')
            break
        elif guess_num < age:
            print('Please think it bigger')
        else:
            print('Please think it smaller!')
        count += 1
        if count == 3:
            continue_confirm = input('Do you want keep tring?')
            if continue_confirm != 'n':         # !=是不等于
                count = 0
    

    十、作业

    作业一:博客

    作业二:编写登陆接口

    • 输入用户名密码
    • 认证成功后显示欢迎信息
    • 输错三次后锁定

    作业三:多级菜单

    • 三级菜单
    • 可依次选择进入各子菜单
    • 所需新知识点:列表、字典
    1. 流程图:www.processon.com
    2. Readme.md
    3. test.md

    相关文章

      网友评论

          本文标题:Day01 - Python基础1

          本文链接:https://www.haomeiwen.com/subject/dmznuttx.html