ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ***** # 7.1 函数 input()的工作原理 程序等待用户输入,并在用户按回车键后继续运行。输入存储在变量message中 ``` message = input("Tell me something, and I will repeat it back to you: ") print(message) ``` 函数input()接受一个参数:即要向用户显示的提示或说明,让用户知道该如何做 ## 7.1.1 编写清晰的程序 每当你使用函数input()时,都应指定清晰而易于明白的提示,准确地指出你希望用户提供 什么样的信息——指出用户该输入任何信息的提示都行,如下所示: ``` name = input("Please enter your name: ") print("Hello, " + name + "!") ``` ## 7.1.2 使用 int()来获取数值输入 使用函数input()时, Python将用户输入解读为字符串 例如: 用户输入的是数字21,但我们请求Python提供变量age的值时,它返回的是'21'——用户输入的数值的字符串表示。 ``` >>> age = input("How old are you? ") How old are you? 21 >>> age '21' ``` 函数int()将数字的字符串表示转换为数值表示,例如: ``` height = input("How tall are you, in inches? ") height = int(height) if height >= 36: print("\\nYou're tall enough to ride!") ``` ## 7.1.3 求模运算符 ``` >>> 4 % 3 1 ``` # 7.2 while 循环简介 ## 7.2.1 使用 while 循环 ``` current_number = 1 while current_number <= 5: print(current_number) current_number += 1 ``` ## 7.2.3 使用标志 flag ``` active = True while active: message = input(prompt) if message == 'quit': active = False else: print(message) ``` ## 7.2.4 在循环中使用break ## 7.2.4 在循环中使用continue # 7.3 使用 while 循环来处理列表和字典 **注意** ``` a = {} if a : #字典或列表为空可以当做布尔值的false ```