Python: Where does if-endif-statement end? - python

I have the following code:
for i in range(0,numClass):
if breaks[i] == 0:
classStart = 0
else:
classStart = dataList.index(breaks[i])
classStart += 1
classEnd = dataList.index(breaks[i+1])
classList = dataList[classStart:classEnd+1]
classMean = sum(classList)/len(classList)
print classMean
preSDCM = 0.0
for j in range(0,len(classList)):
sqDev2 = (classList[j] - classMean)**2
preSDCM += sqDev2
SDCM += preSDCM
return (SDAM - SDCM)/SDAM
I would like to convert this code to VB.NET.
But I am not sure where the if-elseif-statement ends.
Does it end after "classStart += 1"?
I feel it a bit difficult to see where the for-next-loops end as well in Python.
The code is taken from http://danieljlewis.org/files/2010/06/Jenks.pdf
Thank you.

Yes. Python uses indentation to mark blocks. Both the if and the for end there.

In Python, where your indented block ends, that is exactly where your block will end. So, for example, consider a bit simpler code:
myName = 'Jhon'
if myName == 'Jhon':
print(myName * 5)
else:
print('Hello')
Now, when you run this code (make sure to run it from a separate module, not from the interactive prompt), it will print 'Jhon' five times (note that Python will treat the objects exactly as they are specified, it won't even bother to try to convert the variable myName's value to a number for multiplication) and that's it. This is because the code block inside of the if block is only executed. Note that if the else keyword was put anywhere but just below the if statement or if you had mixed the use of tabs and spaces, Python would raise an error.
Now, in your code,
for i in range(0,numClass):
if breaks[i] == 0:
classStart = 0
else:
classStart = dataList.index(breaks[i])
classStart += 1
See, where the indent of for's block of code starts? One tab, so, everything indented one tab after the for statement, will be inside of the for block. Now, obviously, the if statement is inside of the for statement, so it's inside the for statement. Now, let's move to next line, classStart = 0 -- this is indented two tabs from the for statement and one tab from the if statement; so it's inside the if statement and inside the for block. Next line, you have an else keyword indented just one tab from the for statement but not two tabs, so it's inside the for statement, and not inside the if statement.
Consider putting curly-braces like these if you have coded in another language(s) before:
for i in range(0,numClass)
{
if breaks[i] == 0
{
classStart = 0
}
else
{
classStart = dataList.index(breaks[i])
classStart += 1
}
}
The simple differences are that you are not required to put parenthesis for your expressions, unless, you want to force operator precedence rule and you don't need those curly braces, instead, just indent them equally.

for i in range(0,numClass):
if breaks[i] == 0:
classStart = 0
else:
classStart = dataList.index(breaks[i])
classStart += 1
# end if

That is right. In Python, the indentation delimitates your condition block, differently from e.g., Matlab, where you would have to insert an "end" to mark the block's end. I like both ways though!

Related

using else in basic program getting error: unindent does not match any outer indentation level

