python u7 笔记

In [1]:

# 大多数程序旨在解决最终用户的问题,为此通常需要从用户那里获取新信息。

# 假设有人要判断自己是否到投票年龄,要编写程序,就需要知道用户的年龄才能给出答案。

# 需要让用户输入年龄,再将其与投票年龄进行比较,以判断用户是否到投票,年龄从未给出结果。

# 程序需要一个名字时,你需要提示用户输入该名字;程序需要一个名单时,你需要提示输入一系列名字:使用函数input()。

# 以便用户根据需要输入信息。

# 使用while循环让程序不断运行,直到指定的条件不满足为止。

# 通过获取用户输入并学会控制程序的运行时间,你就能编写出交互式程序。

In [2]:

# 函数input()让程序暂停运行,等待用户输入一些文本(eg.Tell me...).

# 获取用户输入后,Python将其赋给一个变量,以方便你使用message。

message = input("Tell me something, and I will repeat it back to you: ")

print(message)

Tell me something, and I will repeat it back to you: Hello

Hello

In [3]:

# 函数input()接受一个参数(Tell me):向用户显示的提示(prompt)或说明,让用户知道该如何做。

# 用户将看到提示Tell me:

# 程序等待用户输入(Hello),并在用户按回车键后继续运行。

# 输入被赋给变量message,

# 接下来print(message)

# 【操作tips】在上述代码行out中空格里填入Hello

In [4]:

# 每当使用函数input()时,都应指定清晰易懂的提示,准确地指出希望用户提供什么信息:

name = input("Please enter your name: ")

print(f"\nHello, {name}!")

Please enter your name: eric

Hello, eric!

In [5]:

# 【操作tips】在提示末尾(这里是冒号后面)包含一个空格,可将提示与用户输入分开,让用户清楚地知道其输入始于何处。 输入eric。

In [6]:

# 提示可能超过一行。

# 可将提示赋给一个变量,再将该变量传递给函数input()。

prompt = "If you tell us who you are, we can personalize the messages you see."

prompt += "\nWhat is your first name? "

name = input(prompt)

print(f"\nHello, {name}!")

If you tell us who you are, we can personalize the messages you see.

What is your first name? eric

Hello, eric!

In [7]:

# 【操作tips】在提示末尾(这里是冒号后面)包含一个空格,可将提示与用户输入分开,让用户清楚地知道其输入始于何处。输入eric。

In [8]:

# 使用函数input()时,Python将用户输入解读为字符串。

age = input("How old are you?")

# 【操作tips】21。

How old are you?21

In [9]:

age

Out[9]:

'21'

In [10]:

# 用户输入的数是21,但我们请求Python提供变量阿哥的值时,它返回的是‘21’:即用户输入数值的字符串表示。

# Python将输入解读成了字符串:这个数用引号括起。

# 如果只想打印输入,这一点问题都没有;

# 但如果试图将输入作为数来使用,就会引发错误:

age >= 18

---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)

Cell In[9], line 6      1 # 用户输入的数是21,但我们请求Python提供变量阿哥的值时,它返回的是‘21’:即用户输入数值的字符串表示。      2 # Python将输入解读成了字符串:这个数用引号括起。      3 # 如果只想打印输入,这一点问题都没有;      4 # 但如果试图将输入作为数来使用,就会引发错误:----> 6 age >= 18

TypeError: '>=' not supported between instances of 'str' and 'int'

In [11]:

# 试图将输入用于数值比较时,无法将字符串和整数进行比较:

# 不能将赋给age的字符串‘21’与数值18进行比较。

# 【解决方法】:

# 使用函数int():可以让Python将输入视为数值;

# 即将属的字符串表示转换为数值表示。

age = input("How old are you?")

# 【操作tips】:输入21

How old are you?21

In [12]:

age = int(age)

age >= 18

Out[12]:

True

In [13]:

# 即用户根据提示输入21后,Python将这个数解读为字符串。

height = input("How tall are you, in inches?")  # 输入

height = int(height)  # 转换为数值

if height >= 48:  # 条件测试

    print("\nYou're tall enough to ride!")

else:

    print("\nYou'll be able to ride when you're a little older.")

How tall are you, in inches?71

You're tall enough to ride!

7.1.3 求模运算符(%)

In [14]:

# 求模运算符(%):将两个数相除并返回余数:

In [15]:

4%3

Out[15]:

1

In [16]:

5%3

Out[16]:

2

In [17]:

6%3

Out[17]:

0

In [18]:

7%3

Out[18]:

1

In [19]:

# 可利用 % 判断一个数是奇数还是偶数。

In [20]:

number = input("Enter a number, and I'll tell you if it's even or odd:")

number = int(number)

if number % 2 == 0:

    print(f"\nThe number {number} is even.")

else:

    print("f\nThe number {number} is odd.")     

Enter a number, and I'll tell you if it's even or odd:36

The number 36 is even.

7.2 while 循环简介

In [21]:

# for循环用于针对集合中的每个元素都执行代码块;

