0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

hackerrack Loop処理

Posted at

hackerrankのLOOPのところで躓いたので、その解決方法を残しておこうと思います。

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10

このように式全体を出したいとき

n=int(input())
i=int(input())
n × i = ni

このように定義しても、8や10といった=の後の数字しか出ませんでした。

ではどのようにすれば式全体が出せるでしょうか?

n= int(input().strip())

    for i in range(1,6):
        print("{} x {} = {}".format(n, i, (n*i)))

このように書くことでできます。
詳しく説明すると、
strip()で文字列の前後の空白を取り除きます。
2行目のrange関数では()の中で、変数の初めと終わりの値を定義できます。
そして、{}を使うことで、変数は変えつつ、文字列として出すことができます。
.formatの()の中の引数の順番と{}の中の変数は一致するので、
この場合だと1つ目にはn、2つ目にはi、3つ目にはn*iがが入ります。

以上になります。
何か間違いや指摘があればお願いします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?