= 182.求模运算符( % ),将两个数相除并返回余数,可用来判断奇偶。number = input("Enter a number, and I'll tell you if it's even or odd: ")number = int(number)if number % 2 =_运用while循环语句与d">
当前位置:   article > 正文

Python笔记(六)——用户输入和 while 循环和函数_运用while循环语句与def函数定义的方法,让用户随机输入一个列表

运用while循环语句与def函数定义的方法,让用户随机输入一个列表

1.input接收存入变量的是字符串类型,不能与整数18比较,所以用int()转换为整形。

  1. age = input("How old are you? ")
  2. age = int(age)
  3. age >= 18

2.求模运算符( % ),将两个数相除并返回余数,可用来判断奇偶。

  1. number = input("Enter a number, and I'll tell you if it's even or odd: ")
  2. number = int(number)
  3. if number % 2 == 0:
  4. print("\nThe number " + str(number) + " is even.")
  5. else:
  6. print("\nThe number " + str(number) + " is odd.")

3.while的用法

  1. active = True
  2. while active:
  3. message = input(prompt)
  4. if message == 'quit':
  5. active = False
  6. else:
  7. print(message)

也是用break跳出循环


4.函数定义def,在 greet_user('jesse') 中,将实参'jesse' 传递给了函数 greet_user() ,这个值被存储在形参 username 中。

  1. def greet_user(username): # 定义以冒号结尾
  2. """函数注释,描述了函数是做什么的。文档字符串用三引号括起"""
  3. print("Hello, " + username.title() + "!")
  4. greet_user('jesse')

5.函数定义中可能包含多个形参,因此函数调用中也可能包含多个实参。向函数传递实参的方式很多,可使用位置实参,这要求实参的顺序与形参的顺序相同;也可使用关键字实参,其中每个实参都由变量名和值组成;还可使用列表和字典。两种传参方式可以混合使用。

  1. # 位置实参
  2. def describe_pet(animal_type, pet_name):
  3. """显示宠物的信息"""
  4. print("\nI have a " + animal_type + ".")
  5. print("My " + animal_type + "'s name is " + pet_name.title() + ".")
  6. describe_pet('hamster', 'harry') # 与形参位置要对应
  7. describe_pet('dog', 'willie') # 重复调用
  8. # 关键字实参 不用考虑对应
  9. describe_pet(animal_type='hamster', pet_name='harry')

6.给形参指定默认值(有默认值未传入实参按照默认值,传入实参后覆盖默认值)

  1. def describe_pet(pet_name, animal_type='dog'):
  2. """显示宠物的信息"""
  3. print("\nI have a " + animal_type + ".")
  4. print("My " + animal_type + "'s name is " + pet_name.title() + ".")
  5. describe_pet(pet_name='willie')
  6. describe_pet(pet_name='harry', animal_type='hamster')

  

7.函数返回值

  1. def get_formatted_name(first_name, last_name):
  2. """返回整洁的姓名"""
  3. full_name = first_name + ' ' + last_name
  4. return full_name.title()
  5. musician = get_formatted_name('jimi', 'hendrix')
  6. print(musician)

  结果:Jimi Hendrix

8.返回字典

  1. def build_person(first_name, last_name, age=''):
  2. """返回一个字典,其中包含有关一个人的信息"""
  3. person = {'first': first_name, 'last': last_name}
  4. if age:
  5. person['age'] = age #更新字典的用法,记住
  6. return person
  7. musician = build_person('jimi', 'hendrix', age=27)
  8. print(musician)

9.向函数传递列表

  1. def greet_users(names):
  2. """向列表中的每位用户都发出简单的问候"""
  3. for name in names:
  4. msg = "Hello, " + name.title() + "!"
  5. print(msg)
  6. usernames = ['hannah', 'ty', 'margot']
  7. greet_users(usernames)

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/490796
推荐阅读
相关标签
  

闽ICP备14008679号