Home  >  Q&A  >  body text

Questions for beginners learning python. About the difference between %d and %s

First code:

# -*- coding:gb2312 -*-
age=18
print("====================")
print("你的年龄是:%d"%age)

The execution result of the first code:

============Delimiter===========================

Second code:

# -*- coding:gb2312 -*-
age=18
print("====================")
print("你的年龄是:%s"%age)

The execution result of the second code:

============Delimiter===========================

The third code:

# -*- coding:gb2312 -*-
age=input("请输入您的年龄:")
print("您的年龄是:%d"%age)

Execution result of the third code:

============Delimiter===========================

Fourth code:

# -*- coding:gb2312 -*-
age=input("请输入您的年龄:")
print("您的年龄是:%s"%age)

Execution results of the fourth section of code:

my question:

Why in the first and second pieces of code, the execution result is the same whether you write %d or %s, but in the third and fourth pieces of code, whether you write %d or % s execution results are different? What's the problem and why is the third piece of code wrong? (PS: My python version is 3.5.1. The editor I use is Geany)

仅有的幸福仅有的幸福2711 days ago614

reply all(2)I'll reply

  • 漂亮男人

    漂亮男人2017-05-18 10:45:55

    Python is unlike the C language. When declaring variables, you do not need to specify the type. It will automatically determine the type of the variable. All input from the keyboard is of string type and must be converted with int. Go check the variable assignment and you will understand the input and output.

    reply
    0
  • 迷茫

    迷茫2017-05-18 10:45:55

    Input input is a string by default, you need to use %s
    You can use int() to convert it to a number, use %d

    reply
    0
  • Cancelreply