This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Why am I getting "IndentationError: expected an indented block"? [duplicate]
(6 answers)
Closed 25 days ago.
for the following code:
if __name__ == '__main__':
min_version = (2,5)
current_version = sys.version_info
if (current_version[0] > min_version[0] or
current_version[0] == min_version[0] and
current_version[1] >= min_version[1]):
else:
print "Your python interpreter is too old. Please consider upgrading."
config = ConfigParser.ConfigParser()
config.read('.hg/settings.ini')
user = config.get('user','name')
password = config.get('user','password')
resource_name = config.get('resource','name')
server_url = config.get('jira','server')
main()
i get error:
else:
^
IndentationError: expected an indented block
You don't have anything in the if side of your if statement. Your code skips directly to the else, while python was expecting a block (an "indented block", to be precise, which is what it is telling you)
At the very least, you need a block with just a 'pass' statement, like this:
if condition:
pass
else:
# do a lot of stuff here
In that case, though, if you really don't ever want to do anything in the if side, then it would be clearer to do this:
if not condition:
# do all of your stuff here
The if must contain one or more statements, e.g.:
if (current_version[0] > min_version[0] or
current_version[0] == min_version[0] and
current_version[1] >= min_version[1]):
pass # <-------------------------------------ADDED
else:
# ...
The pass statement is a placeholder statement that does nothing.
Related
This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 11 months ago.
I'm new to python programming, and as a beginner I want to start by using a code editor,
I choose sublime text 4 but I face this problem,
So help me please !
This is the code :
def return_string(your_string):
if len(your_string) >= 4:
new_string = your_string[0:2] + your_string[-2:]
return new_string
elif len(your_string) == 2:
new_string = your_string * 2
return new_string
elif len(your_string) < 2:
new_string = ""
return new_string
return_string("welcome")**
the expected output is "weme" but I get nothing in sublime text output (when I click Ctrl + B).
When I change return to print the code is executed properly.
By the way the code above works in vscode without any problem.
Python doesn't print outside the REPL normally, unless you explicitly tell it to. Add a call to print on your last line:
print(return_string('welcome'))
This is why adding an explicit print in your function works.
You can store the value into a variable first if you want to use it elsewhere:
result = return_string('welcome')
print(result)
Because "return string" returns a string, you must first save the data in a variable, which you may then use later in the program.
result_string = return_string("welcome")
print(result_string)
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed 3 years ago.
So I'm doing a calculator in python, I have the code for it inside a while loop and a prompt to ask the user if they want to restart the program (that's what the while loop is for) but it does not seem to work properly, am I missing something? I'm kinda new to programming so maybe there is something blatantly wrong that I just don't see. (I did not add the full code but I did import the necessary libraries ("sys" and "math"))
var1 = True
while var1 == True:
op = eval(input("\n Your operation: "))
print(f"\n The result would be: {op}")
var2 = input("\n Would you like to do another operation? If so type yes: ")
if var2 != "yes" or "Yes" or "YES" or "y" or "Y" or "1":
print("\n Ok then, exiting... \n")
sys.exit()
So if the user types, for example, "yes" in the prompt, it should restart the program, but it executes the if statement anyways and closes the program even though the condition for it doesn't apply.
I have tried adding an "else" statement like this:
if var2 != ... :
sys.exit()
else:
print("Restarting...")
But it doesn't seem to work either.
I've also tried doing it the other way around, that is instead of checking if it does not match, check if it does match. Like this:
if var2 == ... :
print("Restarting...")
else:
sys.exit()
But that just gets stuck in the while loop and does not close the program.
I just don't see what's wrong in the code.
The correct way of doing it would be:
if var2.lower() not in ("yes", "1"):
print("Ok then, exiting...")
sys.exit()
You’re logic is backwards you need to exit if it ISNT yes also instead of using or (plus you’re using it incorrectly) use in and instead of typing all the different variations of Yes use star.lower():
var1 = True
while var1 == True:
op = eval(input("\n Your operation: "))
print(f"\n The result would be: {op}")
var2 = input("\n Would you like to do another operation? If so type yes: ")
if var2.lower() not in ("yes", "1"):
print("\n Ok then, exiting... \n")
sys.exit()
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!')
This is the code
GrassFilledX = GrassGenX
GrassFilledY = GrassGenY
GrassFillL = True
while GrassFillL == True:
if gx == hgx or hgx2:
while not crashed:
The error says
while not crashed:
^
IndentationError: expected an indented block
Python expects an indented block after an if statement.
If you want an empty block, use pass:
while GrassFillL == True:
if gx == hgx or hgx2:
pass
while not crashed:
This has the same effect in other languages as an empty pair of braces, like if(condition){}. In Python you're not allowed to leave a block empty, you must at least have an NOP statement, the pass, in the block, to make the program valid.
This is a similar (yet essentially the same) use case of pass.
This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 6 years ago.
Just a little project i'm working on to improve my knowledge.
Curious as to why the program always returns failure, even if the captcha is correctly entered. I assume it has something to do with the results not being stored in memory?
import string
import random
def captcha_gen(size=7, chars=string.ascii_letters + string.digits):
return ''.join(random.SystemRandom().choice(chars) for _ in range(size))
results = print(captcha_gen())
user_input = input("Please enter the captcha code as you see it: ")
if user_input == results:
print("success")
elif user_input != results:
print("failure")
else:
print("error")
Thanks!
results = print(captcha_gen())
print() returns None - it is used to print stuff to the screen. In this case, it is grabbing the output of captcha_gen() and printing it to the screen.
All functions in Python return something - if they don't specify what they return, then it is an implicit None
You want
results = captcha_gen()