python学习:格式化输出

时间:2023-12-31 21:09:32

格式化输出

代码如下:

name = input("Name:")

age = input("Age:")

job = input("Job:")

salary = input("Salary")

msg = '''

------------------- info of %s ----------------------

Name: %s

Age: %s

Job: %s

Salary: %s

-------------------- end --------------------------

''' %(name,name,age,job,salary)

print(msg)

代码2如下:

name = input("Name:")

age =int( input("Age:"))  #将age转化为数字,后面可以计算

job = input("Job:")

salary = input("Salary")

if salary.isdigit(): #判断salary长的像不像数字

  salary = int(salary)

else:

  print("must input digit")

  exit() #退出程序

  #或者 exit("must input digit")

msg = '''

------------------- info of %s ----------------------

Name: %s

Age: %s  #%s改成%d 就只能输入数字

Job: %s

Salary: %s  #%s改成%d 就只能输入数字

You will be retired in %s years

-------------------- end --------------------------

''' %(name,name,age,job,salary,65-age)

print(msg)

#ctrl+? 选中的多行代码被注释

代码3如下:

name = input("Name:")

age =int( input("Age:"))  #将age转化为数字,后面可以计算

job = input("Job:")

salary = input("Salary")

if salary.isdigit(): #判断salary长的像不像数字

  salary = int(salary)

msg = '''

------------------- info of %s ----------------------

Name: %s

Age: %s  #%s改成%d 就只能输入数字

Job: %s

Salary: %d  #%s改成%d 就只能输入数字

You will be retired in %s years

-------------------- end --------------------------

''' %(name,name,age,job,salary,65-age)

print(msg)

#ctrl+? 选中的多行代码被注释

占位符

  %s   s = string 字符串

  %d  d = digit 整数

  %f  f = float 浮点数 就是小数