Python超入门(6)

编程入门 行业动态 更新时间:2024-10-28 20:31:42

Python超<a href=https://www.elefans.com/category/jswz/34/1770026.html style=入门(6)"/>

Python超入门(6)

# 26.函数和参数
# 注意:有参函数和无参函数的名字要不同
def user():  # 无参函数print("hello world!")def user1(my_id):  # 有参函数print(my_id)def user2(first_name, last_name):  # 有参函数print(f'My name is {first_name} {last_name}')print("start...")
user()  # 调用无参函数
user1("123456")
user2("John", "Smith")
print("end...")
'''
start...
hello world!
123456
My name is John Smith
end...
'''

# 27.关键字参数
# 更适合使用数值计算的函数,可使用关键字参数来提高可读性。
user2(last_name="liming", first_name="qiuxie")
'''
My name is qiuxie liming
'''def cal(one, two, three):print(one * (two + three))cal(one=12, two=10, three=30)  # 480

# 28.返回函数
# 指明函数返回的值,需要print输出返回值。
def power(number):  # 一种计算方式number^numberreturn number ** numberprint(power(4))  # 4^4 = 256

# 29.创建可重用函数
# 构建一些常用函数,在需要引用时直接调用,避免重复代码。
def emoji_converter(message):words = message.split()emoji = {"happy": '=^_^=',"sad": '>﹏<',"like": '(❤ ω ❤)'}output = ""for word in words:output += emoji.get(word, word) + " "return outputmessage = input("> ")
print(emoji_converter(message))'''
> I am happy ,but my dag is sad ,because it lose that it like foods.
I am =^_^= ,but my dag is >﹏< ,because it lose that it (❤ ω ❤) foods. 
'''

# 30.例外(一种错误处理方式)
# 可用于提示用户输入错误的原因
# 需要测试的代码
try:age = int(input("> "))income = 10000EXP = age - 18risk = (income * age) / EXPprint(age)# 可能的错误类型,及对应错误类型的处理方式。
except ZeroDivisionError:print("EXP cannot be 0")
except ValueError:print("Invalid value")'''
> 0
0
> w
Invalid value
'''

更多推荐

Python超入门(6)

本文发布于:2023-12-03 13:57:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1656116.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:入门   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!