7.1 函数input()的工作原理

7.1.1 编写清晰的程序

例:

message = input("Tell me something, and I will repeat it back to you: ")
print(message)

函数input接受一个参数:即向用户显示的提示或说明。上述代码的运行结果如下:

Tell me something, and I will repeat it back to you: Hello everyone!

同理,有例子:

prompt = "If you tell us who you are, we can personalize the message you see."
prompt += "\nWhat is your first name?"

name = input(prompt)
print("\nHello, " + name + "!")

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

height = input("How  tall are you, in inches?")
height = int(height)

if height >= 36:
	print("\nYou're tall enough to ride!")
else:
	print("\nYou'll be able to ride when you're a little older.")

在该程序中,我们在输入height后,Python将这个数字解读为一个字符串。但随后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.")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值