Python: "expected indent block" dont know how to fix [duplicate] - python

This question already has answers here:
Why am I getting "IndentationError: expected an indented block"? [duplicate]
(6 answers)
Closed 8 years ago.
Ok, so I have my program but I'm getting an "expected an indent block" and i don't know where it is I believe I have it right but I'm very confused.
##Cave fuction
def cave():
global lvl
global mhp
global exp
while True:
print("Who whould you like to talk to. (Emily(1), James(2), Paco(3)")
talk = int(input("Who to talk to: "))
ptint(" ")
if talk == 1:
#put storie function here
elif talk == 2:
#put train function here
elif talk == 3:
print("Your level is", lvl, "you have", mhp, "and have", exp, "EXP")
else:
amsterdam = 7 #filler
print("Anthing else needed(y/n)")
ant = input("Anthing: ")
if ant == n:
break
else:
mexico = 19 #filler

Put pass (or print statment or anything that executes really) between your if/elif statements. The comments aren't really read as code.

In Python, there is no such thing as empty block like {} in C. If you want block to do nothing, you have to use pass keyword. For example:
if talk == 1:
pass # Put storie function here.
elif talk == 2:
pass # Put storie function here.
This should fix your problem. After line ending with :, next line MUST be intended, and comments do not count to indentation in that respect.

After the condition of if or elif, and after else, an indented block is expected. Something like this:
if condition:
indented_block
elif condition:
indented_block
else:
indented_block
Just a comment as a block:
if condition:
# ...
is not considered, so you have to put something there. One alternative is using a placeholder:
if condition:
pass
pass is a null operation. When it is executed, nothing happens.

You have to put some valid statements inside if-else statements, where you have written put storie function here. Following code will not throw an error as there is some valid statement for each if-else:
def cave():
global lvl
global mhp
global exp
while True:
print("Who whould you like to talk to. (Emily(1), James(2), Paco(3)")
talk = int(input("Who to talk to: "))
ptint(" ")
if talk == 1:
#put storie function here
pass
elif talk == 2:
#put train function here
pass
elif talk == 3:
print("Your level is", lvl, "you have", mhp, "and have", exp, "EXP")
else:
amsterdam = 7 #filler
print("Anthing else needed(y/n)")
ant = input("Anthing: ")
if ant == n:
break
else:
mexico = 19 #filler

you need to enter some statement before the. elif talk == 2:
if talk == 1:
print 1
elif talk == 2:

Your if blocks are empty. Try this
if talk == 1:
pass
#put storie function here
elif talk == 2:
pass
#put train function here
elif talk == 3:
print("Your level is", lvl, "you have", mhp, "and have", exp, "EXP")
else:
amsterdam = 7 #filler

if that's the exact code you're running, your problem should be within:
while True:
print("Who whould you like to talk to. (Emily(1), James(2), Paco(3)")
talk = int(input("Who to talk to: "))
ptint(" ")
if talk == 1:
#put storie function here
elif talk == 2:
#put train function here
here you get the comment #put storie function here which is not evaluated as code so basically what python interprets is:
while True:
print("Who whould you like to talk to. (Emily(1), James(2), Paco(3)")
talk = int(input("Who to talk to: "))
ptint(" ")
if talk == 1:
elif talk == 2:
[…]
whereas it expects:
while True:
print("Who whould you like to talk to. (Emily(1), James(2), Paco(3)")
talk = int(input("Who to talk to: "))
ptint(" ")
if talk == 1:
print("python wants actual code here in an inner block")
elif talk == 2:
print("python wants actual code here in an inner block as well")
[…]
and thus does not compile

Related

How to create a function in Python?

