呵护朋友 发表于 2023-7-18 15:38:04

Python基础(2)

if 语句

给出一个简单的示例
cars = ["audi", "bmw", "subaru", "toyota"]

for car in cars:
    if car == "bmw":
      print(car.upper())
    else:
      print(car.title())每条if语句的核心都是一个值为True 或 False的表达式,这种表达式称为条件测试。
检查多个条件:可以使用 andor   ;检查特定值:in   或者    notin
if 语句结构有三种:

[*]简单的 if 语句
[*]if - else 语句
[*]if - elif - else 语句
while处理列表和字典

列表之间移动元素:
F_users = ["alice", "brain", "candace"]
C_users = []

while F_users:
    curr = F_users.pop()
    C_users.append(curr)删除为特定值的所有列表元素:
pets = ["dog", "cat", "dog", "goldfish", "cat", "rabbit"]

while "cat" in pets:
    pets.remove("cat")使用用户输入来填充字典:
responses = {}
polling_active = True
while polling_active:
    name = input("\nWhat is your name?")
    response = input("Wich mountain would you like to climb someday?")
    responses = responseinput()

input()工作原理:让程序暂停运行,等待用户输入一些文本。
message = input("Tell me something, and I will repeat it back to you: ")
print(message)使用函数input()时,Python将用户输入解读为字符串。但是我们想要使用整形数据的话,可以使用int()来获取数值输入
height = input("How tall are you,in inches?")
height = int(height)Python函数

1、定义函数
#定义函数
def greet_user():
    print("Hello!")
#调用函数
greet_user()2、向函数传递信息
def greet_user(username):
    print(f"Hello,{username.title()}!")
   
greet_user("jesse")        #调用函数关键字实参

关键字实参是传递给函数的名称值对。关键字实参无需考虑函数调用中的实参顺序,还清楚指出函数调用中各个值的用途。
关键字实参的顺序无关紧要,python知道各个值该赋给哪个形参。
def describe_pet(animal_type, pet_name):
    print(f"\nI have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name.title()}")

#二者是等价的
describle_pet(animal_type = "hamster", pet_name = "harry")
describle_pet(pet_name = "harry", animal_type = "hamster")实参占位

在函数定义中,新增可选形参age,并将其默认值设置为特殊值 None(表示变量没有值)。None视为占位值。
def build_person(first_name, last_name, age = None):
    person = {"first":first_name, "last":last_name}
    if age:
      person["age"] = age
    return person

musician = build_person("jimi", "hendrix", age = 27)禁止函数修改列表

我们可以将列表传递给函数后,可以对其进行修改。是因为不同的变量指向的是同一个内存空间的列表。如果禁止函数修改列表,而是仅仅向函数中传递列表的副本。可以如下可做:
function_name(list_name[:])        #切片表示法`[:]` 创建列表的副本。传递任意数量的实参

由于预先不知道函数接受多少个实参,可在形参前加*,接收多个实参。
def make_pizza(*toppings):
    print(toppings)
   
make_pizza("pepperoni")
make_pizza("mushrooms", "green peppers", "extra cheese")形参名 *toppings 中的星号让Python创建一个名为 toppings 的空元组,并将收到的所有值都封装到这个元组中。
使用任意数量的关键字实参

有时候,需要接受任意数量的实参,但预先不知道传递给函数的会是什么样的信息。在这种情况下,可将函数编写成能够接受任意数量的键值对,即调用语句提供了多少就接受多少。
def build_profile(first, last, **user_info):
    user_info["first_name"] = first
    user_info["last_name"] = last
    return user_info

user_profile = build_profile("albert","einstein",
                            location = "princeton",
                            field = "physics")形参 **user_info中的两个星号让Python创建一个名叫 user_info 的空字典,并将收到的所有名称值对都放在这个字典中。
注意:
给形参指定默认值时,等号两边不要有空格: def function_name(parameter_0, parameter_1="default value")
就这么多,日后有遇到的,可进行补充。

来源:https://www.cnblogs.com/BrokenSnow/p/17563089.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: Python基础(2)