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 - 項目實戰(zhàn)
    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 - 四、五年開發(fā)經(jīng)驗
    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的選擇

語法區(qū)別
#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、配置環(huán)境變量
    【右鍵計算機】-->【屬性】-->【高級系統(tǒng)設置】-->【高級】-->【環(huán)境變量】-->【在第二個內(nèi)容框中找到 變量名為Path 的一行,雙擊】 --> 【Python安裝目錄追加到變值值中,用 ;分割】
    如:原來的值;C:\python27,切記前面有分號
  • Linux、Mac
無需安裝,原裝Python環(huán)境
ps:如果自帶2.6,請更新至2.7

四、Python入門

  • Hello World程序
print("Hello World!")
  • 在Linux下運行
print("Hello World!")
print("Hello Again.")
print("hello again \ntwice") #\n 為換行
#檢查是否有可執(zhí)行權限
ll hello.py (Mac: ls -slh)
#添加可執(zhí)行權限
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.注釋

單行注釋:# 被注釋內(nèi)容
多行注釋:""" 被注釋內(nèi)容 """ (三個引號,單引號雙引號均可。)

六、變量

1.聲明變量
name = "Will"

上述代碼聲明了一個變量,變量名為: name,變量name的值為:"Will"

2.變量定義的規(guī)則
  • 變量名只能是 字母、數(shù)字或下劃線的任意組合
  • 變量名的第一個字符不能是數(shù)字
  • 以下關鍵字不能聲明為變量名
    ['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"  #內(nèi)存中開辟新地址保存為“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 數(shù)字,%f = 小數(shù)、浮點
input 默認輸入的是字符串,數(shù)字需要用int()轉(zhuǎn)換

3. 常用模塊初識
  • getpass 輸入密碼
#Pycharm下不可用,僅限于Linux命令行或Windows的CMD
import getpass
username = input("username:")
password = getpass.getpass("password:")
print(username, password)
  • OS 調(diào)用系統(tǒng)命令
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import os
 
os.system("df -h")  #調(diào)用系統(tǒng)命令
import os

os.system("df")
os.mkdir("yourDir")
cmd_res = os.popen("df -h").read() #讀取內(nèi)存中的顯示值并打印
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模塊只能在當前目錄下導入,如果想在系統(tǒng)的任何一個地方都使用,要把這個tab.py放到python全局環(huán)境變量目錄里。
一般都放在一個叫Python/2.7/site-packages目錄下。
這個目錄在不同的OS里放的位置不一樣,用print(sys.path)可以查看python環(huán)境變量列表。

八、表達式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)
#優(yōu)化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.")

九、循環(huán)

1. for循環(huán)
  • 最簡單的循環(huán)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 #停止往后繼續(xù)走,跳出整個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 #停止往后繼續(xù)走,跳出整個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次,詢問是否繼續(xù))
age = 31
counter = 0 #自己的計數(shù)器
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 #停止往后繼續(xù)走,跳出整個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 #跳出本次循環(huán)
        else:
            print("bye")
            break
    counter += 1
2. while循環(huán)
  • 年齡游戲
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次,詢問是否繼續(xù))
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

十、作業(yè)

作業(yè)一:博客

作業(yè)二:編寫登陸接口

  • 輸入用戶名密碼
  • 認證成功后顯示歡迎信息
  • 輸錯三次后鎖定

作業(yè)三:多級菜單

  • 三級菜單
  • 可依次選擇進入各子菜單
  • 所需新知識點:列表、字典
  1. 流程圖:www.processon.com
  2. Readme.md
  3. test.md
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容