Python学习7-8

"""

第7章  用户输入和while循环
    input()
    while
    break
    cotinue
    xx.pop()
    xx.remove
    
第8章  函数
    def
    *
    **
    return
    import

注:此py不可直接运行
"""



name = input("Please input your name:")
print("Hello "+ name + " !")            # 函数input 接受一个参数 输入内容存储在message中 同matlab




prompt = "Input testing"
prompt += "\n What is your name ?"      # 显示字符太长时可另声明一个,如prompt,再用input
name2 = input(prompt)
print('Hello ',name2,' !')              # 逗号,加号,皆可  双引号,单引号,皆可




number = input("Input a number please: ")
number = int(number)                    # input 输入为字符型

if number % 2 == 0:
    print("Even number")
else:
    print("Odd number")

    


i = 1
while i <= 5:
    print(i)
    i += 1




promt = "Tell me,and i'll repeat it back to you."
promt += "\nEnter 'quit' to end the program."

message = ""
while message != 'quit':
    message = input(promt)

    if message != 'quit':       # 没有if条件直接打印的话最后退出有qiut
        print(message)




active = True                   # 注意 True False 首字母大写
while active:
    message = input(promt)

    if message == 'quit':
        active = False

    else:
        print(message)




while True:
    city = input("Enter a number :")

    if city == '0':
        break

    elif city <= '5':
        continue
    
    else:
        print(city)



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

unconfirmed = ['alic','brain','canfd']
confirmed = []

while unconfirmed:
    current = unconfirmed.pop()             # 从列表末尾删除一个元素

    print("Verifing user : " + current.title())
    confirmed.append(current)

print(unconfirmed)                          # 由于前面使用 pop 删除了 -> []
print("The following users have been confirmed :")
for confirmed in confirmed:
    print(confirmed)


print("\n\tModule testing 9")
pets = ['dog','cat','cat','rabbit','fish']
while 'cat' in pets:                        # 使用while循环 删除所有 cat
    pets.remove('cat')                      # remove 删除   p.111
    
print(pets)



###### 使用用户输入来填充字典 ######

responses = {}

polling_active = True       # 以下为标准注释

while polling_active:
    # 提示输入被调查者的名字和回答
    name = input("\nWhat's your name ? ")
    response = input("\nWhich mountain would you like to climb someday? ")

    # 将回答存储在字典中
    responses[name] = response

    # 看看是否还有人参与调查
    repeat = input("Would you like to let another person respond ? (yes/no)")
    if repeat == 'no':
        polling_active = False

# 调查结果,显示结果
print("\n-- Poll Results --")
for name,response in responses.items():
    print(name + " like " + response)


###### 函 数 ######

#1.形参指定默认值时等号两端不要留空格 同样 函数调用时也不要
"""举例如下:

def pet(animal_type,pet_name,color='black'):    # 设置color默认值

pet(animal_type='dog',pet_name='wilii')

"""

#2.阐述函数功能应在函数定义后 采用 文档字符串格式
"""举例如下:

def get(first_name,last_name):
    """返回整洁的姓名"""               # 文档字符串格式对函数用途进行说明
    full_name = first_name + ' ' + last_name
    
"""



def greet_user():                   # 使用关键字 def 定义一个函数 注意有冒号:
    print("hello")

greet_user()

def greet_user(username):           # ussername 形参 huxin 实参

    print(" hello " + username.title())

greet_user('huxin')

def pet(animal_type,pet_name,color='black'):    # 设置一个color默认值
    """显示宠物信息"""                        
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
    print("Color is " + color)
pet('hamster','harry')                          # 实参个数不必与形参对应
pet(animal_type='dog',pet_name='wilii')         # 关键字实参 p.118

def get(first_name,last_name):
    """返回整洁的姓名"""                        # 文档字符串格式对函数用途进行说明
    full_name = first_name + ' ' + last_name
    return full_name.title()                    # 返回值

musician = get('jimi','hendrix')
print('\n',musician)




def get_name(first_name,last_name,middle_name=' '):
    """Return clean name"""
    if middle_name:                             # 并非所有人都有中间名 所以提供默认空 再判断
        full_name = first_name + middle_name + last_name
    else:
        full_name = first_name + last_name

    return full_name.title()

