2016-05-24 6 views
0
print("\nINSTRUCTIONS~\nEnter:\n'c' to use a full fledged calculator,") 
    print("'a' to add and subtract numbers " + 
      "(faster than calculator if you just want to add and subtract),") 
    print("'s' to find a number's square root,") 
    print("'p' to see powers,") 
    print("'n' to arrange numbers in ascending and descending order,") 
    print("'f' to calculate factorials,\n'x' to exit the program,") 

私は現在、同じ行に文の "+"を入れていますが、それ以外の場合は別のprint文を作成します。Python:連続した文章に複数のprint文または "+"を使うべきですか?

+0

これは、複数行の文字列に最適です。 –

+0

@MorganThrappは+の意味ですか? –

+0

いいえ、http://stackoverflow.com/questions/2504411/proper-indentation-for-python-multiline-strings –

答えて

3

あなたの質問に答えるために、それらは本質的に同じです。それは本当に読みやすさの問題であり、したがって個人的な好みです。

しかし、もっと便利な方法があります。これはmulti line stringsです。それらは"""で区切られ、本質的に複数の行にまたがることができる文字列です。

print("""Hello, 
world!""") 

が細かく、これを印刷し、一方、例えば、

print("Hello, 
world!") 

は、EOL while scanning string literalを言って、エラーをスローします:

Hello, 
World! 

それがすることになっているとは。


明確化:それは、行継続文字(\)を使用して、同じではありません。プログラマがコードを読むのを助けるために、文字列を壊さずに次の行に移動するだけです。改行は含まれていません。

この:

print("Hello,\ 
world!") 

はこれと同じではありません。

print("""Hello, 
world!""") 

それは彼らが両方とも有効である事実ですが、彼らは異なる結果を持っています。前者は印刷になります。

Hello,world! 

を、後者は印刷している間

Hello, 
world! 

EDIT: のdocstringのためにこれを使用して、人間の可読性のためのものインデント懸念があるだろう余分なタブを追加することでそれに干渉します。例:

# Less easily readable 
def test(): 
    """Docstring 
Docstring""" 
    pass 

# More easily readable 
def otherTest(): 
    """Docstring 
    Docstring""" 
    pass 

これらの2つのドキュメントストリングは全く同じ結果を生成します。 Pythonは先行する空白を無視します。


出典:彼らは同等である速度の点で Proper indentation for Python multiline strings

+0

しかし、docstringsは、私が持っているタブを挿入し、過去に取得する唯一の方法は、行のタブではないが、私は読みやすさを妨げるだろうと感じています。 –

+0

@NeelKamath私の知る限り、その周りに道はない –

+0

@NeelKamath私は答えを編集しました。それは役に立ちますか? –

2

。プログラムの読み取りと保守が最も簡単するのが最も簡単になるものは何でも

text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.' 

size = 5 


def test_multiple_prints(): 
    for _ in range(size): 
     print(text) 


def test_single_print(): 
    big_text = '\n'.join([text for _ in range(size)]) 
    print(big_text) 


%timeit test_multiple_prints() 
#1000 loops, best of 3: 702 µs per loop 


%timeit test_single_print() 
#1000 loops, best of 3: 703 µs per loop 
2

ありません。

関連する問題