欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python学习记录5:基础知识-用户输入和while循环

程序员文章站 2022-07-14 23:10:23
...

一、用户输入

  1. 函数 .input()
msg = input("Tell me something, and I will repeat it back to you: ")
print(msg)
函数input()接受一个参数;在这个示例中,python运行第一行代码时,用户将看到提示:
Tell me something, and I will repeat it back to you: 
程序等待用户输入,并在用户按回车键后继续运行。
输入存储在变量msg中,接下来的print(msg)将输入输出。

当必要的提示不止一行时,我们可以:

#先将部分提示存入一个变量,再使用+=运算符接上剩余的提示
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("\nHello, " + name + "!")
output:
If you tell us who you are, we can personalize the messages you see.
What is your first name? Ming

Hello, Ming!
  1. 使用 int() 来获取数值输入
    input会将输入理解为字符串,我们需要int来转换。将数值用于计算和比较前,务必将其转化为数值表示,避免不必要的错误。
height = input("How tall are you, in inches? ")
height = int(height) #转化为数值

if height >= 36:
    print("\nYou're tall enough to ride!")
else:
    print("\nYou'll be able to ride when you're a little older.")
  1. 求模运算符:% (同c/c++
    *python 2.7 中应使用: raw_input()来获取输入。

二、while循环

1、简述:

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
  
active = True #随便定义的一个标志变量
while active: #while的用法与c/c++类似,区别是不用括号
    message = input(prompt)
    
    if message == 'quit':
        active = False
    else:
        print(message)

*break/continue在python中的用法与c/c++中相同。

2、用while循环来处理列表和字典:

  1. 在列表间移动元素
#首先,创建一个待验证用户列表
#和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []

#验证每个用户,直到没有未验证用户为止
#将每个经过验证的用户都移动到已验证用户列表中
while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    
    print("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())
output:
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice

The following users have been confirmed:
Candace
Brian
Alice
  1. 删除包含特定值的所有列表元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')
    
print(pets)
output:
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
  1. 使用用户输入来充填字典
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':
        polling_active = False
        
# 调查结束,显示结果
print("\n--- Poll Results ---")
for name, response in responses.items():
    print(name + " would like to climb " + response + ".")
output:
What is your name? 小明
Which mountain would you like to climb someday? 珠穆朗玛峰
Would you like to let another person respond? (yes/ no) yes

What is your name? 不告诉你
Which mountain would you like to climb someday? 也不告诉你
Would you like to let another person respond? (yes/ no) no

--- Poll Results ---
小明 would like to climb 珠穆朗玛峰.
不告诉你 would like to climb 也不告诉你.

参考文献:《Python编程:从入门到实践》——【美】Eric Matthes