[python笔记]6.用户输入和while循环

一.input()函数

1)input()

input接受一个参数,向用户显示的提示说明,输入存储在变量中
eg1:

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 world
hello world

eg2:

name = input("Please inter your name: ")
print("Hello, " + name + "!")

输出

Please inter your name: Eric
Hello, Eric!

eg3:

prompt = "If you tell us who you are, we can peisonalize the message you see"
prompt += "\nWhat is your first name?"
name = input(prompt)
print("\nHello " + name + "!")

输出

If you tell us who you are, we can peisonalize the message you see
What is your first name?Eric

Hello Eric!

2)int()获取数值输入

使用函数input(),Python将用户的输入解读为字符串,如果要获得整数,就需要调用int函数
eg1:

>>> age = input("How old are you? ")
How old are you? 21
>>> age>=18
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>=' not supported between instances of 'str' and 'int'
>>>

这里的21是作为字符串str的类型,需要做整数处理的时候就要用到int()函数

>>> age = input("How old are you? ")
How old are you? 21
>>> age = int(age) 
>>> age>=18
True

eg2:

height = input("How tall are you, in inches? ")
height = int(height)
if height >= 36:
    print("\nYou're tall enough ro 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 ro ride

3)取模运算

**%**用法同C

扫描二维码关注公众号,回复: 9002547 查看本文章
number = input("Enter a number, and I'll tell you if it is even or odd: ")
number = int(number)
if number%2 == 0:
    print("\nThe number " + str(number) + " is even.")
else:
    print("\nThe number " + str(number) + " is odd.")

输出

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

The number 42 is even.

二.while循环

1)while循环

eg:

current_number = 1
while current_number < 5:
    print(current_number)
    current_number += 1 #这里不能是current_number++

输出

1
2
3
4

2)让用户选择合适退出

prompt = "\nTell me something, and I will repeat it back to you: "
prompt += "\nEnter 'quit' to end this program."
message=""
while message != 'quit':
    message = input(prompt)
    print(message)

输出

Tell me something, and I will repeat it back to you:
Enter 'quit' to end this program.hello everyone
hello everyone

Tell me something, and I will repeat it back to you:
Enter 'quit' to end this program.hello again
hello again

Tell me something, and I will repeat it back to you:
Enter 'quit' to end this program.quit
quit

3)使用标志

定义bool类型变量决定while循环进行 flag
eg:

prompt = "\nTell me something, and I will repeat it back to you: "
prompt += "\nEnter 'quit' to end this program."
active = True
while active:
    message = input(prompt)
    if message == 'quit':
        active = False
    else:
        print(message)

输出

Tell me something, and I will repeat it back to you:
Enter 'quit' to end this program.hello world
hello world

Tell me something, and I will repeat it back to you:
Enter 'quit' to end this program.quit

4)使用break退出循环

eg:

prompt = "\nPlease enter the name of a city you have visited"
prompt += "\n(Enter 'quit when you are finished')"
while True:
    city = input(prompt)
    if city == 'quit':
        break
    else:
        print("I'd like love to go to " + city.title() + "!")

输出

Please enter the name of a city you have visited
(Enter 'quit when you are finished')New York
I'd like love to go to New York!

Please enter the name of a city you have visited
(Enter 'quit when you are finished')San Francisco
I'd like love to go to San Francisco!

Please enter the name of a city you have visited
(Enter 'quit when you are finished')quit

5)continue

用法同 C
eg:

current_number = 0
while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:
        continue
    print(current_number)

输出

1
3
5
7
9

无限循环时使用ctrl+C结束终端窗口

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

1)在列表之间移动元素

#创建待验证用户列表和存储已验证用户空间列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
#验证每个用户,直到没有未验证用户为止,将每个经过验证的列表都移到已验证的用户列表中
while unconfirmed_users:#如果列表中没有元素,则返回false
    current_users = unconfirmed_users.pop()
    print("Verifying user: " + current_users.title())
    confirmed_users.append(current_users)
print("\nThe following users have been confirmed")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

输出

Verifying user: Candace
Verifying user: Brian
Verifying user: Alice

The following users have been confirmed
Candace
Brian
Alice

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

eg:

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')#remove会删除pets中第一个值为cat的元素
print(pets)

输出

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

3)使用用户输入来填充字典

eg:

responses = {}
polling_active = True
while polling_active:
    name = input("\nWhat is your name?")
    response = input("Which mountain would you like to climb somedays?")
    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 wo climb " + response + ".")

输出:

What is your name?Eric
Which mountain would you like to climb somedays?Denali
Would you like to let another person respond? (yes/no)yes

What is your name?Lynn
Which mountain would you like to climb somedays?Devil's Thumb
Would you like to let another person respond? (yes/no)no

--- Poll Results ---
namewould like wo climb Denali.
namewould like wo climb Devil's Thumb.
发布了101 篇原创文章 · 获赞 1 · 访问量 2996

猜你喜欢

转载自blog.csdn.net/weixin_44699689/article/details/104113589