Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unless statement in Python

Tags:

python

Is there an equivalent to the unless statement in Python? I do not want to append a line to a label if it has p4port in it:

for line in newLines:
    if 'SU' in line or 'AU' in line or 'VU' in line or 'rf' in line  and line.find('/*') == -1:
        lineMatch = False
    for l in oldLines:
        if '@' in line and line == l and 'p4port' not in line:
            lineMatch = True
            line = line.strip('\n')
            line = line.split('@')[1]
            line = line + '<br>\n'
            labels.append(line)
    if '@' in line and not lineMatch:
        line = line.strip('\n')
        line = line.split('@')[1]
        line="<font color='black' style='background:rgb(255, 215, 0)'>"+line+"</font><br>\n"
        labels.append(line)

I get a Syntax error:

   if '@' in line and not lineMatch:
   UnboundLocalError: local variable 'lineMatch' referenced before assignment
like image 863
user1795998 Avatar asked Nov 12 '12 09:11

user1795998


People also ask

What is and %% in Python?

The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand.

How do you write a conditional statement in Python?

If Statement The statement can be a single line or a block of code. #If the condition is true, the statement will be executed. num = 5 if num > 0: print(num, "is a positive number.") print("This statement is true.") #When we run the program, the output will be: 5 is a positive number. This statement is true.


2 Answers

What about 'not in'?:

if 'p4port' not in line:     labels.append(line) 

Also i guess that you code can be modified then to:

if '@' in line and line == l and 'p4port' not in line:     lineMatch = True     labels.append(line.strip('\n').split('@')[1] + '<br>\n') 
like image 57
Artsiom Rudzenka Avatar answered Oct 02 '22 00:10

Artsiom Rudzenka


There's no "unless" statement, but you can always write:

if not some_condition:     # do something 

There's also the not in operator as Artsiom mentioned - so for your code, you'd write:

if '@' in line and line == l:     lineMatch = True     line = line.strip('\n')     line = line.split('@')[1]     line = line + '<br>\n'     if 'p4port' not in line:         labels.append(line) 

... but Artsiom's version is better, unless you plan to do something with your modified line variable later.

like image 34
Zero Piraeus Avatar answered Oct 02 '22 01:10

Zero Piraeus