python基本数据类型

一、输入与输出

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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值