print(r'''\"To be, or not to be\": that is the question.\nWhether it\'s nobler in the mind to suffer.''')
print('special string: \', \", \\, \\\\, \\n, \\t')
\n表示换行
\t 表示一个制表符
\\表示 \ 字符本身
如果字符串既包含'又包含"怎么办?
这个时候,就需要对字符串中的某些特殊字符进行“转义”,Python字符串用\进行转义。
要表示字符串Bob said "I'm OK"
由于'和"会引起歧义,因此,我们在它前面插入一个\表示这是一个普通字符,不代表字符串的起始,因此,这个字符串又可以表示为
'Bob said \"I\'m OK\".'
注意:转义字符 \不计入字符串的内容中。
与运算
只有两个布尔值都为 True 时,计算结果才为 True。
True and True # ==> True
True and False # ==> False
False and True # ==> False
False and False # ==> False
或运算
只要有一个布尔值为 True,计算结果就是 True。
True or True # ==> True
True or False # ==> True
False or True # ==> True
False or False # ==> False
非运算
把True变为False,或者把False变为True:
not True # ==> False
not False # ==> True
地板除
10//3 # ==> 3
else if 可以用elif代替更简单方便。
写条件的时候要注意逻辑清晰。
打印代码需要缩进
if语句后必须要有“:”
s[0:4] s中的第一个字符到第五个字符,不包括第五个字符
s[2:6] s中的第三个字符到第七个字符,不包括第七个字符
字符串索引
s[i]
字符串切片
s[i]左闭右开
字符串索引 s[i]
字符串切片 s[i:j]左闭右开
字符串索引
s[i]
字符串切片
s[0:i]左闭右开
字符串索引
s[i]
字符串切片
s[i:j]左闭右开
字符串索引
s{i}
字符串切片
s{i:j} 左闭右开
s[i]左闭右开
从0开始切片,最后一个字符不取
字符串的索引
s[i]
字符串的切片
s[i:j]左闭右开
s = 'ABCDEFGHIJK'
abcd = s[0:4] # 取字符串s中的第一个字符到第五个字符,不包括第五个字符
print(abcd) # ==> ABCD
cdef = s[2:6] # 取字符串s中的第三个字符到第七个字符,不包括第七个字符
print(cdef) # ==> CDEF
字符串的索引
s[i]
字符串切片
s[i:j] 左闭右开
字符串索引
s[i]
字符串切片
s[i:j] 左闭右开
任务
编写一个函数,它接受关键字参数names,gender,age三个list,分别包含同学的名字、性别和年龄,请分别把每个同学的名字、性别和年龄打印出来。
参考答案:
def info(**kwargs):
names = kwargs['names']
gender_list = kwargs['gender']
age_list = kwargs['age']
index = 0
for name in names:
gender = gender_list[index]
age = age_list[index]
print('name: {}, gender: {}, age: {}'.format(name, gender, age))
index += 1
info(names = ['Alice', 'Bob', 'Candy'], gender = ['girl', 'boy', 'girl'], age = [16, 17, 15])
任务
请定义一个 greet() 函数,它包含一个默认参数,如果没有传入参数,打印 Hello, world.,如果传入参数,打印Hello, 传入的参数内容.
def greet(name='world'):
print ('Hello, ' + name + '.')
greet()
greet('Alice')
任务
已知两个集合s1、s2,请判断两个集合是否有重合,如果有,请把重合的元素打印出来。
s1 = set([1, 2, 3, 4, 5])
s2 = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
参考答案:
s1 = set([1, 2, 3, 4, 6, 8, 10])
s2 = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
flag = s1.isdisjoint(s2)
if not flag:
for item in s1:
if item not in s2:
continue
print(item)