The use of print() function in python2.7 and the difference between input() and raw_input()

1. Use of the print() function in python2.7:

  1. Directly output any character or number within double quotes or single quotes
  2. To output the value of a variable, you don’t need to add double quotes or single quotes, just write the variable name directly inside (), or write the variable name directly with a space after print
  3. Simultaneously output multiple contents, different contents are separated by commas, and different contents include contents and variables in double quotes or single quotes.
  4. One or more variables are mixed in the content in double quotes or single quotes, and % plus variable type is used to replace the position where the variable value is to be output, such as character type %s, floating point type %f. And add a % sign and parentheses after the double quotation marks or single quotation marks, and write the variable names in order in the parentheses, and separate the variables with commas.
  5. String formatted output:
    Width description : Add a number after the % of the variable value to be output. This number represents how many digits the variable occupies.
    For example: print('Your score is %8s points') %(variable name)
    float Point accuracy description : add a dot after the % of the variable value to be output and then add a number. This number represents the accuracy to a few decimal places.
    For example, print ('your score is %.4s')% (variable name)
    width accuracy Simultaneous description : Add a number after the % of the variable value position to be output, then a dot and a number, you can set the width and precision at the same time
    print('your score is %8.4s')%(variable name)

Code example:

#直接输出双引号或单引号内的任何字符或数字
print '我love123,   前面是三个空格'
#输出变量的值,不用加双引号或单引号,直接在()内写变量名称即可,或者print后面空格直接写变量名称
x=100
y=99
print x
print(x)
print x,y
#同时输出多项内容,不同内容用逗号隔开,不同内容包括双引号或单引号内的内容、变量。
print '我爱中国',x,y,"i love china"
#在双引号或单引号内的内容中掺杂有一个变量或多个,在要输出变量值的位置用%加变量类型来代替
population=14
nationality=56
print '我国有%s亿人口,%s个民族'%(population,nationality)
# 字符串格式化输出
print '我国有%4.1f亿人口,%8s个民族'%(population,nationality)

2. The difference between input() and raw_input() in python2.7

input() inputs numbers, variables, and expressions. If letters are entered, they will be recognized as variables. If the variable is not defined, an error will be reported.
As follows:

input('请输入一个字母:')

error message
insert image description here

raw_input() input any alphanumeric Chinese characters will be displayed exactly the same as the string.
If the input number is to be assigned to other variable calculations, the character type must be converted, for example a=float(input('Please enter the number:'))

After changing to raw_input, it will not be automatically recognized as a variable and can run normally

raw_input('请输入一个字母:')

insert image description here

Guess you like

Origin blog.csdn.net/ananbai/article/details/119254123