Python编程学习笔记(四)

七、用户输入和while循环

1.用户输入函数:input()

(1)简单程序示例

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

输出结果:

Please input your name: jerry
Hello, Jerry!

提示可以超过一行:

prompt ="If you tell us who you are,we can personalize the message you see."
prompt +="\nWhat's your first name? " #在自己后面自加
name=input(prompt)
print("\nHello, "+name.title()+"!")

输出结果:

If you tell us who you are,we can personalize the message you see.
What's your first name? jerry

Hello, Jerry!

(2)使用int()来获取数值输入
  input()函数将用户输入解读为字符串,可用int()来获取数值类型。

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

(3)求模运算符:取余(%)

number=input("Please input a number:")
number=int(number)
if number%2==0:
    print("\nThe number "+str(number)+" is even.")
else:
    print("\nThe number "+str(number)+" is odd.")

输出结果:

Please input a number:666666

The number 666666 is even.

2.while循环简介

(1)简单示例
  不断运行,直到指定的条件不满足为止。

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

输出结果:

1
2
3
4
5

(2)让用户选择何时退出

prompt="\nTell me something,and I will repeat it: "
prompt+="\nEnter 'quit' to end the program."
message="" #初始化,创建一个空字符串,提供比较
while message !='quit':
    message=input(prompt) #input()放在while循环中,每次循环后都停在这等待用户输入

    if message !='quit':
        print(message)

输出结果:

Tell me something,and I will repeat it: 
Enter 'quit' to end the program.Hello!
Hello!

Tell me something,and I will repeat it: 
Enter 'quit' to end the program.How are you?
How are you?

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

(3)使用标志
  当要检查的条件很多时,在一条while语句中检查所有条件比较复杂;可以定义一个变量(标志),让程序在标志为True时运行,并在任何导致标志为False的事件时让程序停止。

prompt="\nTell me something,and I will repeat it: "
prompt+="\nEnter 'quit' to end the program."

active=True
while active:
    message=input(prompt)

    if message =='quit':
        active=False
    else:
        print(message)

(4)使用break退出循环
  立即跳出循环

prompt="\nPlease input 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 love to go to "+city.title()+"!")

输出结果:

Please input the name of a city you have visited:
(Enter 'quit' when you are finished.)beijing
I'd love to go to Beijing!

Please input the name of a city you have visited:
(Enter 'quit' when you are finished.)shanghai
I'd love to go to Shanghai!

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

注:break可用于任何Python的循环语句(for,while,…)
(4)在循环中使用continue
  不执行循环中余下代码,但返回到循环开头

#从1数到10,但只打印其中的奇数
current_number=0
while current_number<10:
    current_number+=1
    if current_number%2==0:
        continue
    print(current_number)

输出结果:

1
3
5
7
9

注意:避免无限循环

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

  for循环一般用于遍历列表但不修改;
  while循环可在遍历列表的同时进行修改。
(1)在列表之间移动元素
  假设有一个未验证用户的列表,使用while循环验证用户并移到已验证用户列表中。

#创建一个未验证用户列表
#和一个已验证用户列表
unconfirmed_users=['alice','danny','candace']
confirmed_users=['tom','david']

#验证未验证的用户,直到没有未验证用户为止
#将验证过的用户移到已验证用户列表中
while unconfirmed_users:
    current_user=unconfirmed_users.pop()
    print("\nVerifying 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())

unconfirmed_users=['alice','danny','candace']
confirmed_users=['tom','david']

for order in range(len(unconfirmed_users)):
    current_user=unconfirmed_users[order]
    print("\nVerifying 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())

输出结果:


Verifying user: Candace

Verifying user: Danny

Verifying user: Alice

The following users have been confirmed: 
Tom
David
Candace
Danny
Alice

(2)删除包含特定值的所有列表元素
  remove()只能删除一个特定值元素

pets=['cat','dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)

pets.remove('cat')
print(pets)

while 'cat' in pets:
    pets.remove('cat')
print(pets)

输出结果:

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

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

#定义一个空字典
responses={}

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

while polling_active:
    #提示被调查者的名字和回答
    name=input("What's your name? ")
    mountain=input("Whice mountain woule you like to climb? ")

    #将名字和答案存储在字典中
    responses[name]=mountain

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

#调查结束,显示结果
print("-----Poll Results-----")
for name,mountain in responses.items():
    print(name.title()+" would like to climb "+mountain.title()+".")

输出结果:

What's your name? jenny
Whice mountain woule you like to climb? denali
Would you like to let another person respond? yes
What's your name? lynn
Whice mountain woule you like to climb? thumb
Would you like to let another person respond? yes
What's your name? bob
Whice mountain woule you like to climb? big mountain
Would you like to let another person respond? no
-----Poll Results-----
Jenny would like to climb Denali.
Lynn would like to climb Thumb.
Bob would like to climb Big Mountain.

参考文献:袁国忠,Python编程:从入门到实践

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值