我有以下脚本:
#! /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))
但这不起作用......
所以,如果你以约翰的第一人称回答,那么你应该得到:
输入约翰的年龄:
我该怎么做?
答案 0 :(得分:1)
尝试
age1 = int(input("Enter the age of {}:".format(name1)))
或者如果您更喜欢字符串插值:
age1 = int(input("Enter the age of %s:" % name1))
答案 1 :(得分:0)
input()
将字符串作为参数,因此只需使用您的变量创建一个字符串。即,如果firstname == 'John'
:
lastname = input('What is the last name of '+firstname+': ')
答案 2 :(得分:0)
age1 = int(input("Enter the first age " + name1))
您需要连接字符串。你太近了......