学习Python需要注意的地方
Hello World
使用 print() 方法打印 helloworld
name = "jenkin li"
print("My name is ", name)
Python 2.x 中的编码问题
因为 Python 2.x 使用的是 ASCII 编码,默认不支持中文,必须在文件头声明文件使用的是什么编码
# -- coding:utf-8 --
Python 的注释
分为单行注释和多行注释
# 单行注释
'''
多行注释
'''
Python 文本格式化输出
1. 使用 %s, %d 等占位符
name = input("name: ")age = input("age: ")job = input("job: ")salary = input("salary: ")info = '''---------- info of %s ---------Name: %sAge: %sjob: %ssalary: %s''' % (name, name, age, job, salary)print(info)
PS: 如果使用 %d ,则必须使用 int() 转换为数值类型,input 的类型默认为字符串。与 int() 相反,str() 将数值类型转换为字符串。
Python 中无法将数值和字符串通过 + 号相连接,必须先通过转换
2. 使用参数格式化输出
info = '''---------- info of {_name} ---------Name: {_name}Age: {_age}job: {_job}salary: {_salary}'''.format(_name = name, _age = age, _job = job, _salary = salary)
3. 使用下标格式化输出
info = '''---------- info of {0} ---------Name: {0}Age: {1}job: {2}salary: {3}'''.format(name, age, job, salary)
使用 getpass 模块隐藏用户输入的密码
import getpassusername = input("username: ")password = getpass.getpass("password: ")print(username)print(password)
需要注意的是,上面那段代码无法在 PyCharm 等 IDE 中运行,必须再终端中运行
立即学习“Python免费学习笔记(深入)”;
使用 type() 函数获取变量类型
type(variable)
while … else 语句
count = 0while count < 3: guess_age = int(input("guess age: ")) if guess_age == age_of_oldboy: print("yes, you got it") break elif guess_age > age_of_oldboy: print("Ooops, think smaller...") else: print("Ooops, think bigger! ") count += 1else : print("Ooops, you dont got it")
else 语句块必须再 while 正常退出时才执行,在 while 语句被 break 的情况下,else 语句块不会被执行
for … else … 语句
for i in range(10): print("i value = ", i) # break 后不会运行 else 块 else: print("success ended")
与 while … else … 类似,当 for 语句正常结束时才会运行,break 后不会运行