my_string = “Let’s Learn Python!”
another_string = ‘It may seem difficult first, but you can do it!’
a_long_string = ‘’‘Yes, you can even master multi-line strings
that cover more than one line
with some practice’’’
也可以使用print来输出:
print(“Let’s print out a string!”)
String连接
String可以使用加号进行连接。
string_one = “I’m reading “
string_two = “a new great book!”
string_three = string_one + string_two
TypeError: Can’t convert ‘int’ object to str implicitly
String复制
String可以使用 * 来进行复制操作:
‘Alice’ * 5 ‘AliceAliceAliceAliceAlice’
或者直接使用print:
print(“Alice” * 5)
Math操作
我们看下python中的数学操作符:
操作符
含义
举例
**
指数操作
2 * 3 = 8*
%
余数
22 % 8 = 6
//
整数除法
22 // 8 = 2
/
除法
22 / 8 = 2.75
*****
乘法
3*3= 9
-
减法
5-2= 3
+
加法
2+2= 4
内置函数
我们前面已经学过了python中内置的函数print(),接下来我们再看其他的几个常用的内置函数:
Input() Function
input用来接收用户输入,所有的输入都是以string形式进行存储:
name = input(“Hi! What’s your name? “)
print(“Nice to meet you “ + name + “!”)
age = input(“How old are you “)
print(“So, you are already “ + str(age) + “ years old, “ + name + “!”)
运行结果如下:
Hi! What’s your name? “Jim”
Nice to meet you, Jim!
How old are you? 25
So, you are already 25 years old, Jim!
len() Function
len()用来表示字符串,列表,元组和字典的长度。
举个例子:
# testing len()
str1 = “Hope you are enjoying our tutorial!”
print(“The length of the string is :”, len(str1))
输出:
The length of the string is: 35
filter()
filter从可遍历的对象,比如列表,元组和字典中过滤对应的元素:
ages = [5, 12, 17, 18, 24, 32]
def myFunc(x):
if x < 18:
return False
else:
return True
adults = filter(myFunc, ages)
for x in adults:
print(x)
函数Function
python中,函数可以看做是用来执行特定功能的一段代码。
我们使用def来定义函数:
def add_numbers(x, y, z):
a= x + y
b= x + z
c= y + z
print(a, b, c)
add_numbers(1, 2, 3)
注意,函数的内容要以空格或者tab来进行分隔。
传递参数
函数可以传递参数,并可以通过通过命名参数赋值来传递参数:
# Define function with parameters
def product_info(productname, dollars):
print("productname: " + productname)
print("Price " + str(dollars))
# Call function with parameters assigned as above
product_info("White T-shirt", 15)
# Call function with keyword arguments
product_info(productname="jeans", dollars=45)
#Change the “year” to 2020:
new_dict= {
“brand”: “Honda”,
“model”: “Civic”,
“year”: 1995
}
new_dict[“year”] = 2020
遍历字典
看下怎么遍历字典:
#print all key names in the dictionary
for x in new_dict:
print(x)
#print all values in the dictionary
for x in new_dict:
print(new_dict[x])
#loop through both keys and values
for x, y in my_dict.items(): print(x, y)
if语句
和其他的语言一样,python也支持基本的逻辑判断语句:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to a <= b
Greater than: a > b
Greater than or equal to: a >= b
看下在python中if语句是怎么使用的:
if 5 > 1:
print(“That’s True!”)
if语句还可以嵌套:
x = 35
if x > 20:
print(“Above twenty,”)
if x > 30:
print(“and also above 30!”)
elif:
a = 45
b = 45
if b > a:
print(“b is greater than a”)
elif a == b:
print(“a and b are equal”)
if else:
if age < 4:
ticket_price = 0
elif age < 18:
ticket_price = 10
else: ticket_price = 15
if not:
new_list = [1, 2, 3, 4]
x = 10
if x not in new_list:
print(“’x’ isn’t on the list, so this is True!”)
Pass:
a = 33
b = 200
if b > a:
pass
Python循环
python支持两种类型的循环,for和while
for循环
for x in “apple”:
print(x)
for可以遍历list, tuple,dictionary,string等等。
while循环
#print as long as x is less than 8
i =1
while i< 8:
print(x)
i += 1
break loop
i =1
while i < 8:
print(i)
if i == 4:
break
i += 1
class car(object):
“””docstring”””
def __init__(self, color, doors, tires):
“””Constructor”””
self.color = color
self.doors = doors
self.tires = tires
def brake(self):
“””
Stop the car
“””
return “Braking”
def drive(self):
“””
Drive the car
“””
return “I’m driving!”
创建子类
每一个class都可以子类化
class Car(Vehicle):
“””
The Car class
“””
def brake(self):
“””
Override brake method
“””
return “The car class is breaking slowly!”
if __name__ == “__main__”:
car = Car(“yellow”, 2, 4, “car”)
car.brake()
‘The car class is breaking slowly!’
car.drive()
“I’m driving a yellow car!”
异常
python有内置的异常处理机制,用来处理程序中的异常信息。
内置异常类型
AttributeError — 属性引用和赋值异常
IOError — IO异常
ImportError — import异常
IndexError — index超出范围
KeyError — 字典中的key不存在
KeyboardInterrupt — Control-C 或者 Delete时,报的异常
NameError — 找不到 local 或者 global 的name
OSError — 系统相关的错误
SyntaxError — 解释器异常
TypeError — 类型操作错误
ValueError — 内置操作参数类型正确,但是value不对。
ZeroDivisionError — 除0错误
异常处理
使用try,catch来处理异常:
my_dict = {“a”:1, “b”:2, “c”:3}
try:
value = my_dict[“d”]
except KeyError:
print(“That key does not exist!”)
处理多个异常:
my_dict = {“a”:1, “b”:2, “c”:3}
try:
value = my_dict[“d”]
except IndexError:
print(“This index does not exist!”)
except KeyError:
print(“This key is not in the dictionary!”)
except:
print(“Some other problem happened!”)