I am new to coding and I am learning python. I’m trying to write a simple program to test my skills, but I’m having some difficulties with it; I want to turn it into a function in order to make the program cleaner, but I get this error: http://prntscr.com/im5pt7
Here is what I want to put inside a function:
name = input(str("\nFull Name: "))
position = input(str("Position at the company: "))
print("\nConfirm Staff Data:\n")
name_confirm = "Name: %s"%(name)
position_confirm = "Position: %s"%(position)
print(name_confirm)
print(position_confirm)
confirmAns = input("Is the information right? (Y/N)")
if confirmAns == "y" or confirmAns == "Y":
message = "\nSearching for %s"%(name)
print(message)
hoursWorked = int(input("Insert hours worked: "))
if hoursWorked <= 0:
print("Please insert a valid number")
elif hoursWorked > 0:
print("\nCalculete Paycheck")
hourRate = int(input("Insert the rate of each hour worked: "))
bonus = input("If a bonus was given insert it here: ")
fine = input("If a fine was given insert it here: ")
print('\n')
payment = hoursWorked*hourRate-int(fine)+int(bonus)
paymentMsg = "Your Payment is: $%d"%(payment)
print(paymentMsg)
elif confirmAns == "n" or confirmAns == "N":
ctypes.windll.user32.MessageBoxW(0, "The software will close to avoid slowness.", "Warning", 1)
else:
print("Please answer with Y or N")
I've tried this but it did not work.
Here is all the code (working but with out the function so I need to copy and paste code): https://pastebin.com/PA9mxMkk
What is happening is that the function as other statements needs to hold it's code into a new indentation level
print('a')
def test(var):
print(var)
not this way
print('a')
def test(var):
print(var)
because this way it will give you the error that you are seeing.
All python code should be indented after the ':' character, in python the indentation should be 4 spaces, or people use the tab key, your code has an issue with indentation which I can't be bothered finding;
for example a 'class'
class this_is_a_class():
#indentation
#code goes here
pass
or a 'for loop' or 'while loop';
numbers = [0,1,2,3,4,5,6,7,8,9]
for number in numbers:
#indentation
print(number)
x = 0
while x < 10:
#indentation
x += 1
print('This is going to print 10 times')
or an 'if statement';
true_boolean = True
if true_boolean:
#indentation
print(True)
or a 'function';
def function():
#indentation
print('You have called a function')
What is actually happening, is python is reading through your code 'Token' by token and 'interpreting' what your code does. But considering you don't know what a function is; gloss over this paragraph.
Now for your question about how functions work. A function is used organize code. You can call a function multiple times, which makes your code more organized and easier to work with, this is why as your code got longer, you ran into this problem; Lets for example say i wanted to print 'hello world' 10 times.
I could write this code on 10 seperate lines;
print("hello world")
print("hello world")
#etc... More chance for error
or I could use a function and call it 10 times;
def say_hello_world():
#indentation
print("hello world")
for each_call in range(0,10):
say_hello_world() #This is the function call
You can also pass 'arguments into a function' for example;
def say_hello(person):
#indentation
print('hello', person)
say_hello('Alex')
Now any words that are in quotations in this answer can be google searched with the word 'python' and you can find out much more about how python works.
I hope this gets you started with python. Although all of these concepts can be used in other programming languages.
The first step which is often difficult in learning python in understanding indentation.
for example.
def hello_world(world):
print("hello ", world)
#your function code goes here.
#you need to indent back to be out of function block.
hello_world("there!")
out: hello there
so in your case it should be like this.
def AnsNo():
name = input(str("\nFull Name: "))
position = input(str("Position at the company: "))
print("\nConfirm Staff Data:\n")
name_confirm = "Name: %s"%(name)
position_confirm = "Position: %s"%(position)
print(name_confirm)
print(position_confirm)
confirmAns = input("Is the information right? (Y/N)")
if confirmAns == "y" or confirmAns == "Y":
message = "\nSearching for %s"%(name)
print(message)
hoursWorked = int(input("Insert hours worked: "))
if hoursWorked <= 0:
print("Please insert a valid number")
elif hoursWorked > 0:
print("\nCalculete Paycheck")
hourRate = int(input("Insert the rate of each hour worked: "))
bonus = input("If a bonus was given insert it here: ")
fine = input("If a fine was given insert it here: ")
print('\n')
payment = hoursWorked*hourRate-int(fine)+int(bonus)
paymentMsg = "Your Payment is: $%d"%(payment)
print(paymentMsg)
elif confirmAns == "n" or confirmAns == "N":
print("working")
else:
print("Please answer with Y or N")
return

I can't seem to run this simple python script

however = ["In converse","On the other hand"]
furthermore = ["To add insult to injury","To add fuel to fire",]
conclusion = ["To ram the point home","In a nutshell"]
def prompt():
answer = str(input("Type either 'however','furthermore' or 'conclusion': "))
return answer
reply()
def reply():
if answer == "however":
print(however)
elif answer == "furthermore":
print(furthermore)
elif answer == "conclusion":
print(conclusion)
else:
prompt()
prompt()
prompt()
What is going on? it just doesnt print when i type in anything
it just skips and doesnt print anything at all
Your reply() function won't be called, because you exit the prompt() function by returning the answer
Here's how this should be done:
however = ["In converse","On the other hand"]
furthermore = ["To add insult to injury","To add fuel to fire",]
conclusion = ["To ram the point home","In a nutshell"]
def prompt():
answer = str(input("Type either 'however','furthermore' or 'conclusion': "))
reply(answer)
return answer
def reply(answer):
if answer == "however":
print(however)
elif answer == "furthermore":
print(furthermore)
elif answer == "conclusion":
print(conclusion)
else:
prompt()
prompt()
prompt()

