Python Crash Course读书笔记 - 第7章:USER INPUT AND WHILE LOOPS

input函数工作原理

>>> message=input("your name:")
your name:steven
>>> print(message)
steven

使用int函数可将输入转换为整数:

>>> age = input("How old are you? ")
How old are you? 18
>>> age = int(age)
>>> age += 2
>>> age
20

如果是浮点数,可以使用函数float:

>>> a = float(1.2)
>>> a
1.2

使用%(modulo)可以求余数:

>>> 11%2
1
>>> 12%2
0

while循环

$ cat months.py
months = ['jan', 'feb', 'march', 'apr']
i=0
while i < 4:
    print(months[i].title())
    i += 1

$ python3 months.py
Jan
Feb
March
Apr

用户选择退出:

$ cat echo.py
message = ""
while message != 'quit':
    message = input("you input:")
    if message != 'quit': print(message)

$ python3 echo.py
you input:hello
hello
you input:world
world
you input:quit

以上程序也可以改为使用标志的方式:

$ cat echo.py
active = True
while active:
    message = input("you input:")
    if message == 'quit':
        active = False
    else:
        print(message)

$ python3 echo.py
you input:hello
hello
you input:world
world
you input:quit

使用break跳出循环,以上程序也可以改为如下:

while True:
    message = input("you input:")
    if message == 'quit':
        break
    else:
        print(message)

类似的,也可以使用continue跳过余下的代码继续循环。

while循环与List和字典结合

示例:

$ cat whilelist.py
todolist = ['task1', 'task2', 'task3']
donelist = [] # empty list

while todolist:
    donelist.append(todolist.pop())

print(f"Done List is: {donelist}")
print(f"Todo List is: {todolist}")

$ python3 whilelist.py
Done List is: ['task3', 'task2', 'task1']
Todo List is: []

注意while todolist:写法,表示当列表非空,不能写成while todolist[]:

另一个实例,使用while in格式:

$ cat removeevil.py
gods = ['zeus','evil', 'athena', 'evil', 'apollo', 'hera', 'iris']
toremove = 'evil'
while toremove in gods:
    gods.remove(toremove)

print(gods)
$ python3 removeevil.py
['zeus', 'athena', 'apollo', 'hera', 'iris']

最后一个例子是利用while bool_variable形式搜集信息,并填充到字典中。

发布了370 篇原创文章 · 获赞 43 · 访问量 55万+

猜你喜欢

转载自blog.csdn.net/stevensxiao/article/details/103996883