一起学习Python的用户输入和while循环
作者:雷蕾
大多数程序目的在于解决最终用户得问题,为此通常需要从用户那里获取一些信息。为此我们需要学习函数input()以及使用while()循环让程序能不断运行,直到指定的条件不满足为止。
(一)函数input()的工作原理
我们先来看一段简单的代码:
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,python world!
hello,python world!
当我们从键盘处输入hello,python world!时,打印结果为hello,python world!
为什么会出现这样的结果呢?我们需要解读一下函数input()的工作原理:函数input()接受一个参数——要向用户显示的提示或说明,让用户如何做。在第一行代码中,用户会看到提示tell me something,and i will repeat it back to you:,然后等待用户输入,并在用户输入完毕按回车键后继续执行,将用户输入的赋给变量message,接下来print(message)就会将用户输入的呈现出来。
为了用户能够看到清晰的提示,我们可以在提示末尾包含一个空格,将提示与用户的输入分开。
有时候我们会面临提示字符串过长,我们可以通过**运算符+=**将在前面赋予变量的字符串末尾附加字符串。我们来看代码:
promot="if you tell us who you are,we can personalized the messages you see"
promot+="\nwhat is you first name?" #多行提示可用运算符+
name=input(promot)
print(f"\nhello,{name.title()}")
输出结果:
if you tell us who you are,we can personalized the messages you see
what is you first name?eric
hello,Eric
下面我们来学习使用**int()**来获取数值输入
在使用函数input()时,python将用户输入解读为字符串而不是数值。
>>> age=input("how old are you ? ")
ho