一、输入与输出
1、常用格式
%s:字符串 %d:整型数(python2中还有长整型)
%.3d:3位整型数,不够位数用0代替
%f:浮点数 %.2f%%:显示2位小数
%%:转译% ctrl + / :批量注释
2、数据类型
int:
整型float:
浮点型 complex:
复数型 bool:
布尔型str:
字符串
a = 1
print(a,type(a))
1 <class 'int'>
b = 1.3e3
print(b,type(b))
1300.0 <class 'float'>
c = True
print(c,type(c))
True <class 'bool'>
d = 'hello'
print(d,type(d))
hello <class 'str'>
注意:强制转换
int() :
整型float() :
浮点型bool() :
布尔型 ##除0之外,全是true
3.python2.7与3.6差异
python3
1.没有长整型
2.input():只识别字符串
5/2=2.5
4.打印时,只识别print(“hello”)
python2.7
1.input():只识别整型数
2.raw_input():转换为字符串
In [1]: a = input("Name:")
Name:123
In [2]: a
Out[2]: 123
In [3]: a = input("Name:")
Name:westos 输入字符串报错
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-3-e3ecbe0eebd3> in <module>()
----> 1 a = input("Name:")
<string> in <module>()
NameError: name 'westos' is not defined
强制转换
In [4]: a = raw_input("Name:")
Name:westos
In [5]: a
Out[5]: 'westos'
5/2=2需要加载division函数
In [11]: 5/2
Out[11]: 2
In [17]: from __future__ import division future左右两边分别有两个下划线
In [18]: 5/2
Out[18]: 2.5
识别print ‘hello’ 和print(‘hello’)
In [19]: print 'hello'
hello
In [20]: print('hello')
hello
In [21]: from __future__ import print_function
In [22]: print 'hello'
File "<ipython-input-22-bfbe230352b8>", line 1
print 'hello'
^
SyntaxError: invalid syntax
In [23]: print('hello')
hello
二、if语句
1、示例:
按照学生的平均分测评等级练习
name = input("name:")
score1 = int(input(" language:"))
score2 = int(input(" mathematics:"))
score3 = int(input(" english:"))
ave_score = (score1+score2+score3)/3
if 90 < ave_score <= 100:
leven = 'A'
elif ave_score >=80:
leven = 'B'
elif ave_score >=70:
leven = 'C'
elif ave_score >=60:
leven = 'D'
else:
leven = 'E'
print("%s的总成绩为%d,综合测评等级为%s" %(name,ave_score,leven))
2、三元运算符
In [1]: a=70
In [2]: b=50
In [3]: print(a if a>b else b)
70
In [4]: a=20
In [5]: b=30
In [6]: print(a if a>b else b)
30
3.要求输入大于0的数,求阶乘;输入0,打印0;输入小于0的数,求平方
num = int(input("请输入数字:"))
res = 1
if num >0:
for i in range(1,num+1):
res *= i
elif num == 0:
res = 0
else:
res = num**2
print(res)
请输入数字:-3
9
请输入数字:0
0
三、循环语句
import os #### 调用命令执行模块
while True:
cmd = input("cmd>>")
if cmd =="":
continue
elif cmd == 'quit':
break
else:
os.system(cmd)