python - Python中输入函数的整数或浮点数
问题描述
通过 Plural Sight 参加 Python 简介课程时,我发现对我有用的代码与讲师的不同。(不同的版本?)有一个我不明白的区别。为什么输入函数有时需要一个 int 或一个浮点数,但有时它会崩溃?以下是一些只能以这种方式工作的示例:
年龄计算器
age = input("How old are you?\n")
decades = int(age) // 10 years = int(age) % 10
贷款计算器
money_owed = float(input("How much money do you own, in dollars?\n")) # 50,000
apr = float(input('What is the annual percentage rate?\n')) # 3.0
payment = float(input('What will your monthly payment be, in dollars?\n')) # 1,000
months = int(input('How many months do you want to see results for? \n')) # 24
解决方案
这是因为input()
,默认情况下,将值存储为str
(字符串)。如果要对存储的值执行数学运算,可以将其类型转换为 anint
或 afloat
例如:
num = int(input())
print(num+10)
或者
num = input()
print(int(num)+10)
推荐阅读
- apache-kafka-connect - Kafka HDFS Sink 连接器重启
- python - 从 Python 中的 Dictionary 打印特定键的值
- laravel - Laravel JSON 响应错误处理不起作用
- apache - 通过 .htaccess 从 URL 中删除双斜杠的问题
- typescript - 在嵌套对象中使用 firestore 的 FieldPath.documentId()
- javascript - React:在渲染函数中获取函数的返回值
- reactjs - 单击链接时滚动到页面一部分的React.js Header?
- python - 将数据框转换为列表时更改值
- c# - JsonSerializer.Deserialize 多次使用
- javascript - 根据 JSON Array 重新排列 HTML 表格数据