码迷,mamicode.com
首页 > 其他好文 > 详细

第 7 章 用户输入和while 循环

时间:2017-12-09 14:05:12      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:python   while   can   python 2   raw_input   messages   put   一个   结果   

7.1 函数input() 的工作原理

函数input() 让程序暂停运行,等待用户输入一些文本,

函数input() 接受一个参数:即要向用户显示的提示 或说明

7.1.1 编写清晰的程序

每当你使用函数input() 时,都应指定清晰而易于明白的提示,准确地指出你希望用户提供什么样的信息

prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? " #创建多行字符串的方式
name = input(prompt)
print("\nHello, " + name + "!")

结果

If you tell us who you are, we can personalize the messages you see.
What is your first name? Eric
Hello, Eric!

 

7.1.2 使用int() 来获取数值输入

7.1.3 求模运算符

处理数值信息时,求模运算符 (%)是一个很有用的工具,它将两个数相除并返回余数:处理数值信息时,求模运算符 (%)是一个很有用的工具,它将两个数相除并返回余数:

number = input("Enter a number, and I‘ll tell you if it‘s 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 Ill tell you if its even or odd: 42
The number 42 is even.

 

7.1.4 在Python 2.7中获取输入

如果你使用的是Python 2.7,应使用函数raw_input() 来提示用户输入。这个函数与Python 3中的input() 一样,也将输入解读为字符串。

 

第 7 章 用户输入和while 循环

标签:python   while   can   python 2   raw_input   messages   put   一个   结果   

原文地址:http://www.cnblogs.com/jdy113/p/8011177.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!