an if Statement inside an if Statement?

FarmGround=input("Do you want to pat the animal? ") #this is the input
if FarmGround==("Yes") or FarmGround==("yes"): #this is if
print("You patted the animal") #print statement if you patted the animal it will go onto the next if statement
if print=("You patted the animal"):
elif FarmGround==("No") or FarmGround==("no"): #this is elif
print("You didn't patt the animal and it is triggered")
undescribed image
Your code is quite clear. What I understand is you want to ask another question if animal is patted.
FarmGround=input("Do you want to pat the animal? ") #this is the input
if FarmGround=="Yes" or FarmGround=="yes": #this is if
print("You patted the animal")
holy_field = input("Did you clear the field?")
if holy_field.lower() == "yes":
print("Do something else. Don't look at me.")
else:
print("When are you going to do it ?")
elif FarmGround== "No" or FarmGround== "no": #this is elif
print("You didn't patt the animal and it is triggered")
You can indent additional statements, including if statements inside your existing if block, just like you're indented the first print statement. It's not clear from your question what exactly you want to do, so I'll fill in some pseudo-code (which you can replace with whatever you actually want):
FarmGround=input("Do you want to pat the animal? ")
if FarmGround==("Yes") or FarmGround==("yes"):
print("You patted the animal")
some_other_answer = input("Some other question?") # here's more code inside the first if
if some_other_answer == "Foo": # it can include another if statement, if you want it to
print("Foo!")
elif FarmGround==("No") or FarmGround==("no"):
print("You didn't patt the animal and it is triggered")
Indentation matters in python. To nest an if statement in another if statement, just indent it below the first with 4 spaces.
If ( var1 == 1 ):
If ( var2 == 2 ):
print "Both statements are true."

Unable to enter if statement after raw_input

Whenever I call a function within a while loop in my project it will do absolute nothing according to the function just being called and will just continue to refresh the loop like nothing happened.
Here is a simple example I wrote demonstrating the problem. By running the code you will be shown a menu and you will need to enter a choice from the menu. When doing so a few "if" statements will check which option you chose and call and execute the code below them if the choice doesn't belong to any of the statements the menu will just refresh:
#!/usr/bin/env python
import os
import time
def test():
x = True
while True:
if not x:
print "You need to type 1\n"
choice = raw_input("type 1 here: ")
if choice == 1:
print 'Works!\n'
time.sleep(5)
break
else:
x = False
def test2():
print "Test123\n"
try:
while True:
os.system("clear")
menu_choice = raw_input("Enter Choice: ")
if menu_choice == 1:
test()
if menu_choice == 2:
test2()
if menu_choice == 3:
os.system("python")
except:
pass
As stated in the comments, raw_input returns a string and you'll need to cast it. BUT, you'd likely need to catch a ValueError for anything typed not a number.
Instead, you could do this
if choice == '1'
Same for menu_choice

Code is looped again and again

I have the following code:
def begin_game():
print "You landed on planet and see three rooms."
door = int(raw_input("Pick number of door>>>"))
print "You approach and see that you need to enter password..."
password = raw_input("Enter your surname>>>")
if door == 1:
medical_room()
if door == 2:
library()
if door == 3:
basement()
else:
print "No room exists"
begin_game()
begin_game()
When I enter door number, I get medical_room function done but then else statement is executed and code starts again over and over.
My question is why else statement is executed? Shouldn't it stop on if statement, execute inside block and stop?
You need to use elif for the second and third if statements. else only considers the statement immediately before it.
Or since it seems that you're looking for switch statement which does not exist in python you could do something like this:
rooms = {
1: medical_room,
2: library,
3: basement,
}
chosen_room = rooms[door]
chosen_room()
You should be using elif, or else every time you input anything other than 3, the else block will be executed, as door != 3 and the else block only considers the preceding if or elif block.
def begin_game():
print "You landed on planet and see three rooms."
door=int(raw_input("Pick number of door>>>"))
print "You approach and see that you need to enter password..."
password=raw_input("Enter your surname>>>")
if door==1:
medical_room()
elif door==2:
library()
elif door==3:
basement()
else:
print "No room exists"
begin_game()
begin_game()
Currently, your code tests the first if condition (door==1) and associated actions, then it tests the second and third if conditions. Since the third if statement is False (door==1), it will perform the else statement.
You should use elif statements instead of repeated if statements.
def begin_game():
print "You landed on planet and see three rooms."
door=int(raw_input("Pick number of door>>>"))
print "You approach and see that you need to enter password..."
password=raw_input("Enter your surname>>>")
if door==1:
medical_room()
elif door==2:
library()
elif door==3:
basement()
else:
print "No room exists"
begin_game()

Categories