musician2 = get_name('jack','tom')
print(musician2)
musician2 = get_name('kao','cag','helen')
print(musician2)




###### 返回字典 ######

def build_person(first_name,last_name,age=''):      # 赋初值等号两端不要留空格
    """Return a dictionary,including personal information"""
    person = {'first':first_name,'last':last_name}
    if age:
        person['age'] = age
    return person

per = build_person('jal','hansix',18)
print(per)              # -> {'first': 'jal', 'last': 'hansix', 'age': 18}
                        # 如果没有 18 ->{'first': 'jal', 'last': 'hansix'}



                    


def greet2(names):      # 以下为标准注释
    for name in names:
        msg = "hello " + name.title() + "!"
        print(msg)

username = ['aaxi','sdf','diidl']
greet2(username)

# 首先创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['ipone case','robot pendant','dodecahedron']
completed_models = []

# 模拟打印每个设计,直到没有未打印的设计为止
# 打印每个设计后,都将其移到列表completed_models中
while unprinted_designs:
    current_design = unprinted_designs.pop()

    #模拟根据设计制作3D打印模型的过程
    print("Printing model :" + current_design)
    completed_models.append(current_design)

# 显示打印好的所有模型
print("\nThe following models have been printed:")
for completed_model in completed_models:
    print(completed_model)




###### 禁止函数修改列表 [:] 创建副本######
 
def print_models(unprinted_designs,completed_models):
    """
    模拟打印每个设计,直到没有未打印的设计为止
    打印每个设计后,都将其移到列表completed_models中
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()

        # 模拟根据设计制作3D打印模型的过程
        print("Printing model: " + current_design)
        completed_models.append(current_design)

def show_completed_models(completed_models):
    """显示打印好的所有模型"""
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs = ['iphone case ','robot pendant','dodecachedron']
completed_models = []

# 切片表示法[:]创建列表副本 传递为副本则unprinted_designs经过pop不会改变
# 若传递unprinted_designs,则经过pop后为空
print_models(unprinted_designs[:],completed_models) 
show_completed_models(completed_models)
print(unprinted_designs)



###### 转递任意数量实参 * 使用 ######

def make_pizza(*toppings):              # *让python创建一个名为toppings的空元祖
    """打印顾客点的所有配料"""
    print(toppings)

make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')


def make_pizz(*topping):
    print("\nMaking a pizza with the following topping : ")
    for top in topping:
        print(top)

make_pizz('pepperoni')
make_pizz('mushrooms','green peppers','extra cheese')

def pizza(size,*toppings):
    print("\nMaking a " + str(size) +
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

pizza(16,'pepperoni')
pizza(12,'mushrooms','green peppers')



###### 使用任意数量的关键字实参 ** 使用 ######

def build_profile(first,last,**user_info):          # ** 创建一个空字典 p.131
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key,value in user_info.items():
        profile[key] = value
    return profile

user_profile = build_profile('albert','einstein',
                             location='princeton',  # 函数调用等号两端不要有空格
                             field='physics')       # 传递两个值,以及两个键-值对
print(user_profile)




###### 将函数存储在模块中 ######

"""
导入整个模块
创建一个pizza.py文件并输入以下内容
"""
def make_pizza2(size,*toppings):
    print("Making a " + str(size) +
          "-inch pizza with the following toppong:")
    for topping in toppings:
        print("- " + topping)
"""
创建一个making.py文件
输入以下即可调用pizza.py中的 make_pizza2 函数
"""
# 1. 导入pizza整个模块
import pizza

pizza.make_pizza2(16,'pepperoni')       # 模块名 + 函数名


# 2. 给模块指定别名
import pizza

pizza.make_pizza2(16,'pepperoni')


# 3. 导入特定的函数
from pizza import make_pizza2  

make_pizza2(16,'pepperoni')             # 函数名


# 4. as 给函数指定别名
from pizza import make_pizza2 as mp

mp(16,'pepperoni)


# 5. 导入模块中所有函数
from pizza import *

make_pizza2(16,'pepperoni')             # 函数名



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值