请解释PYTHON 3.X中的以下代码?

时间:2017-07-11 07:32:33

标签: python python-3.x

我是Python的初学者,无法理解下面的代码。有人请解释执行流程。

问题是输入数字'N'并计算N + NN + NNN。

  a = int(input("Input an integer : ")) 
  n1 = int( "%s" % a )
  n2 = int( "%s%s" % (a,a) )
  n3 = int( "%s%s%s" % (a,a,a) )
  print (n1+n2+n3)

4 个答案:

答案 0 :(得分:0)

它只是完成问题的任务 - 输入数字'N'并计算'N + NN + NNN
因此,第一行将输入数存储在变量“a”中 然后在下一行中,它只是将a的值作为整数传递给n1 在下一行(因为问题想要输入数字N的NN),它只使用%s标记将其作为字符串插入,因此现在变为aa然后通过使用int()方法将其转换为整数。第3行也是如此 然后打印行只打印三个值n1,n2和n3的总和。

答案 1 :(得分:0)

您的代码执行以下操作。

a = int(input("Input an integer : ")) 
  n1 = int( "%s" % a )
  n2 = int( "%s%s" % (a,a) )
  n3 = int( "%s%s%s" % (a,a,a) )
  print (n1+n2+n3)

第1行 - 显示“输入整数:”并将输入存储在变量a中 第2行 - n1存储变量a的值 第3行第n2行将变量“aa”的值存储为整数 第4行 - n3将变量'aaa'的值存储为整数 第5行 - 它添加n1,n2,n3中的值并打印出来。

这里%s是格式化字符串,它被%符号后的结尾处的值替换。有关详细信息,请访问here

答案 2 :(得分:0)

a = int(input("Input an integer : ")) # takes integer as input and stores it as integer in variable a # consider input as 7
n1 = int( "%s" % a ) # when "%s" will give you result "7" and it is stored in n1 as integer 7 because int() is used as int("7")
n2 = int( "%s%s" % (a,a) ) # similarly when %s is written twice it requires two numbers in this case it is same hence you will get "77" to converted to integer and stored in n2
n3 = int( "%s%s%s" % (a,a,a) ) # just like n2 number is used three times instead of two so you will get n3=777 in this case
print (n1+n2+n3) # as all values of n1,n2 and n3 are integer it can be added 7+77+777 and you will get result 861

你可以通过下面的许多方法实现同样的目标:

a = input("Input an integer : ") # gets any input but if you need validation you can try it using while loop and if condition or try block
aa = a+a # in python when two string are concatnated i.e. "71"+"71" result will be like "7171"
aaa = a+a+a # concatnated three string
print(int(a)+int(aa)+int(aaa)) # Note: if input won't be a number this will throw ValueError

您可以在string formatting

的官方文档中了解更多信息

答案 3 :(得分:0)

您所展示的代码是一种非常笨拙的方法,可以对由数字的1到3位数字组成的数字之和进行处理。

只是为了好玩,将生成器理解提供给sum,并使用字符串乘法生成由相同数字/数字组成的字符串1到3次:

a = input("Input an integer : ")  # python 2 would need raw_input or the result would be incorrect
print (sum(int(a*i) for i in range(1,4)))