PyCharm shows "PEP8: expected 2 blank lines, found 1" - python-2.7

Consider the following code:
def add_function(a, b):
c = str(a) + b
print "c is %s" % c
def add_int_function(c, d):
e = c + d
print "the vaule of e is %d" % e
if __name__ =="__main__":
add_function(59906, 'kugrt5')
add_int_function(1, 2)
It always shows me: "expected 2 blank lines ,found 1" in aadd_int_function, but not in the add_function.
When I add two spaces in front of the def add_int_function(c, d):
there is a error shows unindent does not match any outer indentation level
in the end of add_function:

Just add another line between your function definitions :
1 line :
2 lines:

This is a pretty common question within the python community. After the release of PEP 8, new formatting styles were accepted into python. One of them states that after the definition of a class or function there must be two lines separating them. As such:
def yadayada:
print("two lines between the functions")
def secondyadayada:
print("this is the proper formatting")
So, you should never do it like:
def yadayada:
print("two lines between the functions")
def secondyadayada:
print("this is the proper formatting")
Or else PyCharm will throw that error at you.

Further clarification on #kennet-celeste & #shreyshrey 's answers,
Each function or class defined requires 2 spaces above and 2 spaces below. Unless the function is the last item in the script, in which the expected format is one blank line as an End of File marker. So:
# some code followed by 2 blank spaces
def function1():
def function2():
def function3():

For people who wonders why it requires two blank lines
if you were to write in other languages it would be:
fun doSth() {
print()
}
fun doSth1() {
print()
}
but if you were to delete all the curly braces from the code you will see:
two blank lines between methods
fun doSth()
print()
#
#
fun doSth1()
print()
#

Related

Use of global variables in script

I threw the 'Apple-code' in the trash, please look at the following code :
# Define processing inputted line
def inputfile(line):
linecontents = { 'item_0110': line[0:8],
'item_0111': line[8:16],
'item_0112': line[16:24] }
print 'In the function : ', linecontents
print 'In the function : ', len(linecontents)
# Set dictionary
linecontents = {}
# Pretend to open a file and read line for line
line = '010012343710203053525150'
# Start processing the read line
inputfile(line)
# Display end resultprint
print '\nOutside the function : ', linecontents
print 'Outside the function : ', len(linecontents)
Ok, first off : I'm an idiot for trying this with vars. In the original post I already stated I have more than thirty items (fields if you want) in the file. To make matters more complex, a line from the file could look like this :
010012343710203053525150
And not all lines have the same fields so depending on what type of field it is, I would like to call a different function.
The question now is : why is the output like this :
In the function : {'item_0112': '53525150', 'item_0111': '37102030', 'item_0110': '01001234'}
In the function : 3
Outside the function : {}
Outside the function : 0
I thought the dictionary is independent from functions and/or classes ?
There are some issues with your code. I don't really see the see for global variables here.
I reformatted and refactored your code (no uppercase except for classes). You intent is not clear so I tried my best. The function read_file actually reads you file line by line and returns customer_name and customer_item line by line.
def read_file(filepath):
with open(filepath) as customer_file:
for line in customer_file:
customer_name = line[:10]
customer_item = line[10:]
print('Name : ' + customer_name)
print('Item : ' + customer_item)
yield customer_name, customer_item
In the main() or whatever function, you can do what you want with the customer's variables.
What is important here, is that read_file actually reads a file and process the information for the file before returning them to the calling function.
def main():
myfile = 'CustomerFile.txt'
for customer_name, customer_item in read_file(myfile):
if customer_item == 'Apple':
print(customer_name)
else:
print(customer_name + ' is not eating an apple')
Instead of using globals, let the ReadFile function return the values
def ReadFile(line):
...
return CustomerName, CustomerItem
and assign them to variables after calling the function:
for line in CustomerFile:
CustomerName, CustomerItem = ReadFile(line)
def ReadFile(line):
CustomerName = line[0:10]
CustomerItem = line[10:]
return CustomerName, CustomerItem
def Report(CustomerName, CustomerItem):
# Try to keep all print statements in one place
print 'Name : ' + CustomerName
print 'Item : ' + CustomerItem
if CustomerItem == 'Apple':
print CustomerName
else:
print CustomerName + ' is not eating an apple'
with open(CustomerFile.txt) as CustomerFile:
for line in CustomerFile:
CustomerName, CustomerItem = ReadFile(line)
Report(CustomerName, CustomerItem)
Note that the PEP8 style guide recommends using lower_case for variable and function names and to reserve CamelCase for classes. While you are free to use your own style, use of PEP8 is quite prevalent and so by joining the PEP8-club your code will more naturally "fit in" with other people's code and vice-versa.
I found the (obvious) answer. As I said, my Python is a bit rusty :
## Define processing inputed line
#
def inputfile(line, linecontents):
linecontents['item_0110'] = line[0:8]
linecontents['item_0111'] = line[8:16]
linecontents['item_0112'] = line[16:24]
print 'In the function : ', linecontents
print 'In the function : ', len(linecontents)
## Define main script
#
def main():
# Set dict
linecontents = {}
# Pretend to open a file and read line for line
line = '010012343710203053525150'
# Start processing the read file
inputfile(line, linecontents)
# Display end resultprint
print '\nOutside the funtion : ', linecontents
print 'Outsude the function : ', len(linecontents)
## Start main script
#
main()
And this neatly returns :
In the function : {'item_0112': '53525150', 'item_0111': '37102030', 'item_0110': '01001234'}
In the function : 3
Outside the funtion : {'item_0112': '53525150', 'item_0111': '37102030', 'item_0110': '01001234'}
Outsude the function : 3

