2.python基础知识(分支循环、列表、元组、字典、集合、函数)(一)

笔记说明:这是我的学习笔记,这部分内容整理自小甲鱼的python零基础入门,但不限于小甲鱼。

目录

基础知识

import os
os.getcwd()
os.chdir('D:\codes\python')

print('i love python \n' *3)

"""---小甲鱼说这是一个游戏,哈哈哈哈哈---"""
temp = input("猜下小好这个月能胖几斤:")
guess = int(temp)
if guess == 0:
    print("ni you du ba ,zhe ye neng caidui")
else:
    print("you're wrong~~")
print("game over~~")

# "烦人的反斜杠"

分支循环

temp = input("猜下小好这个月能胖几斤:")
guess = int(temp)
r=1
while guess != 0 and r!=3:
    temp = input("猜错了,再猜猜小好这个月增肥几斤")
    guess = int(temp)
    r+=1
    if guess==0:
        print("唉呀妈呀,猜对了")
    else:
        if guess>0:
            print("大了大了")
        else:
            print("小了小了") 
    if r==3:
        print("times is out")

##条件分支循环
score = int(input("请输入一个分数:"))
if 90<=score<=100:
    print('A')
elif 80<=score<90:
    print('B')
elif 60<=score<80:
    print('C')
else:
    print('D')

##三元操作符
small= int(input('随便写一个数字:'))
x=7;y=77
small = x if x<y else y    

## for,range,break,continue
for i in range(1,9,2):
    print(i)

bingo="小好是帅哥"
answer = input('请输入小好最想听的一句话:')
while True:
    if answer == bingo:
        break
    answer = input('抱歉回答错误,请重新输入(答对方可结束游戏):')
print("谢谢你眼神真好!有眼光")
    
for i in range(10):
    if i % 2 !=0:
        print(i)
        continue
    i += 2
    print(i)

列表、元组、字典、集合、函数

列表、元组

###列表、元组、字符串
list1=[1,2,3,4,'小好是帅哥',[0,1,2]]
list1.extend([7,8])
list1
list1.insert(0,0)
list1[5]
list1.remove(0)
list1[5][0]

list2=[1,2,3,4,5,6,7,8,9]

tuple1=(1,2,3,4,5,6,7,8,9)  #### 元组的核心是逗号,

##xu序列
a = list()
b=list("single monk")
b
c=list((1,2,3,4,5,6,7,8,9)) ##同理还有tuple()和str()
c
len([1,2,3,4,5,6,7])
max([1,9,7,55,77,-5])
max("xiaohao is handsome")
tuple3=1,2,3,4,5
sum(tuple3)

sorted(c)
c.sort(reverse=True)

函数

def myfirstfunction():
    print("this is my first function")
    print("i am so so so so so excited...")
    print("here, i will appreciate my country")
myfirstfunction()

for i in range(7):
    myfirstfunction()
    
def mysecondfunction(name):
    print(name +" " +"is handsome.")
mysecondfunction("小好")

def add(num1,num2):
    sum=num1+num2
    print("和为:")
    print(sum)
add(6,7)
    
def add(num1,num2):
    sum=num1+num2
    return sum
add(7,8)

###so what's difference between print and return?

#函数文档
def exchangerate(dollar):
    """ 美元 -> 软妹币
    汇率我不敢瞎写啊,就按现在的实际汇率6.8
    """
    return dollar * 6.8
exchangerate(77)
exchangerate.__doc__
help(exchangerate)
  
  
###关键字参数
def saysomething(name,words):
    print(name+words)
saysomething(name="小好",words="是帅哥")

###默认参数
def saysomething1(name="小好",words="是个帅哥"):
    print(name +"->" +words)
saysomething1()
saysomething1(name="吴彦祖")

###收集参数,使用*打包
def test(*params,extra):
    print("收集参数是:",params)  
    print("位置参数是:",extra)
test(1,2,4,5,6,7,8,extra=9)

#将其他变量传入收集参数的时候需要在变量前添加星号解包
def test(*params):
    print("有%d个参数"% len(params))
    print("第二个参数是:",params[1])
a=[1,2,3,4,5,6,7,8,9]
test(*a)

