Different indentation no error in python - python

password = raw_input("Enter password: ")
if password == "1234":
print "You logged in correctly!"
else:
print "GTFO"
Though i give different indentations the code is working fine i'm unable to figure it out.

it will not be flagged as as IndentationError, sine any block of statement has to have at lease 1 space of indent
here your if and else are two different blocks, so it was indented anyway so the interpreter throws no error
if True:
print
elif True:
print
elif True:
print
elif True:
print
else:
print
This will work without any problem
But if I try the following I will get IndendationError
if True:
print ""
print "" # has different Indentation
print ""

The Python documentation explains indentation. Here's a relevant excerpt:
At the beginning of each logical line, the line’s indentation level is
compared to the top of the stack. If it is equal, nothing happens. If
it is larger, it is pushed on the stack, and one INDENT token is
generated. If it is smaller, it must be one of the numbers occurring
on the stack
In your code, since the indentation level is larger than the top of the stack (which is 0), it is treated as a single indent. The else: line popped 2 off of the top of the stack, so the interpreter has no memory of your previous indentation level of 2. It only knows that it's higher than the 0.
Problems arise when you start mixing indentation within a block:
def foo():
if True:
return True
return False # Is this part of the if statement or not?
When the parser reaches return False, the stack contains [4, 8]. The next line has an indent of 6, which is not contained in the stack and therefore generates an IndentationError.

Related

Indention Errors on Python IDLE

