python系列2之数据类型
目录
- Python数据类型
- python的运算符
- Python的循环与判断语句
- python练习
- Python作业
一. Python的数据类型
1. 整型(int)
<1>. 赋值
1 num1 = 123 # 变量名 = 数字 2 num2 = 456 3 num3 = int(123) # 另外一种赋值的方法 4 print(num1) 5 print(num2)
6 print(num3)
<2>. int类的额外功能
def bit_length(self): # real signature unknown; restored from __doc__
#--------------这个功能主要是计算出int类型对应的二进制位的位数--------------------------------------- """ int.bit_length() -> int Number of bits necessary to represent self in binary. >>> bin(37) '0b100101' >>> (37).bit_length() 6 """ return 0
例子:
num = 128 # 128的二进制10000000,它占了一个字节,八位 print(num.bit_length()) 显示: 8
<3>. int的赋值
每一个赋值int类都要重新开辟一段地址空间用来存储,而不会改变原来地址空间的值。
num1 = 123 num2 = num1 num1 = 456 print(num1) print(num2) 显示: 456 123
原理:
第一步赋值:开辟了一个空间存入123 ,变量为num1。
第二步赋值:先指向num1,然后通过地址指向了123。
第三部赋值:重新开辟一个地址空间用来存入456,num2的指向不变。
def clear(self): # real signature unknown; restored from __doc__ #------------------清空字典-------------------------------------- """ D.clear() -> None. Remove all items from D. """ pass def copy(self): # real signature unknown; restored from __doc__ #----------------------复制字典给一个变量----------------------------- """ D.copy() -> a shallow copy of D """ pass @staticmethod # known case def fromkeys(*args, **kwargs): # real signature unknown """ Returns a new dict with keys from iterable and values equal to value. """ pass def get(self, k, d=None): # real signature unknown; restored from __doc__ #---------------------得到某个键对应的值------------------------------------ """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ pass def items(self): # real signature unknown; restored from __doc__ #--------------------------得到字典的键值对------------------------------------------ """ D.items() -> a set-like object providing a view on D's items """ pass def keys(self): # real signature unknown; restored from __doc__ #--------------------------得到字典的键----------------------------------------- """ D.keys() -> a set-like object providing a view on D's keys """ pass def pop(self, k, d=None): # real signature unknown; restored from __doc__ #---------------------删除某个键值对----------------------------------------- """ D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised """ pass def popitem(self): # real signature unknown; restored from __doc__ #----------------随机删除一个键值对------------------------------------------- """ D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. """ pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ #------------------和get方法类似, 如果键不存在于字典中,将会添加键并将值设为默认值-------------- """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ pass def update(self, E=None, **F): # known special case of dict.update #----------------------- 把一个字典添加到另外一个字典中-------------------------------------- """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] """ pass def values(self): # real signature unknown; restored from __doc__ #-----------------------------得到字典的值----------------------------------------------- """ D.values() -> an object providing a view on D's values """ passView Code
二. Python的运算符
1. 运算符
# 运算符主要有+ - * / ** % // # ** 是幂运算 # % 取模 # // 是整除,不留小数 a = 8 b = 16 print('a + b=',a + b) print('a - b=',a - b) print('a * b=',a * b) print('a / b=',a / b) print('a // b=',a // b) print('a % b=',a % b) print('a ** 2=',a ** 2) 显示结果: a + b= 24 a - b= -8 a * b= 128 a / b= 0.5 a // b= 0 a % b= 8
2. 比较运算符
# 比较运算符有: > < >= <= == != # == 代表恒等于,一个等号代表赋值 # != 代表不等于 a = 8 b = 16 print('a > b ?', a > b) print('a < b ?', a < b) print('a >= b ?', a >= b) print('a <= b ?', a <= b) print('a == b ?', a == b) print('a != b ?', a != b) 显示: a > b ? False a < b ? True a >= b ? False a <= b ? True a == b ? False a != b ? True
3. 逻辑运算符
# 逻辑运算值有: and or not # and 代表 与 # or 代表或 # not 代表非 a = 8 b = 16 c = 5 print('c<a<b', c<a<b) print('a > c and a > b', a > c and a > b) print('a > c and a < b', a > c or a < b) print('not a>c ', not a>c) 显示: c<a<b True a > c and a > b False a > c and a < b Tr
三. Python的判断循环语句
循环和判断语句最重要的是要学习他的结构,结构记住了就是往里面套条件就是了,下面先说一下Python的特点
- 缩进 在很多语言里面,每一个结构都是有头有尾的,不是小括号就是大括号,因此,很多语言通过其自身的结构就会知道程序到哪里结束,从哪里开始,但是Python不一样,Python本身并没有一个表示结束的标志(有人会觉得这样会使程序简单,但是有人会觉得这样会使程序变得麻烦),不管怎样,那Python是通过什么来标志一个程序的结束的呢?那就是缩进,因此缩进对于Python来讲还是蛮重要的。尤其对这些判断循环语句。
1. while循环语句
结构: while condition: statement statemnet if........... 这个while循环只会执行statement,因为后面的if和statement的缩进不一样,因此当跳出while循环的时候才会执行后面的if语句
事例:执行了三次beautiful,执行了一次ugly num = 3 while num < 6: print('you are beautiful.', num) num += 1 print('you are ugly.') 显示: you are beautiful. 3 you are beautiful. 4 you are beautiful. 5 you are ugly.
2. for循环语句
结构: for var in condition: statement statement if ............ for后面的跟的是变量,in后面跟的是条件,当执行完for循环之后,才会执行后面的if语句
事例:显示了三次beautiful,一次ugly,因为他们的缩进不同 i = 1 for i in range(3): print('you are beautiful.', i) print('you are ugly.') 显示: you are beautiful. 0 you are beautiful. 1 you are beautiful. 2 you are ugly.
3. if判断语句
结构: if condition: statement statement else: statement1 statement2 statement3........... 当满足条件,则执行statement,否则执行statement1和2,执行完了之后执行statement3
事例: a = 16 b = 89 if a > b: print('a>b') else: print('a<b') print('you are right.') 显示: a<b you are right.
四. Python的练习题
1. 使用while循环输入1 2 3 4 5 6 8 9
num = 1 while num < 10: if num == 7: num += 1 continue print(num, end = ' ') num += 1
2. 求1-100内的所有奇数之和
# -*- coding:GBK -*- # zhou # 2017/6/13 num = 1 sum = 0 while num < 100: if num % 2 == 1: sum += num num += 1 print('所有奇数之和为: ',sum)
3. 输出1-100内的所有奇数
# -*- coding:GBK -*- # zhou # 2017/6/13 num = 1 sum = 0 while num <= 100: if num % 2 == 1: print(num,end = ' ') num += 1
4. 输出1-100内的所有偶数
# -*- coding:GBK -*- # zhou # 2017/6/13 num = 1 sum = 0 while num <= 100: if num % 2 == 0: sum += num num += 1 print('所有偶数之和为: ',sum)
5. 求1-2+3-4+5........99的所有数之和
# -*- coding:GBK -*- # zhou # 2017/6/13 num = 1 sum = 0 while num < 100: if num % 2 == 1: sum -= num else: sum += num num += 1 print(sum)
6. 用户登录程序(三次机会)
# -*- coding:GBK -*- # zhou # 2017/6/13 name = 'hu' password = 'hu' num = 1 while num <= 3: user_name = input('Name: ') user_password = input('Password: ') if user_name == name and user_password == password: print('you are ok. ') break num += 1 else: print('you are only three chance, now quit.')
五. Python的作业题
1. 有如下值集合{11,22,33,44,55,66,77,88,99.......},将所有大于66的值保存至字典的第一个key中,将小于66 的值保存至第二个key的值中,即:{‘k1’:大于66的所有值,‘k2’:小于66的所有值}
# -*- coding:GBK -*- # zhou # 2017/6/13 dict = {'k1':[],'k2':[]} list = [11,22,33,44,55,66,77,88,99,100] for i in list: if i <= 66: dict['k1'].append(i) else: dict['k2'].append(i) print(dict)
2. 查找列表中的元素,移动空格,并查找以a或者A开头 并且以c结尾的所有元素
li = ['alec','Aric','Alex','Tony','rain']
tu = ('alec','Aric','Alex','Tony','rain')
dic = {'k1':'alex', 'k2':'Aric', 'k3':'Alex', 'k4':'Tony'}
# -*- coding:GBK -*- # zhou # 2017/6/13 li = ['alec','arix','Alex','Tony','rain'] tu = ('alec','aric','Alex','Tony','rain') dic = {'k1':'alex', 'k2':'aric', 'k3':'Alex', 'k4':'Tony'} print('对于列表li:') for i in li: if i.endswith('c') and (i.startswith('a') or i.startswith('A')): print(i) print('对于元组tu:') for i in tu: if i.endswith('c') and (i.startswith('a') or i.startswith('A')) : print(i) print('对于字典dic:') for i in dic: if dic[i].endswith('c') and (dic[i].startswith('a') or dic[i].startswith('A')): print(dic[i])
3. 输出商品列表,用户输入序号,显示用户选中的商品
商品 li = ['手机','电脑','鼠标垫', '游艇']
# -*- coding:GBK -*- # zhou # 2017/6/13 li = ['手机','电脑','鼠标垫', '游艇'] # 打印商品信息 print('shop'.center(50,'*')) for shop in enumerate(li, 1): print(shop) print('end'.center(50,'*')) # 进入循环输出信息 while True: user = input('>>>[退出:q] ') if user == 'q': print('quit....') break else: user = int(user) if user > 0 and user <= len(li): print(li[user - 1]) else: print('invalid iniput.Please input again...')
4. 购物车
- 要求用户输入自己的资产
- 显示商品的列表,让用户根据序号选择商品,加入购物车
- 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功
- 附加:可充值,某商品移除购物车
# -*- coding:GBK -*- # zhou # 2017/6/13 name = 'hu' password = 'hu' num = 1 while num <= 3: user_name = input('Name: ') user_password = input('Password: ') if user_name == name and user_password == password: print('you are ok. ') flag = True break num += 1 else: print('you are only three chance, now quit.') shop = { '手机': 1000, '电脑': 8000, '笔记本': 50, '自行车': 300, } shop_car = [] list = [] if flag: salary = input('Salary: ') if salary.isdigit(): salary = int(salary) while True: print('shop'.center(50, '*')) for i in enumerate(shop, 1): print(i) list.append(i) print('end'.center(50, '*')) user_input_shop = input('input shop num:[quit: q]>>:') if user_input_shop.isdigit(): user_input_shop = int(user_input_shop) if user_input_shop > 0 and user_input_shop <= len(shop): if salary >= shop[list[user_input_shop - 1][1]]: print(list[user_input_shop - 1]) salary -= shop[list[user_input_shop - 1][1]] shop_car.append(list[user_input_shop - 1][1]) else: print('余额不足.') else: print('invalid input.Input again.') elif user_input_shop == 'q': print('您购买了一下商品:') print(shop_car) print('您的余额为:', salary) break else: print('invalid input.Input again.') else: print('invalid.')
第二个简单版本
# -*- coding:GBK -*- # zhou # 2017/6/13 ''' 1. 输入总资产 2. 显示商品 3. 输入你要购买的商品 4. 加入购物车 5. 结算 ''' i1 = input('请输入总资产:') salary = int(i1) car_good = [] goods = [ {'name':'电脑','price':1999}, {'name':'鼠标','price':10}, {'name':'游艇','price':20}, {'name':'手机','price':998} ] for i in goods: print(i['name'], i['price']) while True: i2 = input('请输入你想要的商品: ') if i2.lower() == 'y': break else: for i in goods: if i2 == i['name']: car_good.append(i) print(i) #结算 price = 0 print(car_good) for i in car_good: price += i['price'] if price > salary: print('您买不起.....') else: print('您购买了一下商品:') for i in car_good: print(i['name'],i['price']) print('您的余额为:', salary-price)
5. 三级联动
# -*- coding:GBK -*- # zhou # 2017/6/13 dict = { '河南':{ '洛阳':'龙门', '郑州':'高铁', '驻马店':'美丽', }, '江西':{ '南昌':'八一起义', '婺源':'最美乡村', '九江':'庐山' } } sheng = [] shi = [] xian = [] for i in dict: sheng.append(i) print(sheng) flag = True while flag: for i in enumerate(dict,1): print(i) sheng.append(i) user_input = input('input your num: ') if user_input.isdigit(): user_input = int(user_input) if user_input > 0 and user_input <= len(dict): for i in enumerate(dict[sheng[user_input - 1]], 1): print(i) shi.append(i) user_input_2 = input('input your num: ') if user_input_2.isdigit(): user_input_2 = int(user_input_2) if user_input_2 > 0 and user_input_2 <= len(shi): for i in dict[sheng[user_input - 1]][shi[user_input_2 - 1][1]]: print(i, end = '') print() else: print('invalid input') else: print('invalid input.') else: print('invalid input. Input again.')
- Python基础系列----语法、数据类型、变量、编码
- 自动化运维Python系列(二)之基础数据类型
- Spark机器学习MLlib系列1(for python)--数据类型,向量,分布式矩阵,API
- python系列笔记一:基本数据类型
- 【Python系列】python关键字、符号、数据类型等分类
- Python系列之 - python数据类型(一)
- Python从零开始系列连载(3)——Python的基本数据类型(上)
- python学习系列(二)python基本数据类型
- 2Python全栈之路系列之MysQl基本数据类型
- Python系列之 - python数据类型
- python系列二:python3基本数据类型
- python基础系列(一)之基本数据类型
- python入门系列3―——数据类型
- Python系列之 - python数据类型(二)
- Python 循序渐进教程系列 之基础02 基础数据类型
- Python系列之 - python数据类型
- [Python]Python/PHP如何查询sql server中NTEXT类型数据
- MySQL查询优化系列讲座之数据类型与效率
- [Python]Python/PHP如何查询sql server中NTEXT类型数据
- [Python]Python/PHP如何查询sql server中NTEXT类型数据