i am new to python and i want to write a simple function which will get some input and print it accordingly, something like this
def printer(data):
if data<5:
print('data is less than 5')
else:
print('data is greater than 5')
return;
but when i run this code, i get an
'unexpected indent'
error, what am i doing wrong
As the error points out, you need to indent your code as required by Python language. So after typing if condition1:, hit enter, then hit tab and write your following code.
def printer(data):
if data<5:
print('data is less than 5')
else:
print('data is greater than 5')
return
And don't put a ; at the end of your function, this is not JS.
Welcome to Python! You need to make sure your code is properly indented. Python doesn't use braces to mark sections, instead, it uses indentation. Just like missing a brace in another language, you need to make sure the indentation is right.
def printer(data):
if data<5:
print('data is less than 5')
else:
print('data is greater than 5')
No need for a return if there is no return value, and Python doesn't use semi-colons as end of statement markers.
The unexpected indent in the picture is the initial space before def, as indicated by the red rectangle. (This is an IDLE feature, so I suspect you are using IDLE.)
When you fix that, see AIG's or Rostan's answer.
Related
Hello everyone I have my code almost done but I'm trying to add in some sort of check to avoid errors. But I'm not really understanding what statement would be better to use to test the code. I know there are a few options of either using a loop, if-statement, or try. But here is the code in regards to doing captcha. I need it to run the first set of code which if the captcha doesn't pop up I continue on. But if the captcha does pop up solve it then continue on.
Some times captcha doesnt appear and if I run the whole set of code I get an error because we are expecting captcha to pop up.
Or if the captcha does appear to solve it which would.
I would really appreciate any help please as I'm not sure the right statement to use.
try should be used when something would return an error and would otherwise cause your program to stop/crash. An example of this would be:
try:
import pandas
except:
print("Unable to import pandas. Module not installed")
In this example your program will attempt to import the pandas module. If this fails it will then print out a line of text and continue running.
if statements are used to decided when to do something or not based on the returned logic. The key difference is that logic IS returned and not an error.
if x > 10:
print("This is a large number")
else:
print("This is a small number")
With this example, if 'x' did not exist it would produce an error, no more code will be executed, and the program will crash. The main difference between IF and TRY is whether logic is returned as true/false or is something just plains fails.
With your specific example it is important to know if the captcha appearing or not will break your code. Does the logic boil down to captcha = false or does captcha not exist at all and logic fails entirely?
Q: How do you define sometimes captcha doesn't appear (1%, 20%, 50%, ...)?
A: Maybe 5% of the time captcha doesn't appear.
In this case, I prefer to use Exception handling: do stuff and if something goes wrong, fix it
try:
# > 95% of the time the code below works when the captcha appears
except SomeException:
# < 5% of the time the code is called when the captcha doesn't appear
IMHO, you have not really 2 different codes: you have one and a fallback solution, it's really different than:
if x % 2:
...
else:
...
I can't seem to find what's wrong. It gives me no error message, but instead just ends the process without printing the wanted message
def choose_chracter_class():
character_class_option = raw_input()
return character_class_option
if character_class_option is str("mage") or str("Mage"):
print "Mage, sorcerers who wield mass amounts of magic energy to cause havoc among their opponents, summon entities, or protect themselves from harm."
print "Attack - 5"
print "Magic Atk - 30"
print "Defence - 10"
print "Magic Def - 15"
print "Speed - 10"
if chracter_class_option is str("warrior") or str("Warrior"):
print "Warrior"
else:
print character_class_option + " isn't an option"
choose_chracter_class()
I agree with the previous comment that one issue is the return on the second line preventing the remaining code from executing. I also agree with the previous comment that using the .lower() would probably be cleaner code then checking for both the situations of lowercase 'mage' and the first letter being capital 'Mage'. By using .lower() you don't need to check both situations of 'mage' and 'Mage' as no matter how it is typed even if it is typed like: 'mAgE' then the code would still work.
However, I have one idea to get the code to work in a similar way that you have it set up.
You could also try:
if character_class_option == "mage" or character_class_option == "Mage"
In addition, I don't think it is necessary use str() on something that is already a string. However, I can understand you may have done this in an attempt to debug.
I am studying Python using a book. But there is an example code I don't understand:
from time import sleep
for i in range(100):
msg = '\rProgress %d%%' %(i+1)
print(' '*len(msg), end='') #I don't understand this statement.
print(msg, end='')
sleep(0.1)
Actually, I commented out that statement, I got the same result.
Why do I need that statement?
It is meant to print a series of spaces, to make sure the previous line is cleared.
In this specific case, that'll never happen, because the message printed will only grow longer (going from 0% to 99%). Moreover, the number of spaces is based on the new message, which would be too short if the previous message was longer.
So no, it is not needed here, you found an error in the book.
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
I've been trying to print out the progress of a for loop in python2.7 using the following code:
for i in range(100):
if float(i) % 10.0 == 0:
print i, "\r",
The behaviour I'm after is the refreshing of the same line on std out rather than writing to a new line every time.
EDIT 1:
Testing in my console (Xfce Terminal 0.4.8), I actually don't get any output regardless of whether I include the if statement or not.
Why is there no output?
I originally said the behaviour of the stdout changed depending on the if statement being there or not because I simplified the code that produced the problem to its most simple form (only to produce the above mentioned effect). My apologies.
EDIT 2:
Thanks to senderle, this is solved. If you miss out the sleep() command, the prints and carriage return happen so quickly you can't see them.
EDIT 3:
One last thing. If you don't catch for the final number in range(100), i.e. 99, the number is cleared off the screen.
EDIT 4:
Note the comma after print i in senderle's answer.
I have found that using sys.stdout is a more system-independent way of doing this, for varions reasons having to do with the way print works. But you have to flush the buffer explicitly, so I put it in a function.
def carriage_return():
sys.stdout.write('\r')
sys.stdout.flush()
This is kind of a WAG. Let me know if it helps.
I tried this and it works for me. The time.sleep is just for dramatization.
import sys, time
def carriage_return():
sys.stdout.write('\r')
sys.stdout.flush()
for i in range(100):
if i % 10 == 0:
print i,
carriage_return()
time.sleep(1)
Finally, I have seen people do this as well. Using terminal control codes like this seems right in some ways, but it also seems more brittle to me. This works for me with the above code as well (on OS X).
def carriage_return():
if sys.platform.lower().startswith('win'):
print '\r'
else:
print chr(27) + '[A'
Testing your code as is, and just including a :colon: at the end of the first line, works just fine with Py2.7 32bit, Windows7 64-bit.
Do you have any out writes to stdout in your if or for block that could be causing the new-lines to be written out ?