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