Python学习笔记(六): 输入与while循环

第六章 输入与while循环


6.1 函数input()的工作原理


函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中。

name = ''
name = input("who are you?")
print("Hello, " + name + "!")

who are you?
输入:tim
输出:
Hello, tim!

函数input()接受一个参数:即要向用户展示的提示或说明
程序等待用户输入,在用户按回车键后继续运行。

6.1.1 用int()获取数值输入

使用函数input()时,Python会将用户输入解读为字符串。
可以使用int()函数,让Python将参数汇总的的字符串转化为数值。(与str()对应)

age = ''
age = input("How old are you?\n")
age = int(age)
if age >= 18:
    print("You are an adult.")

输入:19
输出:You are an adult.


6.2 while循环


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

1
2
3
4
5

s = input("i am a repeater\n")
while s != 'quit'
    print(s)
    s = input()

复读机,直到用户输入quit停止

flag = True
count = 5
while flag:
    print(count)
    count -= 1
    if count < 0:
        flag = False

5
4
3
2
1
0

6.2.1 在循环中使用break和continue

while True:
    s = input()
    if s == 'quit':
        break
    print("You just inputed " + s)

复读机,直到输入quit

continue不多赘述,与C语言作用相同

6.3 用while循环来处理列表和字典


6.3.1 在列表之间移动元素

target = ['apple', 'bannana', 'peach']
shopping_car = []
while target:
    cur = target.pop()
    print("Buy " + cur)
    shopping_car.append(cur)
print("You have bought these:")
print(shopping_car)
print("These not bought:")
print(target)

Buy peach
Buy bannana
Buy apple
You have bought these:
[‘peach’, ‘bannana’, ‘apple’]
These not bought:
[]

6.3.2 删除所有列表中的特定值

fruits = ['apple', 'orange', 'peach', 'apple', 'apple']
while 'apple' in fruits:
    fruits.remove('apple')
print(fruits)

[‘orange’, ‘peach’]

6.3.3 利用输入填充字典

cilent = {}
while True:
    name = input("Please input your name:")
    nick_name = input("Please input your nickname:")
    cilent[nick_name] = name
    re = input("Would you like to continue? (yes/no)")
    if re == 'no':
        break
print(cilent)
发布了35 篇原创文章 · 获赞 15 · 访问量 1127

猜你喜欢

转载自blog.csdn.net/irimsky/article/details/95768078
今日推荐