如何将输入读取为整数而不显式转换它们?

时间:2018-08-08 22:26:27

标签: string python-3.x type-conversion integer user-input

我编写了一个程序,在从用户那里读取一些简单的数字和字符串后,将其输出给用户。

为了打印和使用数学运算符,我不得不多次转换数据类型,以便按照我想要的方式打印它。

这是我的代码:

print("What is your name?")
name = input()

print("What is your age?")
age = input()

print(type(age))
print("Check for type")

print("We will now add your " + age + " years to 50.")
age = int(age)
print(type(age))
print("Check for type")

finalAge = 50 + age
finalAge = str(finalAge)
age = str(age)
print("In 50 years " + name + " will be " + finalAge + " years old.")

以下是输出:

What is your name?
Gavin
What is your age?
23
<class 'str'>
Check for beginning
We will now add your 23 years to 50.
<class 'int'>
Check for end
In 50 years Gavin will be 73 years old.

最重要的是,我正在寻找一种更好的方法,不必在程序完成之前多次转换类型。欢迎任何建议!

2 个答案:

答案 0 :(得分:0)

尽管int值中包含数字,但是您无法将str值添加到str值或类似的值中,因为它们的变量类型不同,但是您可以创建函数来简化操作您的项目或为相同的内容使用更少的代码,例如,您可以使用以下代码:-

def sum(a, b):
    return str(int(a)+int(b));

此函数可将两个数字值的总和作为字符串返回,并且您可以根据需要创建许多自定义函数,可以通过使用使代码更轻松,更有趣功能

答案 1 :(得分:-1)

最好不要进行重新分配,而仅在需要时进行投射。

print("What is your age?")
age = input()

print("We will now add your " + age + " years to 50.")

finalAge = 50 + int(age)
print("In 50 years " + name + " will be " + str(finalAge) + " years old.")

此外,优良作法是根据数据类型分配合适的数据类型。 age最适合int

print("What is your age?")
age = int(input())

print("We will now add your " + str(age) + " years to 50.")

finalAge = 50 + age
print("In 50 years " + name + " will be " + str(finalAge) + " years old.")