Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

syntax - Breaking a line of python to multiple lines?

In C++, I like to break up my lines of code if they get too long, or if an if statement if there are a lot of checks in it.

if (x == 10 && y < 20 && name == "hi" && obj1 != null) 
    // Do things 

// vs

if (x == 10
    && y < 20
    && name == "hi"
    && obj1 != null)
{
    // Do things
}

AddAndSpawnParticleSystem(inParticleEffectName, inEffectIDHash, overrideParticleSystems, mAppliedEffects[inEffectIDHash], inTagNameHash);
// vs
AddAndSpawnParticleSystem(inParticleEffectName, inEffectIDHash, overrideParticleSystems, 
    mAppliedEffects[inEffectIDHash], inTagNameHash);

In Python, code blocks are defined by the tabs, not by the ";" at the end of the line

if number > 5 and number < 15:
    print "1"

Is mutliple lines possible in python? like...

if number > 5 
and number < 15:
    print "1"

I don't think this is possible, but it would be cool!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Style guide (PEP-8) says:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it.

Method 1: Using parenthesis

if (number > 5 and
        number < 15):
    print "1"

Method 2: Using backslash

if number > 5 and 
number < 15:
    print "1"

Method 3: Using backslash + indent for better readability

if number > 5 and 
        number < 15:
    print "1"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...