字典,集合,函数,global全局变量声明

1.if实现switch

#!/usr/bin/env python
#coding=utf-8
while 1:
    num1 = input("num1:")
    oper = raw_input("操作符:")
    num2 = input("num2:")

    if oper == "+":
        print num1 + num2
    elif oper == "-":
        print num1 - num2
    elif oper == "*":
        print num1 * num2
    elif oper == "/":
        if num2 == 0:
            print "Error:分母为0"
        else:
            print num1 / num2
    else:
        print "操作符错误"

2.字典实现switch语句

#!/usr/bin/env python
#coding=utf-8
from __future__ import division

num1 = input("num1:")
oper = raw_input("操作符:")
num2 = input("num2:")


def add(num1,num2):
    return num1 + num2


def sub(num1,num2):
    return num1 - num2


def muilt(num1,num2):
    return num1 * num2


def div(num1,num2):
    if num2 == 0:
        print "分母为0,参数错误"
    else:
        return num1 / num2


dict = {
    "+": add,
    "-": sub,
    "*": muilt,
    "/": div,
}

if oper in dict:
    print dict[oper](num1, num2)
else:
    print "error"

3.字典的遍历

favourite_places = {
    "fentiao":['Xi\'an','Hangzhou'],
    'laoli':['Xianyang','Hanzhong']
}

for name in favourite_places:     ##先遍历key --定义为name
    print '\n' + name.title() + "\'s favourite places are"
    for place in favourite_places[name]:   ##再遍历values 定义place
        print place

4.集合是不重复的数据类型

集合s={1,2,3,4,5,1,2,3}

In [1]: s = {1,2,3,4,5,1,2,3}

In [2]: print type(s)
<type 'set'>

In [3]: print s
set([1, 2, 3, 4, 5])
4.1集合的定义,同元组列表一样,集合元素的数据类型不同,但不能存在列表,字典

这里写图片描述

s= {1,’hello’,’1L’,’1+3j’} 合法的集合
s= {1,’hello’,’1L’,’1+3j’,(1,2,3)} 集合里边可以存在元组

In [9]: type(s)
Out[9]: set

In [10]: print s
set([1, ‘hello’, ‘1+3j’, ‘1L’, (1, 2, 3)])

定义一个空集合s = set()
In [17]: s1 = set()

In [18]: print type(s1)
<type 'set'>

In [19]: 
4.2集合的一些特性:集合是无序的数据类型,这样就不会有索引, 切片, 重复,连接这些特性,但支持成员操作符
s = {
  91,2,3,15,
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值