how to exit from multiple loops in python

In my code below, I keep getting an error that I cant tell how to fix it.
See code:
def WordSelector():
global pattern
words = [location]
corpus = " ".join(words)
sentences1 = re.split(r'\.', corpus)
name17 = [name66, name666, name67, name68, name69, name612]
k1 = iter(name17)
keyword = next(k1)
pattern1 = keyword
class LocalBreak(Exception):
pass
try:
for pattern1 in name17:
for sentence in sentences1:
if pattern1 in sentence:
print 'code'
raise LocalBreak()
except LocalBreak:
pass
WordSelector()
I keep getting this error:
"C:\Python27\synonyms3.py", line 72, in LocalBreak
except LocalBreak:
NameError: free variable 'LocalBreak' referenced before assignment in enclosing scope
Whole try/except block is defined inside LocalBreak body, where you cannot reference class itself (since it's definition is not yet done).
Simply indent your code correctly and do your looping in fuction body, not in custom Exception definition scope.
def WordSelector():
global pattern
words = [location]
corpus = " ".join(words)
sentences1 = re.split(r'\.', corpus)
name17 = [name66, name666, name67, name68, name69, name612]
k1 = iter(name17)
keyword = next(k1)
pattern1 = keyword
class LocalBreak(Exception):
pass
try:
for pattern1 in name17:
for sentence in sentences1:
if pattern1 in sentence:
print 'code'
raise LocalBreak()
except LocalBreak:
pass
WordSelector()

python 2.7 - trying to print a string and the (printed) output of function in the same line

I have the following function defined:
def displayHand(hand):
"""
Displays the letters currently in the hand.
For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in hand.keys():
for j in range(hand[letter]):
print letter, # print all on the same line
print '' # print an empty line
Now, I want to print the following:
Current hand: a b c
To do this, I try to do:
print "Current hand: ", displayHand({'a':1, 'b':1, 'c':1})
And I get:
Current hand: a b c
None
I know that None is printed cause I am calling the print function on the displayHand(hand) function, which doesn't return anything.
Is there any way to get rid of that "None" without modifying displayHand(hand)?
if you want to use your function in a print statement, it should return a string and not print something itself (and return None) - as you would do in a __str__ method of a class. something like:
def displayHand(hand):
ret = ''
for letter in hand.keys():
for j in range(hand[letter]):
ret += '{} '.format(letter) # print all on the same line
# ret += '\n'
return ret
or even
def displayHand(hand):
return ''.join(n*'{} '.format(k) for k,n in hand.items() )
When you trail a print with a ,, the next print will appear on the same line, so you should just call the two things on separate lines, as in:
def printStuff():
print "Current hand: ",
displayHand({'a':1, 'b':1, 'c':1})
Of course you could just adapt this and create a method like:
def printCurrentHand(hand):
print "Current hand: ",
displayHand(hand)
The only way to do this (or I believe the only way to do this) is to use return instead of print in your displayhand() function. Sorry if I didn't answer your question.
Your function 'displayHand' does not have to print the output,
it has to return a string.
def displayHand(hand):
mystring=''
for letter in hand.keys():
for j in range(hand[letter]):
mystring+= letter # concatenate all on the same line
return mystring
BUT, you have to check the '.keys' command help as the order of the input (a/b/c) may not be respected

Python Help - Learn Python The Hard Way exercise 41 "phrase = PHRASES[snippet]"

I am learning python - this is my first programming language that I am learning. I am a little confused about one line of the code. The full code can also be found at http://learnpythonthehardway.org/book/ex41.html
import random
from urllib import urlopen
import sys
WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []
PHRASES = {
"class %%%(%%%):":
"Make a class named %%% that is-a %%%.",
"class %%%(object):\n\tdef __init__(self, ***)" :
"class %%% has-a __init__ that takes self and *** parameters.",
"class %%%(object):\n\tdef ***(self, ###)":
"class %%% has-a function named *** that takes self and ### parameters.",
"*** = %%%()":
"Set *** to an instance of class %%%.",
"***.***(###)":
"From *** get the *** function, and call it with parameters self, ###.",
"***.*** = '***'":
"From *** get the *** attribute and set it to '***'."
}
# do they want to drill phrases first
PHRASE_FIRST = False
if len(sys.argv) == 2 and sys.argv[1] == "english":
PHRASE_FIRST = True
# load up the words from the website
for word in urlopen(WORD_URL).readlines():
WORDS.append(word.strip())
def convert(snippet, phrase):
class_names = [w.capitalize() for w in
random.sample(WORDS, snippet.count("%%%"))]
other_names = random.sample(WORDS, snippet.count("***"))
results = []
param_names = []
for i in range (0, snippet.count("###")):
param_count = random.randint(1,3)
param_names.append(', '.join(random.sample(WORDS, param_count)))
for sentence in snippet, phrase:
result = sentence[:]
# fake class name
for word in class_names:
result = result.replace("***", word, 1)
# fake other names
for word in other_names:
result = result.replace("***", word, 1)
# fake parameter lists
for word in param_names:
result = result.replace("###", word, 1)
results.append(result)
return results
# keep going until they hit CTRL-D
try:
while True:
snippets = PHRASES.keys()
# returns a randomly shuffled dictionary keys list
random.shuffle(snippets)
for snippet in snippets:
phrase = PHRASES[snippet]
question, answer = convert(snippet, phrase)
if PHRASE_FIRST:
question, answer = answer, question
print question
raw_input("> ")
print "ANSWER: %s\n\n" % answer
except EOFError:
print "\nBye"
It is the 11th line of code from the bottom that I don't quite understand: phrase = PHRASES[snippet]. Since snippet in for snippet in snippets: is looping through the keys of the randomized-shuffled PHRASES list, why can't the code simply be phrase = snippet. Thanks in advance for any help.
Cheers - Darren
get the value of key"snippet" in the dictionary

Need help counting only certain words (Python) [duplicate]

I have this code, where I am trying to count the number of:
Lines of code in a .py script
for_loops ("for ")
-while_loops ("while ")
if_statements ("if ")
function definitions ("def ")
multiplication signs ("*"
division signs ("/"
addition signs ("+")
subtraction signs ("-")
On the mathematical signs the code works, but when the code is looking for if statements it returns 2, when there is one, which is the main problem, but it makes me think I have written the for loop incorrectly, which could bring up more problems later. As well as this I am not sure how to print the Author line which comes up as [] instead of the name of the Author
The code:
from collections import Counter
FOR_=0
WHILE_=0
IF_=0
DEF_=0
x =input("Enter file or directory: ")
print ("Enter file or directory: {0}".format(x))
print ("Filename {0:>20}".format(x))
b= open(x)
c=b.readlines()
d=b.readlines(2)
print ("Author {0:<18}".format(d))
print ("lines_of_code {0:>8}".format((len (c))))
counter = Counter(str(c))
for line in c:
if ("for ") in line:
FOR_+=1
print ("for_loops {0:>12}".format((FOR_)))
for line in c:
if ("while ") in line:
WHILE_+=1
print ("while_loops {0:>10}".format((WHILE_)))
for line in c:
if ("if ") in line:
IF_+=1
a=IF_
print ("if_statements {0:>8}".format((a)))
for line in c:
if ("def ") in line:
DEF_+=1
print ("function_definitions {0}".format((DEF_)))
print ("multiplications {0:>6}".format((counter['*'])))
print ("divisions {0:>12}".format((counter['/'])))
print ("additions {0:>12}".format((counter['+'])))
print ("subtractions {0:>9}".format((counter['-'])))
The file being read from:
'''Dumbo
Author: Hector McTavish'''
for for for # Should count as 1 for statement
while_im_alive # Shouldn't count as a while
while blah # But this one should
if defined # Should be an if but not a def
def if # Should be a def but not an if
x = (2 * 3) + 4 * 2 * 7 / 1 - 2 # Various operators
Any help would be much appreciated
Instead of treating the source code as a string, use the ast module to parse it and then just walk through the nodes:
import ast
from collections import Counter
tree = ast.parse('''
"""
Author: Nobody
"""
def foo(*args, **kwargs):
for i in range(10):
if i != 2**2:
print(i * 2 * 3 * 2)
def bar():
pass
''')
counts = Counter(node.__class__ for node in ast.walk(tree))
print('The docstring says:', repr(ast.get_docstring(tree)))
print('You have', counts[ast.Mult], 'multiplication signs.')
print('You have', counts[ast.FunctionDef], 'function definitions.')
print('You have', counts[ast.If], 'if statements.')
It's pretty straightforward and handles all of your corner cases:
The docstring says: 'Author: Nobody'
You have 3 multiplication signs.
You have 2 function definitions.
You have 1 if statements.
if ("if ") in line will also count def if #.