python基础(四)

1、嵌套

1.1 字典列表

alien_0={'color':'green','points':5}

alien_1={'color':'yellow','points':10}

alien_2={'color':'red','points':15}

aliens=[alien_0,alien_1,alien_2]    //列表元素成员时字典

for alien in aliens:

    print(alien)

-->{'color': 'green', 'points': 5}

    {'color': 'yellow', 'points': 10}

    {'color': 'red', 'points': 15}

1.2 在字典中存储列表

pizza={

    'crust':'thick',

    'toppings':['mushrooms','extra  cheese'],    //该值为列表

}

print("You ordered a "+pizza['crust']+"-crust pizza"+"with the following toppings:")

for topping in pizza['toppings']:    //for循环键值列表

    print("\t"+topping)

-->You ordered a thick-crust pizzawith the following toppings:

        mushrooms

        extra  cheese

注意:列表和字典的嵌套层级不应太多。如果嵌套层级比前面的示例多得多,很可能有更简单的解决问题的方案。

1.3 在字典中存储字典

users={

    'aeinstein':{    //用户信息也是字典

    'first':'albert',

    'last':'einstein',

    'location':'princeton'

},

'mcurie':{    //同理

    'first':'marie',

    'last':'curie',

    'location':'paris'

},

}

for username,user_info in users.items():    //该user字典包含两个键

    print("\nUsername: "+username)        //键

    full_name=user_info['first']+" "+user_info['last']    //值

    location=user_info['location']    //值

    print("\tFull_name: "+full_name.title())

    print("location: "+location.title())

-->Username: aeinstein

        Full_name: Albert Einstein

        location: Princeton

    Username: mcurie

        Full_name: Marie Curie

        location: Paris

2、用户输入和while循环

首先设置Sublime实现终端交互,参考博客:https://blog.csdn.net/weixin_36892106/article/details/80079074

2.1 使用input()函数

name=input("Please enter your name: ")

print("Hello "+name+"!")

-->Please enter your name: Eric    //从终端键入,然后按Enter键

    Hello Eric!

2.2 使用int()来获取数值输入

>>> age=input("How old are you? ")

How old are you? 21

>>> age=int(age)

>>> age>=18

True

注意:将数值用于计算和比较前,务必将其转换为数值表示

2.3 求模运算

>>> 7%3

1

3、使用while循环来处理列表和字典

3.1 在列表之间移动元素

unconfirmed_uesrs=['alice','brian','candace']

confirmed_users=[]

while unconfirmed_uesrs:    //列表不空时循环

current_users=unconfirmed_uesrs.pop()

    print("Verifing user:"+current_users.title())

    confirmed_users.append(current_users)

print("\nThe following users have been confirmed:")

for c in confirmed_users:

    print(c.title())

-->Verifing user:Candace

    Verifing user:Brian

    Verifing user:Alice

    The following users have been confirmed:

        Candace

        Brian

        Alice

3.2 删除包含特定值的所有列表元素

pets=['dog','cat','dog','goldfish','cat','rabbit','cat']

print(pets)

while 'cat' in pets:    //条件循环

    pets.remove('cat')

print(pets)

-->['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']

    ['dog', 'dog', 'goldfish', 'rabbit']

4、函数

4.1 定义函数

def greet_user():    //    使用def定义函数,定义以冒号结尾

    print("Hello!")

greet_user()

-->Hello!

4.2 向函数传递信息

def greet_user(username):    //函数定义中包含形参username

    print("Hello, "+username.title()+"!")

greet_user('mike')     //函数调用包含实参'mike'

-->Hello, Mike!

你可能感兴趣的:(python基础(四))