input是输入语句,用于人机交互。 input() 函数接受一个标准输入数据,返回为 string 类型。如果需要输入的未数字,则需要额外定义。
sex=input(“Sex:”) #这里会默认为Sex为字符串类型变量 #需要改为: sex=int(input("Sex:") #这样Sex的才会变成整形变量
字符串拼接一般有三种方式
1、用加号拼接(最直观的做法,但是不推荐)
2、用%占位符拼接
3、用.format格式化工具进行占位拼接。
具体看以下代码:用%占位符拼接的程序案例
1 name=input("name:") 2 sex=input("sex:") 3 age=int(input("age:")) #age是整形变量,需要用int()赋值 4 5 infor=''' 6 ------infor of %s----- 7 name:%s 8 sex:%s 9 age:%d #因为age为整形变量,所以用%d 10 11 '''%(name,name,sex,age) 12 13 print(infor.title()) #.title格式是让每行第一个字母大写
代码运行结果:
1 C:UsersAdministratorPycharmProjectsuntitledvenvScriptspython.exe C:/Users/Administrator/PycharmProjects/untitled/show530/interduce.py 2 3 name:hongtao 4 sex:male 5 age:36 6 7 ------Infor Of Hongtao----- 8 Name:Hongtao 9 Sex:Male 10 Age:36 11 12 13 14 Process finished with exit code 0
用.format格式化工具进行占位拼接的程序案例:
1 name=input("Please input your name:") 2 sex=input("Please input your sex:") 3 job=input("Please input your job:") 4 saleary=int(input("Please input your saleary:")) 5 6 7 8 print("Information of {_name} name:{_name} sex:{_sex} job:{_job} saleary:{_saleary}".format(_name=name,_sex=sex,_job=job,_saleary=saleary).title())
代码运行结果:
1 C:UsersAdministratorPycharmProjectsuntitledvenvScriptspython.exe C:/Users/Administrator/PycharmProjects/untitled/show530/interduce2.py 2 3 Please input your name:hongtao 4 Please input your sex:male 5 Please input your job:it 6 Please input your saleary:30000 7 8 9 Information Of Hongtao 10 Name:Hongtao 11 Sex:Male 12 Job:It 13 Saleary:30000 14 15 16 Process finished with exit code 0
另外一种方式需要用到{}。把代码1改一下,改为以下代码:
1 name=input("name:") 2 sex=input("sex:") 3 age=int(input("age:")) 4 5 infor=''' 6 ------INFOR OF {0}----- #用{0}表示name 7 name: {0} 8 sex: {1} 9 age: {2} 10 11 '''.format(name,sex,age) 12 13 print(infor.title())
代码运行结果:
1 C:UsersAdministratorPycharmProjectsuntitledvenvScriptspython.exe C:/Users/Administrator/PycharmProjects/untitled/show530/interduce3.py 2 3 name:hongtao 4 sex:male 5 age:36 6 7 ------Infor Of Hongtao----- 8 Name: Hongtao 9 Sex: Male 10 Age: 36 11 12 13 14 Process finished with exit code 0