#函数变量的作用域
###避雷!!!!!一定要避开在局部变量中修改全局变量,渣渣我是会混乱的。
def discounts(price,rate):
    final_price = price*rate
    old_price=50
    print('在局部变量里面修改old_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)

##内嵌函数和闭包
def funx(x):
    def funy(y):
        return x*y
    return funy
i=funx(8)
i(5)        
funx(8)(5)

funy(5)

def funX():
    x=[5]
    def funY():
        x[0] *= x[0]
        return x[0]
    return funY
funX()()

def funX():
    x = 5
    def funY():
        nonlocal x
        x *= x 
        return x
    return funY()
funX()()

##lambda表达式
g = lambda x , y :x*y
g(6,7)

##;两个实用的内置函数
help(filter)

temp = filter(None,[1,0,False,True])
list(temp)

### filter 过滤器。有两个参数,第一个参数可以是函数,则第二个参数参数中的每个元素作
#为第一个参数的函数的参数进行计算,返回计算结果为true的。若第一个参数为none,
##则直接将第二个参数中true的值筛选出来。
def odd(x):
    return x % 2
temp= filter(odd,range(10))
list(temp)

list(filter(lambda x :x%2,range(10)))

###  map 映射函数
list(map(lambda x:x**2,range(10)))

#写一个求阶乘的函数
def recursion(n):
    result = n
    for i in range(1,n):
        result *= i
    return result

number=int(input('请输入一个数字:'))
result=recursion(number)
print('%d 的阶乘是:%d' % (number,result))

def factorial(n):
    if n == 1:
        return 1 
    else:
        return n *factorial(n-1)
number=int(input('请输入一个数字:'))
result=recursion(number)
print('%d 的阶乘是:%d' % (number,result))

#斐波那契数列
def fab(n):
    a1=1
    a2=1
    if n<=0:
        print('输入有误')
        return -1
    if n==1 or n==2:
        result=1
        return result
    while n>=3:
        a3=a1+a2
        a1=a2
        a2=a3
        n -= 1
    print('总共有%d对兔崽子出生' %a3)
    return a3
fab(10)

#递归的斐波那契数列
def fab2(n):
    if n<=0:
        print('输入有误')
        return 1
    if n==1 or n==2:
        return 1
    else:
       result= fab(n-1)+fab(n-2)
       return result
fab2(10)   
    
#迭代实现序列的打印
fab_list=[]
def fab3(n):
    a1=1
    a2=1
    a3=1
    if n<=0:
        print('输入有误')
        return -1
    else:
        for i in range(n):
            if i==0 or i==1:
                fab_list.append(1)
            else:
                 a3=a1+a2
                 fab_list.append(a3)
                 a1=a2
                 a2=a3
                 i -= 1
        print('总共有%d对兔崽子出生' %a3)
        print("数列是:", fab_list )
fab3(5)

#递归实现序列的打印
fab_list=[]
def fab4(n):
    for i in range(n):
        if i==0 or i==1:
            fab_list.append(1)
        else:
            fab_list.append(fab_list[i-1]+fab_list[i-2])
    print('总共有%d对兔崽子出生' % fab_list[n-1])
    print("数列是:", fab_list )
fab4(3)

fab_list=[]
def fab5(n):
    if n <=0:
        print("输入有误")
        return -1
    else:
        for i in range(n):
            if i==0 or i==1:
                fab_list.append(1)
            else:
                fab_list.append(fab_list[i-1]+fab_list[i-2])
        print('总共有%d对兔崽子出生' % fab_list[n-1])
        print("数列是:", fab_list )
fab5(10)

#汉诺塔
def hanoi(n,x,y,z):
    if n == 1:
        print(x,'-->',z)
    else:
        hanoi(n-1,x,z,y)
        print(x,'-->',z)
        hanoi(n-1,y,x,z)
hanoi(5,'X','Y','Z')

3 and 4

help(list)
dict1={"lining":"everything is possible","nike":"just do it"}
print("nike's slogan is:",dict1['nike'])

字典与集合

##字典与集合
empty={}
dict1=dict(f=70,I=105,S=115)
dict1['x']=80
dict1

##各种内置方法
help(dict.fromkeys)
dir(dict)

dict2={}
dict2.fromkeys((1,2,3),('one','two','three'))
dict1={}
dict1=dict1.fromkeys(range(10),'赞')
dict1
dict1.keys()
dict1.values()
dict1.items()

dict1.get(6)
dict1.clear()

b=dict2.copy()
b
help

a={1:'one',2:'two',3:'three',4:'four'}
a.setdefault(3)

#集合
num1={1,2,3,7,7,2}
num1        ####唯一性,且无序,不可以去索引
#创建集合
set1={"小甲鱼","小好","胡萝卜汁","葡萄柚汁"}
set2=set(["小甲鱼","小好","胡萝卜汁","葡萄柚汁"])
set1==set2

a=list((1,2))

##访问集合
set1={1,2,3,4,3,0}
for each in set1:
    print(each,end='')

set1.add(6)
set1

set2=frozenset({1,2,3,4,5,6,7,7,7,7,7})
set2
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值