When I run the following code, I get an error: "IndentationError: unident does not match any outer indentation level".
What am I doing wrong? I've included my code below for reference:
file=open('csquetionseasy.txt','r')
print(file.read(432))
answersinputeasy=input('enter the letter responding to the correct answer for all 3 questions e.g. BBB')
if answersinputeasy==('BAA'):
print('you got 3/3!')
else:
if answersinputeasy==('BAB'):
print('2/3!')
else:
if answersinputeasy==('BBB'):
print('1/3!')
else:
if answersinputeasy==('ABB'):
print('0/3!')
else:
if answersinputeasy==('AAB'):
print('1/3!')
else:
if answersinputeasy==('AAA'):
print('2/3!')
else:
if answersinputeasy==('ABA'):
print('1/3!')
Use elif rather than else. You need else statement to do something when if and elif statements evaluate to false.
if answersinputeasy==('BAA'):
print('you got 3/3!')
elif answersinputeasy==('BAB'):
print('2/3!')
elif answersinputeasy==('BBB'):
print('1/3!')
elif answersinputeasy==('ABB'):
print('1/3!')
elif answersinputeasy==('AAA'):
print('2/3!')
elif answersinputeasy==('ABA'):
print('1/3!')
else:
print('Invalid Input')
Also, if you want to indicate a block of code, you must indent each line of the block by the same amount, which is typically four spaces.
The reason that you are getting the error "IndentationError: unident does not match any other indentation level" is because you are chaining tabs together to create a nested logic statement (in pseudo-code):
if <condition>:
#then do something
else if <condition>:
#then do something else
else if <condition>
#then do something further else
This is not how Python likes to see syntax in a logical block. Additionally, the next error you're going to run into will surround the use of nested if statements inside of else clauses.
To run an else if statement in Python, you will want to use the syntax elif: followed by an indented line with the code that you want to execute if that condition is met (in pseudo-code):
if <condition>:
#then do something
elif <condition>:
#then do something else
elif <condition>:
#then do something further else
One other call out as a best practice, is that you should include an explicit else clause in a conditional block with a bunch of elif statements if you're not going to do any further validation on the string you're getting from the user. Imagine that the user passed in XYZ. They wouldn't meet any of the conditions you've defined, and because of that the code would just continue out of the bottom of this logic block (which may or may not be a good thing). In the following code, I've added an example of what an explicit else clause might look like, but it's up to you to ultimately decide what might make sense for your application:
file=open('csquetionseasy.txt','r')
print(file.read(432))
answersinputeasy=input('enter the letter responding to the correct answer for all 3 questions e.g. BBB')
if answersinputeasy==('BAA'):
# Code to be executed following an if-statement must be indented by 4 spaces:
print('you got 3/3!')
elif answersinputeasy==('BAB'):
# Code to be executed following an elif-statment (else-if) must be indented by 4 spaces:
print('2/3!')
elif answersinputeasy==('BBB'):
print('1/3!')
elif answersinputeasy==('ABB'):
print('0/3!')
elif answersinputeasy==('AAB'):
print('1/3!')
elif answersinputeasy==('AAA'):
print('2/3!')
elif answersinputeasy==('ABA'):
print('1/3!')
# Else clause would provide a default condition that executes if none of the prior cases are met.
else:
# Code following an else statment must be indented by 4 spaces:
#Example of a default Else-block entry:
print('Wasn\'t able to parase your entry into a valid answer!')

Syntax error when adding to a variable in a while true loop

So I'm new to python, and I was just messing around with some code I made and it kept giving me a syntax error when I try to run it. I couldn't find anything on it so I assume its very simple but I can't figure it out. help pls.
factor = 1;
ness = "yes";
while True: {
factor += 1
print (ness*factor)
}
Python doesn't use {} for control constructs. Just remove the braces and the semicolons, and you'll be fine.
There is no semicolon in python statements and no braces in the loops
your code doesn't check any condition it will lead to a indefinite loop. just change the code
factor = 1
ness = "yes"
while factor<=10:
factor += 1
print (ness*factor)
and the output is
yesyes
yesyesyes
yesyesyesyes
yesyesyesyesyes
yesyesyesyesyesyes
yesyesyesyesyesyesyes
yesyesyesyesyesyesyesyes
yesyesyesyesyesyesyesyesyes
yesyesyesyesyesyesyesyesyesyes
yesyesyesyesyesyesyesyesyesyesyes

Continue and break statement doing the same thing

