Day01 - Python基础1

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容