(1)變量與賦值
name = "wanghuafeng"
age = 29
print(name, age)
a和b交換值
a = 3
b = 5
tmp = a
a = b
b = tmp
print(a, b)
變量要求:
a.顯式
b.nums_of_words = 19
c.NumsOfWords = 19 #駝峰寫法
d."-"在任何語言中都是減號,保留符號
e.數字不能開頭,可以在中間和結尾
f.特殊字符不能有,!@¥%……&*()
g.不能有空格、只能是下划線、數字和字母,關鍵字不能作為變量
(2)字符編碼
ASCII碼表(2**8=128個字符)
unicode:統一碼、萬國碼
每一個字符最少用2個字節(16位)來存儲,即2**16=65536
utf-8:是針對unicode的可變長度元編碼。
它可以使用1~4個字節表示一個符號,根據不同的符號而變化字節長度。
(3)Pycharm修改文件模板
依次打開:File—>Settings—>Editor—>File and Code Templates—>Python Scripts
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: WangHuafeng
(4)多行打印
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: wanghuafeng
name = input("input your name:")
age = int(input("input your age:"))
job = input("input your job:")
#print("name is:", name + "\nage is:", age + "\njob is:", job)
msg = """
Information of user %s:
-------------------------
Name: %s
Age : %d
Job : %s
---------End-------------
""" % (name, name, age, job)
print(msg)
%d:整數
%f:浮點數
%s:字符串
代碼中的注釋
#注釋一行最多不超過80個字符
"""
多行注釋,
不用每行注釋
"""
'''
也可以采用這個注釋
'''
(5)隱藏輸入密碼
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: WangHuafeng
import getpass
username = input("請輸入用戶名:")
password = input("請輸入密碼:")
print(username, password)
注意:Pycharm上輸入密碼時沒有隱藏,Linux上可以隱藏。
(6)導入模塊
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: WangHuafeng
import os
cmd_java = os.system("java -version")
print(cmd_java)
注意:導入模塊或自己的python文件時不能加.py即:import Hello
(7)Linux上增加tab補全
新建文件tab.py
# 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
保存到/usr/lib/python2.7/dist-packages目錄中
python命令行中輸入:import tab
即可tab查看命令提示。
(8)if判斷
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: wanghuafeng
user = 'wanghuafeng'
passwd = '123456'
username = input("input your name:")
password = input("input your password:")
if user == username and passwd == password:
print("Welcome to login...")
else:
print("用戶名或密碼錯誤...")
(9)猜年齡
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: wanghuafeng
age = 22
counter = 0
for i in range(10):
print("counter is :", counter)
if counter < 3:
guess_num = int(input("input your guess num: "))
if guess_num == age:
print("Congratulations! You got it.")
break
elif guess_num > age:
print("Think smaller!")
else:
print("Think Big...")
else:
continue_confirm = input("Do you want to continue because you are stupid:")
if continue_confirm == 'y':
counter = 0
continue
else:
print("Bye.")
break
counter += 1