Python--基础1

import  random
 
'''
#secret = random.randint(1,10)
secret =  6
temp  = input('不妨猜一下我心里想的是几?:')
guess = int(temp)
 
a = 3
 
if guess == secret:
    print('哎呀猜对了')
    print('爱你')
       
while guess != secret and a > 0:
 
    if guess == secret:
        print(temp)
        print('哎呀猜对了')
        print('爱你')
    else:
        if guess > secret:
            print('大了呀')
        else:
            print('小了呀')
 
    a -= 1
    print('只剩下%d次了呀'%a)
    temp = input('哎呀,猜错了,再猜一次吧:')
    guess = int(temp)
 
print(',游戏结束')
 
不妨猜一下我心里想的是几?:4
小了呀
只剩下2次了呀
哎呀,猜错了,再猜一次吧:5
小了呀
只剩下1次了呀
哎呀,猜错了,再猜一次吧:6
,游戏结束
 
#enumerate(iterable)
#enumerate()方法生成由二元组构成的一个迭代对象,每个二元组是由可迭代的索引号及其对应的元素组成
str1 = 'FishC'
for each in enumerate(str1):
    print(each)
 
(0, 'F')
(1, 'i')
(2, 's')
(3, 'h')
(4, 'C')
 

#zip用于返回由各个可迭代参数共同组成的元祖
list1 = [1,2,3,4,5,6]
for each in zip(str1,list1):
    print(each)
 
'F', 1)
('i', 2)
('s', 3)
('h', 4)
('C', 5)
'''
#6.1函数的参数
def myFirstFunction(name):
    '''不开玩笑
        我是真的帅 '''
    print(name+'你好帅啊')
'''
>>> myFirstFunction('吴长青')
吴长青你好帅啊
myFirstFunction.__doc__
'不开玩笑\n        我是真的帅 '
'''
#收集参数
def test(*parames , extra):
    print('收集的参数是:',parames)
    print('位置参数是:',extra)
'''
>>> test(1,2,3,4,extra=4)
收集的参数是: (1, 2, 3, 4)
位置参数是: 4
'''
'''
#函数变量的作用域
#全局变量:整个代码段中都是可以访问,但不要试图在函数内修改全局变量,
#因为那样PYTHON会自动在函数内部新建一个名字一样的局部变量代替
def discounts(price,rate):
    final_price = price * rate
    #old_price  = 20
    global old_price                #global 能够在函数内修改全局变量
    old_price = 40
    print('在函数内修改全局变量0ld_price',old_price)
    return final_price
 
old_price = float(input('请输入原价:'))
rate  = float(input('折扣率:'))
new_price = discounts(old_price,rate)
print('全局变量old_price',old_price)
print('折扣后的价:',new_price)
 

#global 能够在函数内修改全局变量
请输入原价:100
折扣率:0.6
在函数内修改全局变量0ld_price 40
全局变量old_price 40
折扣后的价: 60.0
'''
#闭包 在一个函数内部f(y),对在外部作用域f(x)的变量进行引用,
#那么内部函数f(y)就被认为闭包,f(y)函数内部不能对外部变量修改,只能进行访问
def f(x):
    def f(y):
        nonlocal x
        x = 5
        print('x,y',x,y)
        return x * y
    return f
'''
>>> f(2)(3)
x,y 2 3
6
 
nonlocal :内部函数能够修改外部函数变量
>>> f(2)(3)
x,y 5 3
15
'''
'''
g = lambda x : 2 * x +1
 
#print(g(3))
#dict1= dict((1,2),(2,4)) 字典
#dict()函数可以是一个序列但不能太多()
 
dict1= dict(((1,2),(2,4)))
dict2 = dict(a=1,b=2)
dict2['c']=3
#print(dict2)
dict3 = {}
#dict3.fromkeys(keys,values)
#items() = keys() + values()
a =dict3.fromkeys((1,2,3),'lla')
b = a.items()
c = a.values()
d = a.get(1)  #获取键对应的值
print(b)
print(c)
print(d)
'''
#集合:集合里面的元素  唯一
list1 = [1,2,5,4,6,3,2,1]
list1 = sorted(list(set(list1)))
#print(list1)
for i in range(10):
    if i % 2 != 0:
        print(i)
        #continue
        break
    i  += 2
    print('i1',i)
 
'''
continue  终止本轮循环并开始下一轮循环
没有加continue i +=2 都执行了
i1 2
1
i1 3
i1 4
3
i1 5
i1 6
5
i1 7
i1 8
7
i1 9
i1 10
9
i1 11
 
加了continue  i +=2 只执行了偶数,将奇数进行循还后不进行 i += 2操作
i1 2
1
i1 4
3
i1 6
5
i1 8
7
i1 10
9
 
break   当条件满足时,终止循环
i1 2
1
'''

猜你喜欢

转载自www.cnblogs.com/eilinge/p/9239804.html