【发布时间】:2018-08-08 22:26:26
【问题描述】:
我写了一个程序,在从用户那里读取一些简单的数字和字符串后输出给用户。
为了打印和使用数学运算符,我必须多次转换数据类型才能按我想要的方式打印。
这是我的代码:
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.
最重要的是,我正在寻找一种更好的方法,在程序完成之前不必多次转换类型。接受任何建议!
【问题讨论】:
-
使用字符串格式而不是串联:
print("{}".format(50)) -
@JonathonReinhart 你有任何示例代码来说明它的外观吗?
-
但是为什么你给年龄赋予
str值,然后你给它一个int值呢?是不是错了? -
@Azhy 一开始是一个字符串,后来我改成 Integer 来添加,然后又改回 String。看起来我本可以更好地制定我的方法。
标签: string python-3.x type-conversion integer user-input