2
2.字符串操作:
2.1.字符串:用单引号或者双引号引起来
print 'hello'
hello
2.2.字符串拼接:用+号将多个字符串拼接起来
print 'hello '+'world'
hello world
2.3.字符串转义:在Python中字符串使用单引号或双引号括起来,如果字符串内部出现了需要转义的字符(例如:"和'本身),只需要在字符前添加转义字符:\即可
常用转义字符:
>>> print 'My name\'s lilei'
My name's lilei
4.变量:变量值可以是字符串、数字、list、dict、tup
x = 'hello world'
print x
hello world
age = 20
print age
20
5.获取用户输入:raw_input()#python内置函数
#代码
x = raw_input('please input a string: ')
print 'hello '+x
#输入
world
输出 hello world
6.字符串格式化:
常用类型:
%s:字符串
%d:整型
%f:浮点型
%x:十六进制
%%:表示%本身
name = 'liuyang'
age = 26
#数字和字符串不能直接相加
#26为数字,不能与字符串相连,所以我们要将类型转换成字符串
print 'hello '+name+',and i am '+str(age)+' years old'
hello liuyang,and i am 26 years old
#字符串格式化%s 引入变量 后边%结尾意思是左边字符串结束了现在要代入变量)
print 'hello %s,and i am %s years old' %(name,age)
hello liuyang,and i am 26 years old
#用%s换成%d占位符,代表一个数字
>>>print 'hello %s,and i am %d years old' % (name,age)
hello liuyang,and i am 26 years old
7.数据类型
int:整型
str:字符串
float:浮点型
bool:布尔型
x = raw_input('print input a number: ')
y = raw_input('print input a number2: ')
False
10.2.逻辑运算:and or not
#A and B 就是A 和B都是TRUE的时候才是TRUE,其它情况都是false
#A or B 就是A 和B只要有一个是TRUE就是TRUE,条件至成立一个即为TRUE
#not A如果A是FALSE返回TRUE,如果A 是True返回FALSE
注:‘and’的优先级高于‘or’
10.3.if else判断:
if 条件判断(真/假):条件为真执行if后面语句
else:#条件为假执行else语句
条件为假的情况:
#空字符串
#空列表
#数字0
#空字典都是
#none
if '':
print '123'
else:
print '1231343'
1231343
#
if not 0:
print 'add'
else:
print 'dd'
add
#
list = []
>>>if list:
print 'list不为空为真'
else:
print 'aaa'
aaa
#
if dict:
print '123132'
else:
print 'af'
af
10.4.while循环:
#while 条件成立:
# 如果情况是TRUE,代码持续执行;不成立即为False
#while循环直到情况是false才会退出
#while True一直循环,break手动终止
break和continue都是针对for循环和while循环的
break:跳出循环
#continue:跳过本次循环
i = 0
while i<20:
print i
i = i + 1
#
>>>name = ''
# 定义name为空,while判断name非空是True,代码执行,
# name空为假,条件判断FALSE退出print name
while not name:
name=raw_input('input your name')
print 'hello '+name
10.5.for 循环序列:专门针对list,dict,以后用到比较多的流程控制
for name in ['2','3','4']:
print name