python 2

1. 格式化输出

%s 可以代替str

%d 可以代替int

%f  可以代替浮点数( float )

格式:

Name = input('你的名字:')
Age = int(input('你的年龄:'))
Job = input('你的工作:')
hobby = input('你的爱好:')
Score = float(input('你的成绩:'))
msg = '''
------------ info of %s -----------
Name  : %s
Age   : %02d
job   : %s
Hobbie: %s
Score : %.1f
------------- end -----------------
''' % (Name, Name, Age, Job, hobby, Score)
print(msg)

字典:

 1 dic = {
 2     'name': '老男孩',
 3     'age': 58,
 4     'job': 'boss',
 5     'hobby': 'money',
 6 }
 7 msg = '''
 8 ------------ info of %(name)s -----------
 9 Name  : %(name)s
10 Age   : %(age)d
11 job   : %(job)s
12 Hobbie: %(hobby)s
13 ------------- end -----------------
14 ''' % dic
15 print(msg)

2. while else

如果循环被break打断,不执行else

count = 0
while count < 10:
    print(count)
    count += 1
    if count == 5: break
else:
    print('循环正常结束')
print('---------over---------')

3. 运算符

<> : 不等于
!= : 不等于
** : 乘方

布尔值和int可以相互转换

 1 print(bool(-1))  
 2 print(bool(5))
 3 print(bool(1))
 4 print(bool(0))
 5 print(int(True))
 6 print(int(False))
 7 
 8 True
 9 True
10 True
11 False
12 1
13 0

先算not 再算and 最后算or

print(1 and 2) 为 2
print(1 or 2)为 1
print(1 > 2 or 5 and 7 > 9 or 8 and 4 < 5) 为 True

4. 编码

gbk 可以与 Unicode转换

utf-8可以与 Unicode 转换

gbk 不可以直接与 utf-8 转换

一个字节(bytes)为8位(bit)

 5. for in, range.

L = ['Bart', 'Lisa', 'Adam']
for i in L:
    print('Hello, %s!' % i)
---------------
Hello, Bart! 
Hello, Lisa! 
Hello, Adam! 
sum = 0
for x in range(101):
    sum = sum + x
print(sum)

----------
5050
原文地址:https://www.cnblogs.com/leonraw/p/8962799.html