这很有效,但我觉得为打印调用定义一个新变量效率不高。是否有更好的方法来获取输入并将其作为字符串打印。然后将它转换为int并可能再次返回到str?我读了%命令,但不相信我正确地加入了它。
print ('This is a program to choose two numbers adding up to ten')
firstInput = input(" Pick a number? ")
firstNumber = int (firstInput)
print ('Ok the base number is ' + firstInput + ' so make that 10')
newNumber = int(input(' Number to add? '))
if newNumber + firstNumber == 5 + 5:
print ("That worked!")
if newNumber + firstNumber != 5 + 5:
print ("That didn't work!")`
答案 0 :(得分:2)
使用string formatting插入整数:
print('Ok the base number is {} so make that 10'.format(firstNumber))
您可以执行更复杂的格式化,但在此基本示例中,第一个插槽({}
)的值取自第一个参数(firstNumber
),该参数自动转换为字符串使用str()
内置函数。
作为一个完整的程序,只需要一些小的优化:
print ('This is a program to choose two numbers adding up to ten')
firstNumber = int(input(" Pick a number? "))
print('Ok the base number is {} so make that 10'.format(firstNumber))
newNumber = int(input(' Number to add? '))
if newNumber + firstNumber == 10:
print("That worked!")
else:
print("That didn't work!")`