本文摘自php中文网,作者零下一度,侵删。
Hello World
使用 print() 方法打印 HelloWorld
name = "Jenkin Li"
1 | print ( "My name is " , name)
|
Python 2.x 中的编码问题
因为 Python 2.x 使用的是 ASCII 编码,默认不支持中文,必须在文件头声明文件使用的是什么编码
# -- coding:utf-8 --
Python 的注释
分为单行注释和多行注释
# 单行注释
'''
多行注释
'''
Python 文本格式化输出
1. 使用 %s, %d 等占位符
1 2 3 4 5 6 7 8 9 10 11 12 13 | name = input( "name: " )
age = input( "age: " )
job = input( "job: " )
salary = input( "salary: " )
info = '' '
---------- info of %s ---------
Name: %s
Age: %s
job: %s
salary: %s
'' ' % (name, name, age, job, salary)
print (info)
|
PS: 如果使用 %d ,则必须使用 int() 转换为数值类型,input 的类型默认为字符串。与 int() 相反,str() 将数值类型转换为字符串。
Python 中无法将数值和字符串通过 + 号相连接,必须先通过转换
2. 使用参数格式化输出
1 2 3 4 5 6 7 8 9 10 | info = '' '
---------- info of {_name} ---------
Name: {_name}
Age: {_age}
job: {_job}
salary: {_salary}
'' '.format(_name = name,
_age = age,
_job = job,
_salary = salary)
|
3. 使用下标格式化输出
1 2 3 4 5 6 7 | info = '' '
---------- info of {0} ---------
Name: {0}
Age: {1}
job: {2}
salary: {3}
'' '.format(name, age, job, salary)
|
使用 getpass 模块隐藏用户输入的密码
1 2 3 4 5 | import getpass
username = input( "username: " )
password = getpass.getpass( "password: " )
print (username)
print (password)
|
需要注意的是,上面那段代码无法在 PyCharm 等 IDE 中运行,必须再终端中运行
使用 type() 函数获取变量类型
while … else 语句
1 2 3 4 5 6 7 8 9 10 11 12 13 | count = 0
while 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 += 1
else :
print ( "Ooops, you dont got it" )
|
else 语句块必须再 while 正常退出时才执行,在 while 语句被 break 的情况下,else 语句块不会被执行
for … else … 语句
1 2 3 4 5 | for i in range(10):
print ( "i value = " , i)
# break 后不会运行 else 块
else :
print ( "success ended" )
|
与 while … else … 类似,当 for 语句正常结束时才会运行,break 后不会运行
以上就是学习Python需要注意的地方的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python和go语言有区别吗
Python 实现在excel末尾增加新行
使用 if x is not none 还是if not x is none
Python数据可视化的四种方法介绍(附示例)
Python如何合并两个列表?
anaconda是什么?
Python如何批量提取win10锁屏壁纸
Python实现的求解最大公约数算法示例
Python能做什么工作吗
Python如何编写公众号
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » 学习Python需要注意的地方