Python 一日精通Python编程》Jamie Chan"/>
《爱上Python 一日精通Python编程》Jamie Chan
目录
第1章 什么是Python?
Python——编程新手最好的选择
第2章 为Python做好准备
关于分号
第3章 变量和操作符的世界
3.1定义变量
3.2命名变量
3.3赋值符号
3.4基本操作符
3.5更多的分配操作符+= -= *=
第4章 Pyhon中的数据类型
4.1整型——同C
4.2浮点型——同C
4.3字符串
4.3.1内建的字符串函数
4.3.2使用%操作符格式化字符串
4.3.3使用format()方法格式化字符串
4.4Python中的类型转换
4.5列表
4.6元组
4.7字典
第5章 程序可交互
5.1&5.2 Input() Print()
5.3三引号
5.4转义字符
第6章 选择和判断
6.1条件语句
6.2if语句
6.3内联if
6.4for循环
6.4.1迭代
6.4.2在一段数字上循环
6.5while循环
6.6break中断
6.7continue
6.8Try,Except
《Python编程快速上手》(一)Python基础
《Python编程快速上手》(二)控制流
《Python编程快速上手》(三)函数
《Python编程快速上手》(四)列表
《Python编程快速上手》(五)字典和结构化数据
《Python编程快速上手》(六)字符串操作
第1章 什么是Python?
Python——编程新手最好的选择
第2章 为Python做好准备
#打印出单词"Hello World"
print("Hello World")
'''
这是注释
'''
print("Hello Python")"""
这也是注释
"""
关于分号
参考:.htm
在C、Java等语言的语法中规定,必须以分号作为语句结束的标识。Python也支持分号,同样用于一条语句的结束标识。但在Python中分号的作用已经不像C、Java中那么重要了,Python中的分号可以省略,主要通过换行来识别语句的结束。
例如,以下两行代码是等价的:
- print "hello world!"
- print "hello world!";
输出结果都为:
- hello world!
如果要在一行中书写多条句,就必须使用分号分隔每个语句,否则Python无法识别语句之间的间隔:
- # 使用分号分隔语句
- x=1; y=1 ; z=1
第2行代码有3条赋值语句,语句之间需要用分号隔开。如果不隔开语句,Python解释器将不能正确解释,提示语法错误:
- SyntaxError: invalid syntax
注意分号不是Python推荐使用的符号,Python倾向于使用换行符作为每条语句的分隔,简单直白是Python语法的特点。通常一行只写一条语句,这样便于阅读和理解程序。一行写多条语句的方式是不好的习惯。
第3章 变量和操作符的世界
3.1定义变量
userAge,userName = 16,'saber'
"""
相当于
userAge = 16
userName = 'saber'
"""
3.2命名变量
'''
与C一致:
1.字母数字下划线;
2.不能为关键字;
3.区分大小写;
命名规则举例:
1.驼峰式:ThisIsAVariableName
2.下划线式:this_is_a_variable_name
'''
3.3赋值符号
"""注意区分 x=y 与 y=x 的不同"""
x = 8
y = 2
x = y
print("x =",x)
print("y =",y)"""
运行结果:
x = 2
y = 2
"""
3.4基本操作符
+ - * / // % **
加法 减法 乘法 除法 整除 求余 指数
x = 5
y = 2
print("x+y =",x+y)
print("x-y =",x-y)
print("x*y =",x*y)
print("x/y =",x/y)
print("x//y =",x//y) #向下取整
print("x%y =",x%y)
print("x**y =",x**y)
"""
运行结果:
x = 2
y = 2
x+y = 7
x-y = 3
x*y = 10
x/y = 2.5
x//y = 2
x%y = 1
x**y = 25
"""
3.5更多的分配操作符
+= -= *=
第4章 Pyhon中的数据类型
注释不能写在代码行的后面,会报语法错误。可跨行但开始时应独立成行书写。这一点与C不同。以上写法中,只有第三种正确。
但如果采用#的注释方法,则可以在代码行后直接注释。但此时并不支持跨行注释。
4.1整型——同C
4.2浮点型——同C
4.3字符串
- [样例] userName = 'peter',userSpouseName = "Janet",usrAge = '30'
- "" 或 '' 都可以,但必须配对使用,不能一个'一个"地使用
- 可以使用 + 连接多个字符串 如: "I love"+" Saber"+" forever!" 等于 "I love Saber forever!"
print("I love"+" Saber"+" forever!")
"""[运行结果]:I love Saber forever!"""
4.3.1内建的字符串函数
'excalibur'.upper() #这是一条注释
"""将字符串中每一个字符都转化为大写"""
4.3.2使用%操作符格式化字符串
- [格式]" string to be formatted " %(values or variables to be inserted into string,separated by commas)
- 引号内编写要格式化的字符串,写出% 使用一对小括号,括号内写上要插入字符串的值或变量。
- 这对包含值的小括号事实上叫做——元组
- %d %f %s 宽度,保留小数位数等与C一致
brand = 'Apple'
exchangeRate = 1.235235344
message = 'The price of this %s laptop is %d USD and the exchange rate is %4.2f USD to 1 EUR' %(brand,1299,exchangeRate)
print(message)
"""
[运行结果]The price of this Apple laptop is 1299 USD and the exchange rate is 1.24 USD to 1 EUR
"""
4.3.3使用format()方法格式化字符串
- [格式]" string to be formatted ".format(values or variables to be inserted into string,separated by commas)
- 使用大括号,像这样:message = 'The price of this {0:s} laptop is {1:d} USD and the exchange rate is {2:4.2f} USD to 1 EUR'.format("Apple",1299,1.4354351)
- 大括号内首先写下要使用参数的位置(从0开始),后面加一个冒号(英文),冒号后面写下格式化符号(d——整型 f——浮点型 s——字符串),并且大括号内不能有任何空格。
- 如果不想要格式化字符串,可写为:message = 'The price of this {} laptop is {} USD and the exchange rate is {} USD to 1 EUR'.format("Apple",1299,1.4354351) 那么,解释器将会根据大括号内所提供的变量顺序进行替换。
message = 'The price of this {0:s} laptop is {1:d} USD and the exchange rate is {2:4.2f} USD to 1 EUR'.format("Apple",1299,1.4354351)
print(message)
message = 'The price of this {} laptop is {} USD and the exchange rate is {} USD to 1 EUR'.format("Apple",1299,1.4354351)
print(message)'''[运行结果]The price of this Apple laptop is 1299 USD and the exchange rate is 1.44 USD to 1 EURThe price of this Apple laptop is 1299 USD and the exchange rate is 1.4354351 USD to 1 EUR '''message1 = '{0} is easier than {1}'.format("Python",'Java')
message2 = '{1} is easier than {0}'.format("Python","Java")
message3 = '{:10.2f} and {:d}'.format(1.23454545,12)
message4 = '{}'.format(1.233455644)print(message1)
print(message2)
print(message3)
print(message4)
"""[运行结果]
Python is easier than Java
Java is easier than Python1.23 and 12
1.233455644
"""
4.4Python中的类型转换
"""Python中的三个内建函数 int() float() str() """print(int(2.34))
print(int("4654"))
"""错误句 int("856.42")#ValueError: invalid literal for int() with base 10: '856.42' """
print(int(8)+6)
print(float(6+7))
print(float("85438.443"))
print(float("5"))
print(str(6))
print(str(9.56)+"dfjgh")
print(str("534fdf"))"""[运行结果]
2
4654
14
13.0
85438.443
5.0
6
9.56dfjgh
534fdf
"""
4.5列表
""" a. 使用中括号[] """
""" b. 索引从0开始,最后一个元素为-1,倒数第二为-2 依此类推 """
""" c. 1:5叫做切片,它总是包括开始索引的元素,而不包括结尾索引的元素。 因此,1:5表示从索引1到索引4 =(5-1) """
""" d. 切片第三个数字叫做步长 [1:5:2]从索引位置1~4=5-1 中每隔一个数字的子列表,故步长为2 """
""" e. 若不指定则默认:第一个数字为0,第二个数字为列表长度 [:4]表示0~3 [2:]表示2~4 (总长为5,共有5个元素)"""
myList = [1,2,3,4,5.5,"Hello"]print(myList)
print(myList[2])
print(myList[-1])myList2 = myList[1:5]
print(myList2)myList[1] = 20
print(myList)myList.append("How are you")
print(myList)del myList[5]
print(myList)
4.6元组
"""值无法修改,初始化后值不会再变使用小括号() 其他类比列表"""
month = ("Jan","Feb","Mar")
4.7字典
""" 字典里的字是唯一的 使用大括号{} """
userNameAndAge = {"peter":34,"John":42,"Saber":16,"Archer":"Not Available"}
userNameAndAge = dict(peter=34,John=42,Saber=16,Archer="Not Available")
第5章 程序可交互
5.1&5.2 Input() Print()
myName = input("Please enter your name: ")
myAge = input("What about your age: ")
print("Hello World,my name is ",myName,"and I am",myAge,"years old.")
5.3三引号
print('''Hello World.
My name is John and
I am 20 years old.''')
5.4转义字符
print("a\tb\nc\\d\"e\'f")
第6章 选择和判断
6.1条件语句
== != < > <= >= and or not
等于 不等于 小于 大于 小于等于 大于等于 与 或 非
6.2if语句
user = input("Enter 1 or 2:")if user == "1":print("Hello World")print("How are you")
elif user == "2":print("Python Rocks")print("Ilove Python")
else:print("You didn't enter a valid number!")
6.3内联if
user = input("Enter 1 or 2:")
num=1 if user=="1" else 5
print(num)
print("This is task A " if user=="2" else "This is task B")
6.4for循环
6.4.1迭代
pets = ["cats","dogs","rabbits","hamsters"]
for mypets in pets:print(mypets)for index,mypets in enumerate(pets):print(index,mypets)message = "Hello"
for i in message:print(i)
6.4.2在一段数字上循环
range(start,end,step)
a.如不指定,start默认为0
b.如不指定,step默认为1,生成连续列表
c.end必须指定
- [例]range(5)生成[0,1,2,3,4] range(3,10)生成[3,4,5,6,7,8,9] range(4,10,2)生成[4,6,8]
for i in range(5):print(i)
6.5while循环
counter = 5
while counter>0:print("counter = ",counter)counter = counter - 1
6.6break中断
j = 0
for i in range(5):j=j+2print("i=",i,"j=",j)if(j==6):break
6.7continue
j = 0
for i in range(5):j=j+2print("i=",i,"j=",j)if(j==6):continueprint("if counter!=6,print counter=",i)
6.8Try,Except
try子句(可能出错的语句) except子句(错误发生,执行的语句)
def spam(divideBy):try:return 42/divideByexcept ZeroDivisionError:print('Error:Invalid argument')
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(3))
None的输出是因为print()函数的返回值为none
这本书讲到这里基本就结束了,所以我又去借了本《Python编程快速上手:让繁琐工作自动化》来看,具体的笔记也在此系列的后面博客中。
-
《Python编程快速上手》(一)Python基础
-
《Python编程快速上手》(二)控制流
-
《Python编程快速上手》(三)函数
-
《Python编程快速上手》(四)列表
-
《Python编程快速上手》(五)字典和结构化数据
-
《Python编程快速上手》(六)字符串操作
更多推荐
《爱上Python 一日精通Python编程》Jamie Chan
发布评论