2017-07-11 7 views
-1

私はPythonの初心者で、以下のコードを理解できません。誰かが実行の流れを説明してください。PYTHON 3.Xにある以下のコードについて説明してください。

質問は数字「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) 
+0

これは、このコードを実行するように見えるものです。 –

答えて

0

それは単に番号を入力するquestion- の作業を行い「N」AND計算「それが変数に入力された番号を格納N + NN + NNN
だから、最初の行』。
次に、次の行では、単にaの値を整数としてn1に渡します。
質問で入力番号NのNNが必要なので、単に%sトークンを使用して文字列として挿入するので、今はaaになり、int()メソッドを使用して整数に変換されます。 3行目と同じです。
次に、印刷行は、3つの値n1、n2、n3の合計を出力します。

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

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

0

コードの公式ドキュメントでより多くを学ぶことができます」再演は、数字の1〜3桁で構成される数字の合計を行う非常に不器用な方法です。

楽しみのためだけに、sumに供給された発電機の理解と、そして3回に同じ桁数/ 1で構成される文字列を生成する文字列の乗算を使用して:

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))) 
関連する問題