首页 > 解决方案 > 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

标签: python

解决方案


这是因为input(),默认情况下,将值存储为str(字符串)。如果要对存储的值执行数学运算,可以将其类型转换为 anint或 afloat

例如:

num = int(input())
print(num+10)

或者

num = input()
print(int(num)+10)

推荐阅读