This is my 2nd noob question for today... so bear with me. So this is supposed to loop through 'nothing' and 'persp' while still renaming/printing After:[u’concrete_file1’] because of the continue; statement, but I just get empty brackets. I ran the same function without this:
if not (maya.cmds.ls(texture) and
maya.cmds.nodeType(texture)=='file'):
continue;
And without 'nothing' and 'persp' and it worked fine so I'm assuming the problem is in there somewhere, but after fiddling with it for a while I still don't know what it is... This'll probably be some super simplistic answer but I'm on day 2 of learning this stuff so ¯\_(ツ)_/¯
def process_all_textures(**kwargs):
pre = kwargs.setdefault('prefix');
if (isinstance(pre, str) or
isinstance(pre, unicode)):
if not pre[-1] == '_':
pre += '_';
else: pre = '';
textures = kwargs.setdefault('texture_nodes');
new_texture_names = [];
if (isinstance(textures, list) or
isinstance(textures, tuple)):
for texture in textures:
if not (maya.cmds.ls(texture) and
maya.cmds.nodeType(texture)=='file'):
continue;
new_texture_names.append(
maya.cmds.rename(
texture,
'%s%s'%(pre, texture)
)
);
return new_texture_names;
else:
maya.cmds.error('No texture nodes specified');
#Should skip over the 2 invalid objects ('nothing' & 'persp')
#because of the continue statement...
new_textures= [
'nothing',
'persp',
maya.cmds.shadingNode('file', asTexture=True)
];
print ('Before: %s'%new_textures);
new_textures = process_all_textures(
texture_nodes = new_textures,
prefix = 'concrete_'
);
print ('After: %s'%new_textures);
Before: ['nothing', 'persp', u'file1']
After: []
Also I'm just using the Maya Script Editor to write all this, is there a better editor that might be easier?
Include an else to make the statements after continue; run when if not (maya.cmds.ls(texture) and maya.cmds.nodeType(texture)=='file'): is not true.
What happens here, is that there is only that one condition. Whenever that is true, it evaluates continue; and skips the rest of the statements. However, whenever that is not true, it also skips new_texture_names.append(maya.cmds.rename(texture, '%s%s'%(pre, texture))); because that is inside the if condition.

Copy and paste Python functions in Emacs

I have a program that looks something like (this is a silly example to illustrate my point, what it does is not very important)
count = 0
def average(search_term):
average = 0
page = 0
current = download(search_term, page)
while current:
def add_up(downloaded):
results = downloaded.body.get_results()
count += len(results)
return sum(result.score for result in results)
total = average*count
total += add_up(current)
average = total/count
print('Average so far: {:2f}'.format(average))
page += 1
current = download(search_term, page)
If I have the cursor on any of the lines 8–11 and press a key combination I want Emacs to copy or kill the add_up function, and then I want to move the cursor to line 2 and press a key combination and paste the function there, with the correct level of indentation for the context it is pasted in.
Is this possible, and if so, how would I do that?
With python-mode.el py-kill-def and yank would do the job.
However, there are some restrictions. py-kill-def must be called from inside def in question. So needs to go upward from line 11 first.
Also indenting after insert poses some problems: as indent is syntax, sometimes Emacs can't know which indentation is wanted. In example below have an indent of 4 first and of 8 in add_up probably is not wanted - however it's legal code. After indenting first line in body of add_up, py-indent-and-forward should be convenient for the remaining.
def average(search_term):
average = 0
def add_up(downloaded):
results = downloaded.body.get_results()
count += len(results)
return sum(result.score for result in results)
page = 0
current = download(search_term, page)
while current:
total = average*count
total += add_up(current)
average = total/count
print('Average so far: {:2f}'.format(average))
page += 1
current = download(search_term, page)
For this type of thing I usually use expand-region, which I choose to bind to C-=.
Using your example I can select the add_up() function by pressing C-= once, kill the region normally (C-k), move to line 2, and yank as usual (C-y).
Depending on what else you have configured for Python you may have to clean up some whitespace, or it may get cleaned up for you. For example, aggressive-indent would be helpful.
One manual option would be to reindent the pasted code with something like C-x C-x M-\.
I've been using smart-shift (available in Melpa) for this sort of thing. global-smart-shift-mode to enable (beware, it binds keys). Select the block you want to move (I'd use expand-region like Chris), and the default keybind C-S-c <arrow> starts moving it. Once you're shifting, the arrows (without C-S-c) shift further. Horizontal shifts use the major mode's indent offset (python-indent-offset for python.el).