# while循环则不断运行,知道指定的条件不满足为止。

current_number = 1

while current_number <= 5:   # 将接下来的while循环设置成:只要current_number小于或等于5,就接着运行这个循环。

    print(current_number)

    current_number += 1

1

2

3

4

5

In [22]:

# eg.游戏使用while循环,确保在玩家想玩时不但运行,并在玩家想退出时停止运行。

7.2.2 让用户选择何时退出

In [23]:

# 可以使用while循环让程序在用户愿意时不断运行,我们在其中定义了一个退出值,只要用户输入的不是这个值,程序就将接着运行:

prompt = "\nTell me something, and I'll repeat it back to you:"    # 定义

prompt += "\nEnter 'quit' to end the program."

message = ""    # 创建变量message

while message != 'quit':    # 只要message的值不是‘quit’,这个循环就会不断运行。

    message = input(prompt)

    print(message)

# 【tips】输入Hello everyone!,回车键,输入Hello everyone!,回车键,输入quit.

Tell me something, and I'll repeat it back to you:

Enter 'quit' to end the program.Hello everyone!

Hello everyone!

Tell me something, and I'll repeat it back to you:

Enter 'quit' to end the program.Hello everyone!

Hello everyone!

Tell me something, and I'll repeat it back to you:

Enter 'quit' to end the program.quit

quit

In [24]:

#【解析】:创建变量message:

# 用于记录用户输入的值;

# 我们将变量message的初始值设置为空字符串"",让Python首次执行while代码行时有可供检查的东西;

# Python执行while语句时,需要将message的值与‘quit’进行比较,但此时用户还没有输入。

# 如果有可供比较的东西,Python将无法继续运行程序。

# 为解决这个问题,必须给变量message指定初始值;

# 虽然这个初始值只是一个空字符串,但符合要求。

In [25]:

# 唯一美中不足的是,它将单词‘quit’也作为一条消息打印出来。

#【解决方法/修复】:

prompt = "\nTell me something, and I'll repeat it back to you:"    # 同上

prompt += "\nEnter 'quit' to end the program."

message = ""     # 同上--------------------

while message != 'quit':

    message = input(prompt)

    

    if message != 'quit':

        print(message)

        

# 【操作tips】:输入Hello everyone!,回车键;输入Hello everyone!,回车键;输入quit.

Tell me something, and I'll repeat it back to you:

Enter 'quit' to end the program.Hello everyone!

Hello everyone!

Tell me something, and I'll repeat it back to you:

Enter 'quit' to end the program.Hello everyone!

Hello everyone!

Tell me something, and I'll repeat it back to you:

Enter 'quit' to end the program.quit

7.2.3 使用标志

In [26]:

# 在更复杂的程序中,很多不同的时间会导致程序停止运行。

# eg.有多种时间可能导致游戏结束,如玩家失去所有飞船、时间已用完,或者要保护的城市被全部摧毁。

# 在要求很多体哦阿健都满足才继续运行的程序中,可定义一个变量 ,用于判断整个程序是否处于活动状态。

# 这个变量成为标志(flag)。

# 可以让程序在标志为True时继续运行,并在任何时间导致标志的值False时让程序停止运行。

# 这样,在while语句中就只需检查一个条件:标志的当前值是否为True;

# 然后将所有其他测试(将标志设置为False的事件)都放在其他地方,从而让程序更整洁。

In [27]:

prompt = "\nTell me something, and I will repeat it back to you."

prompt += "\nEnter 'quit' to end the program."

active = True     # 初始设置

while active:     # while

    message = input(prompt)    # input

    

    if message == 'quit':    # if:False

        active = False

    else:            # else/elif:print

        print(message)

        

#【输入tips】:输入1→输入quit

Tell me something, and I will repeat it back to you.

Enter 'quit' to end the program.1

1

Tell me something, and I will repeat it back to you.

Enter 'quit' to end the program.quit

In [28]:

# 如果要添加测试(如elif语句)以检查是否发生了其他导致active变为False的事件,就会很容易;

# 在任意个事件导致活动标志变成False时,主游戏循环将退出。

7.2.4 使用break退出循环

In [29]:

# 使用break语句:

# 要立即退出while循环,不再运行循环中余下的代码;

# 也不管条件测试的结果如何(即不运行)。

In [30]:

prompt = "\nPlease enter the name of acity you have visited:"

prompt += "\n(Enter 'quit' when you are finished.)"

while True:

    city = input(prompt)

    

    if city == 'quit':

        break

    else:

        print(f"I'd love to gog to {city.title()}!")

        

# 【输入tips】:输入NY→输入Lee→输入quit

Please enter the name of acity you have visited:

(Enter 'quit' when you are finished.)New York

I'd love to gog to New York!

Please enter the name of acity you have visited:

(Enter 'quit' when you are finished.)Lee

I'd love to gog to Lee!

Please enter the name of acity you have visited:

(Enter 'quit' when you are finished.)quit

In [31]:

# 以whileTrue打头的循环将不断运行,直到遇到break语句;

# 这个程序中的循环判断让用户输入他到过的城市的名字,指导用户输入‘quit’为止。

# 也可以使用break语句来退出遍历列表或字典的for循环。

7.2.5 在循环中使用continue

In [32]:

# 根据条件测试结果决定是否继续执行循环,可使用continue语句;

# 不像break语句那样不再执行余下的代码并退出整个循环。

In [33]:

# eg.从1数到10但只打印其中奇数的循环:

current_number = 0    

while current_number < 10:

    current_number += 1    # 没有input,所以需要命令定义cu_number

    if current_number % 2 == 0:  

        continue    

        

    print(current_number)

1

3

5

7

9

In [34]:

# 以步长1的方式往上数。

7.2.6 避免无限循环

In [35]:

# 每个while循环都必须有停止运行的途径,这样才不会没完没了地执行下去。

In [36]:

# eg. 循环从1数到5:

x = 1

while x <= 5:

    print(x)

    x += 1

1

2

3

4

5

In [37]:

# 但如果不小心遗漏了代码行(x+=1),这个循环将没完没了地运行(打印)。

In [38]:

# 每个程序员偶尔因不小心而编写出无限循环;

# 如果陷入无限循环,可按【Ctrl+C】,也可关闭显示程序输出的终端窗口;

# 要避免编写无限循环,务必对每个while循环进行测试,确保其按预期那样结束。如果你希望程序在用户输入特定值时结束,可以:

# (一)至少有一个这样的地方能让循环条件为False;

# (二)使用break语句得以执行。

# (三)Sublime Text等一些编辑器内嵌了输出窗口,这可能导致难以结束无限循环。

7.3 使用while循环处理列表和字典

7.3.1 在列表之间移动元素

In [39]:

# 要记录大量的用户和信息,需要在while循环中使用列表和字典。

# for循环是一种遍历列表的有效方式,但不应再for循环中修改列表,否则将导致Python难以跟踪其中的元素。

# 要在while循环中使用列表和字典。

# for循环是一种遍历列表的有效方式,但不应在for循环中修改列表,否i则将导致Python难以跟踪其中的元素。

# 要在遍历列表的同时对其进行修改,可使用while循环.

In [40]:

# 假设有一个列表包含新注册,但还未验证的网站用户。

# 验证这些用户后如何将他们移到另一个已验证用户列表中呢?

# 可以使用一个while循环。

unconfirmed_users = ['jay', 'jerk', 'jude']    

confirmed_users = []

while unconfirmed_users:

    current_user = unconfirmed_users.pop()

    

    print(f"Verifying user: {current_user.title()}")

    confirmed_users.append(current_user)

    

print("\nThe following users have been confirmed:")

for confirmed_user in confirmed_users:

    print(confirmed_user.title())

# 创建一个未验证用户列表;

# 创建一个空列表,用于存储以验证的用户;

# 方法pop()以每次一个的方式从列表unconfirmed_users末尾删除未验证的用户;

# 由于jude位于列表unconfirmed_users末尾,起名字将首先被删除/赋给变量current_user并加入列表confirmed_users中。

# 未验证用户列表为空后结束循环,再打印已验证用户列表。

Verifying user: Jude

Verifying user: Jerk

Verifying user: Jay

The following users have been confirmed:

Jude

Jerk

Jay

7.3.2 删除为特定值得所有列表元素

In [41]:

# 函数remove():

# 删除列表中的特定值;

# 这之所以可行,是因为要删除的值只在列表中出现一次.

In [41]:

# eg.假设有一个宠物列表,其中包含多个值为‘cat’的元素。

# 要删除所有这些元素,可不断运行一个while循环,知道列表追踪不再包含值‘cat’

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']

print(pets)

while 'cat' in pets:

    pets.remove('cat')

    

print(pets)

['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']

['dog', 'dog', 'goldfish', 'rabbit']

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

In [42]:

responses = {}

polling_active = True                 # 设置一个标志。指出调查是否继续。

while polling_active:

    name = input("\nWhat is your name?")

    response = input("Which 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':                # 退出while循环

        polling_active = False

    

print("\n--- Poll Results ---")

for name,response in responses.items():

    print(f"{name} would like to climb {response}.")

    

#【输入tips】:输入jay,输入hn,输入yes;输入jerk,输入cq,输入no。

What is your name?jay

Which mountain would you like to climb someday?hn

Would you like to let another person respond?(yes/no)yes

What is your name?jerk

Which mountain would you like to climb someday?cq

Would you like to let another person respond?(yes/no)no

--- Poll Results ---

jay would like to climb hn.

jerk would like to climb cq.

In [43]:

# eg2.熟食店

# 创建一个名为sandwich_orders的列表,在其中包含各种三明治的名字;

# 再创建一个名为finished_sandwiches的空列表;

# 遍历列表sandwich_orders,如I made your tuna sandwich,并将其以到列表finished_sandwiches中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值