包括变量的输入函数提示



我有以下脚本:

#! /usr/bin/python3
name1 = input('Enter the name of first person ')
name2 = input('Enter the name of second person ')
age1 = int(input("Enter the first age "))
age2 = int(input('Enter the second age '))
print('%s' %name1,  'is %d' %age1, 'years and %s' %name2,  'is %d' %age2, 'years')
agex = age1
age1 = age2
age2 = agex

print('Now we swap ages: %s' %name1,  'is %d' %age1, 'years and %s' %name2,  'is %d' %age2, 'years')

想要的是询问年龄,包括在姓名问题中输入的名称,我的意思是,像这样:

age1 = int(input("Enter the age of", name1))

但这行不通...

因此,如果你以第一人格约翰的身份回答,那么你应该得到:

输入约翰的年龄:

我该怎么做?

试试

age1 = int(input("Enter the age of {}:".format(name1)))

或者,如果您更喜欢字符串插值:

age1 = int(input("Enter the age of %s:" % name1))

input()将字符串作为其参数,因此只需使用变量创建一个字符串即可。 即,如果firstname == 'John'

lastname = input('What is the last name of '+firstname+': ')
age1 = int(input("Enter the first age " + name1))

您需要连接字符串。 你离得这么近...

最新更新