If vs. else if vs. else statements?

Are:
if statement:
if statement:
the same as
if statement:
elif statment:
and
if statement:
else statement:
the same?
If not, what's the difference?
No, they are not the same.
if statement:
if statement:
If the first statement is true, its code will execute. Also, if the second statement is true, its code will execute.
if statement:
elif statment:
The second block will only execute here if the first one did not, and the second check is true.
if statement:
else:
The first statement will execute if it is true, while the second will execute if the first is false.
The first one is different
if True:
print 'high' #printed
if True:
print 'low' #printed
than the second
if True:
print 'high' #printed
elif True:
print 'low' #not printed
and the third is invalid syntax
See tutorial.
Statement like if , else and else if are used in almost all programming languages to take a decision by the machine or software like Chrome ,Firefox and some other software....
if will be written initially in the if statement code.
else if will be executed if code if is not true.
else will be executed if none of them are true.
Below example will gives you more understanding about it.
if( something is true ){ // execute this code; }
else if( if previous condition is not true){ // then execute this code;}
else { //if none of the above are true finally execute this code. }
you can use number of else if statements between if and else, like example shown above also in the below. And remember "if" statement should start with if and ends with else
here I declared if code in two different ways.
below examples written in JavaScript ( concept apply same with Python )
Remember :
`elif` in (python) --same as-- `else if` in ( Java Script ).
print() in (python) --and-- document.write() in ( Java Script ).
Example 1:
var a=10; // declared variable with value `10`
if(a==20){ document.write("Twenty"); }
//above code is false because "a" value is not 20
else if(a==10){ document.write("Ten"); }
//above is true output comes as "Ten" a==10 //true
else if(a==10){ document.write("Forty"); }
// above also true because "a" is equal to 10 but it won't print in console
else{ document.write("None of them are correct!"); } //also not printed.
In the code above we declared var a=10 and else if a==10 is true in 2 cases, but "Ten" will be printed in console. And rest of the code will not be executed (or) run.
we can do it another way, we declare it with all if statements like below.
Example 2:
var a = 10;
if(a==10){ document.write('ten'); } // it will be printed because condition is `true`;
if(a==20){ document.write('twenty') } // not printed `false`
if(a==10){ document.write("hundred") } // this also `true` therefore printed in console.
else{ //document.write("none")} // not printed because `false`
Difference explained here.
in the " 1st example " we write code with if and else if statements , where code was terminated, because condition is true at-least one time. And rest of the code will not be executed even the condition is true.
In the "2nd example" we write code with all if statements, the code was executed in all cases and prints all true conditions in console, but in the 1st example it was not printed.
if statement:
if statement:
It is like individual conditions; each if statement is checked one after another.
The same as:
if statement:
elif statment:
It is like: the first if condition failed then check the next after the condition.
And:
if statement:
else statement:
It is like: Check the first if condition, and then execute the else block.
no, not the same.
if statement:
if statement:
second if executes whether first if executed or not.
if statement:
elif statment:
elif only executes if first if passes the statement to it. you can have any number of elif statements.
if statement:
else statement:
this is nearly same as if and elif statement. if first if condition doesn't satisfy the requirements, then it passes to the else which can be happen if the conditions not satisfied.
They are not the same. if executes if the condition is True, elif executes if the if is false and the elif is true, and else executes if the if is false.
Example:
if True:
print('This will be printed') #This will be printed
if True:
print('This will also be printed') #This will also be printed
if True:
print('This will be printed') #This will be printed
elif True:
print('This will not be printed')
if False:
print('This will not be printed')
else:
print('This will be printed') #This will be printed

Categories