# 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^number
- return number ** number
-
-
- print(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 output
-
-
- message = 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 = 10000
- EXP = age - 18
-
- risk = (income * age) / EXP
- print(age)
-
- # 可能的错误类型,及对应错误类型的处理方式。
- except ZeroDivisionError:
- print("EXP cannot be 0")
- except ValueError:
- print("Invalid value")
-
- '''
- > 0
- 0
- > w
- Invalid value
- '''