I'm just following the basic's of python and have been using IDLE as I find it handy to experiment scripts in real-time.
While I can run this script with no issues as a file I just cannot include the last print statement in IDLE!. I have tried an indentation, 4 spaces, no indentation's. Please explain what I'm doing wrong.
while True:
print ('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
if password == 'swordfish':
break
print('value')
SyntaxError: invalid syntax
You can type one statement at a time. The while loop considered one with the loop itself, and since the loop is a code block everything in it is okay.
The print at the end however is a new command. You have to run the while loop first and type the print after in the interpreter.
You can't paste more than one statement at a time into IDLE. The problem has nothing to do with indentation. The while loop constitutes one compound statement and the final print another.
The following also has issues when you try to paste at once into IDLE:
print('A')
print('B')
The fact that this has a problem shows even more clearly that the issue ins't one of indentation.
You have an undentation error in line 10, then you need just to add an espace
while True:
print ('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
if password == 'swordfish':
break
print('value')
As others have kindly pointed out python IDLE only allows one block of code to be executed at a time. In this instance the while loop is a 'block'. The last print statement is outside this block thus it cannot be executed.

Return statements acting weird in "if" statements in Python

My question is regarding this statement I read online that went something along the lines of "lines that follow the 'if statement' and are at the same indentation as the "if statement" will always run, regardless whether the 'if statement' is true or false." I'll show that using my examples below.
So I have this procedure that takes in two numbers as inputs and returns the greater of the two inputs.
Therefore, the 4th and 5th lines of code in this first example, which are at the same level of indentation as "if a>b:" should always run according to the statement above.
Example #1
def bigger(a,b):
if a>b:
x = "the first number is bigger"
x = "the second number is bigger"
return x
print bigger(9,7)
Python prints "the second number is bigger," so the code is working according to that original statement I wrote in the beginning. Even though that is false because 9>7.
But where I run into confusion is when return statements are used in the following example:
Example #2
def bigger(a,b):
if a>b:
return "the first number is bigger"
return "the second number is bigger"
print bigger(9,7)
This time, Python prints "the first number is bigger." This is true because 9>7
My confusion: Shouldn't the 4th line of code in this second example, "return "the second number is bigger"", always run because it's at the same indentation level of the "if statement," just like we saw in example #1?
It seems like the two examples of code contradict each other because in the example #1, Python recognizes the "second number is bigger" line and prints that line but in example #2, Python ignores the "second number is bigger" line and prints the other "first number is bigger" line.
I tried to make this as clear as possible. Thanks
My confusion: Shouldn't the 4th line of code in this second example,
"return "the second number is bigger"", always run because it's at the
same indentation level of the "if statement," just like we saw in
example #1?
This is because the function execution breaks when you have a return statement:
def bigger(a,b):
if a>b:
return "the first number is bigger" # function execution breaks here!!!
return "the second number is bigger"
print bigger(9,7)
You might want to read a little a bit about function and what return means.
Very briefly, if a return statement is executed the function goes out of scope and will not run anything after it.
In the first example, first it compares two values 9 and 7, then x = the first number is bigger, then it assigns x= the second number is bigger and return x. It is why you see this line.
In second example, it also compare two values, but it return x immediately, so it doesn't go the the next lines.
I think the "statement that you read" was a bit too simplistic. It is correct only if nothing changes Python's normal control flow during the if statement or the following indented block. It doesn't apply if the control flow is changed, which is exactly what you're doing in your second example. A return statement does change the control flow, to make the function exit immediately, so the rest of the code after the if does not get run.
Other statements that change the control flow are raise (and invalid operations that cause exceptions to be raised without an explicit raise statement), break and continue. The latter two are only valid in loops.

Python code gives none

I am new to python,trying to write program for finding amstrong and modulus . But I have problem in finding amstrong no,it will not go to end state,hang in the middle. However,modulus is working fine. It will not throw any error. Here is my code:
try:
def check(s):
if(s==1):
print 'enter the no'
v=[]
s=int(raw_input())
print s
for x in str(s):
print x
v.append(x)
print v
x=len(v)
i=0
y1=0
print v[0]
while(i<x):
y=int(v[i])
y=y**3
y1=y1+y
print y1
if(y1==s):
print "given no",s,"is amstrong no"
else:
print "given no",s,"is not a amstrong no"
elif(s==2):
print 'enter the 1st no'
s=int(raw_input())
print 'enter the 2nd no'
s1=int(raw_input())
ans=s%s1
print 'modulus ans is',ans
finally:
print "bye bye"
try:
print "1.amstrong 2.modulus"
x=int(raw_input())
if(x>=1 and x<=2):
check(x)
finally:
print 'bye bye'
Please help me on this.
The reason it's hanging in the middle is that you enter into the while loop while(i<x):, but you never change the value of either i or x. (You do change y and y1, but your conditional doesn't involve either.) The condition never ends up being false, and can't ever end up being false, so it continues to execute forever.
Note also that you're not really using try blocks correctly. There's no point in using try unless you're using except to handle any exceptions. (On a different level, you shouldn't be wrapping the entirety of your code in a try block in the first place - exceptions are useful information that make it easier to discover ways your program isn't working correctly, and ignoring them can lead to unpredictable, difficult-to-debug states.)
Last piece of advice - recognizing and fixing your problems is almost universally made easier (for both of us) by using distinct, pertinent names to your variables - it's very difficult to figure out what you're doing when every single variable is a single letter, and some are just a letter you've already used with a number appended.
You can check if a number is a 3-digit ammstrong using the function coded below.
This however is restricted to only 3 digits, but using loops correctly this will work of a greater number of digits as well. Almost in the way you have done. But always remember to increment or decrement the loop counter to prevent infinite loop. Otherwise the loop "will not go to end state,hang in the middle".
def Ammstrong(s):
n1=s/100
#n1 contains the 1st digit of number, s.
n2=s%100
n2=n2/10
#n2 contains the 2nd digit of number, s.
n3=s%10
#n3 contains the 3rd digit of number, s.
number=(n1**3)+(n2**3)+(n3**3)
if number==s:
print number,"is an Ammstron Number"
#return number
else:
print number,"is not an Ammstron Number"
#return number
num=input(Enter a number: ")
Ammstrong(num)
#use this if return is uesd:
#number=Ammstrong(num)
This function will print the answer. So, there wont be any need to use the print function in the main function to print your answer.
If you wish to perform further calculations, use 'return'. This is illustrated in the coded using comments. But, as soon as the return execution is executed, the program in which the statement is executed, terminates. Meaning the function will terminate not the main program. So, use the return function after the print function.
If you do use the return function u'll have to store the returned value in a variable.
One thing more:
You have made use of the variable x before initiating it.
And, instead of using (s==2) statement use (s!=0). "!=" is the symbol for "not equal"
Best of luck with learning python. It is a very interesting language.
http://pythontutor.com will show you the execution of the code step by step.

Unindent error and input number limit

I am making a calculator (using tkinter) and I need to have a limit so if the user enters an input of more than 999, an error message appears and the numbers are not calculated (it is a school project). When I run the script from below, at school it just appears with a blank GUI and on my home computer it says 'unindent does not match any outer indentation level'. How can I solve this?
Thanks
P.S. I am using Python 3.3.2
def calc(self):
try:
self.display.set(self.validate_result(eval(self.display.get())))
self.need_clr = True
except:
showerror('Operation Error', 'Illegal Operation')
self.display.set('')
self.need_clr = False
def validate_result(self, result):
if result >= 1000:
raise ValueError('result too big!')
else:
return result
Python uses indentation to distinguish levels of scope.
Here all your code seems to be entirely indented, so Python thinks all your code is in an inner scope, and tries to find the outer scope that contains it, but there isn't any.
You should try with this indentation :
def calc(self):
try:
...
def calc(self):
try:
...
Edit : also, you seem to have other indentation problems in the second function. You must align except with try, and there is one space missing before if result >= 1000:.

Invalid syntax on if-else statement

Can someone explain why I am getting an invalid syntax error from Python's interpreter while formulating this simple if/else statement? I don't add any tabs myself I simply type the text then press enter after typing. When I type an enter after "else:" I get the error. else is highlighted by the interpreter. What's wrong?
>>> if 3 > 0:
print("3 greater than 0")
else:
SyntaxError: invalid syntax
Python does not allow empty blocks, unlike many other languages (since it doesn't use braces to indicate a block). The pass keyword must be used any time you want to have an empty block (including in if/else statements and methods).
For example,
if 3 > 0:
print('3 greater then 0')
else:
pass
Or an empty method:
def doNothing():
pass
That's because your else part is empty and also not properly indented with the if.
if 3 > 0:
print "voila"
else:
pass
In python pass is equivalent to {} used in other languages like C.
The else block needs to be at the same indent level as the if:
if 3 > 0:
print('3 greater then 0')
else:
print('3 less than or equal to 0')
The keyword else has to be indented with respect to the if statement respectively
e.g.
a = 2
if a == 2:
print "a=%d", % a
else:
print "mismatched"
The problem is indent only.
You are using IDLE. When you press enter after first print statement indent of else is same as print by default, which is not OK. You need to go to start of else sentence and press back once. Check in attached image what I mean.
it is a obvious mistake we do, when we press enter after the if statement it will come into that intendation,try by keeping the else statement as straight with the if statement.it is a common typographical error
Else needs to be vertically aligned. Identation is playing a key role in Python. I was getting the same syntax error while using else. Make sure you indent your code properly

Categories