Giter VIP home page Giter VIP logo

intermediatepython's Introduction

Intermediate Python Book Cover

Intermediate Python

Python is an amazing language with a strong and friendly community of programmers. However, there is a lack of documentation on what to learn after getting the basics of Python down your throat. Through this book I aim to solve this problem. I will give you bits of information about some interesting topics which you can further explore.

The topics which are discussed in this book will open your mind to some nice corners of Python language. This book is an outcome of my desire to have something like this when I was beginning to learn Python.

If you are a beginner, intermediate or even an advanced programmer there is something for you in this book.

Please note that this book is not a tutorial and does not teach you Python. The topics are not explained in-depth and only the minimum required information is given.

I am sure you are as excited as I am. So, let’s start!

Note: This book is a work in progress. If you find anything which you can further improve (I know you will find a lot of stuff) then kindly submit a pull request. :)

Moreover, if you want to add more content to this book then kindly submit a pull request and I will be more than happy to merge it. 👍


Note: If you want to tip me for my work then you can buy the donation version of this book from Gumroad. Apart from that, if this book somehow helps you then kindly share your experience with me. I would really appreciate it.


Table of Contents:

  1. Programmer tools
  2. Syntax
  3. Functional programming
  4. Data structures
  5. Data types
  6. Decorators
  7. Extras

Author:

Acknowledgement:

He wrote the chapter on Open function. Thanks Philipp! 👍

Translation:

If you want to translate this book in any other language then kindly let me know. I would love your contribution. The currently translated versions are listed below:

License:

This book is released under the following CC license (CC BY-NC-SA 4.0).

If you end up using/recommending this book to someone then kindly let me know. 😄

intermediatepython's People

Contributors

bbishop423 avatar bgroff avatar davidawad avatar faichou avatar gabycasper007 avatar joshmccullough avatar jpastuszuk avatar kwpolska avatar lancelote avatar larsclaussen avatar liquiddandruff avatar mafrasi2 avatar mahanmarwat avatar mathur avatar nbasu02 avatar phihag avatar romza avatar sanketdg avatar saurvs avatar seanplusplus avatar shazeline avatar ssundarraj avatar ssword avatar stevenmaude avatar stevestar888 avatar sudipidus avatar tscizzle avatar vshih avatar williamscott avatar yasoob avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

intermediatepython's Issues

9.Mutation Typo found

Second example

foo = ['hi']
print(foo)
# Output: ['hi']

bar = foo
bar += ['bye']

print(foo)
# Output: ['hi'] 
***#THE OUTPUT HERE SHOULD BE ['hi', 'bye']***

print(bar)
# Output: ['hi', 'bye']

Request: async/await programming?

Hi!

Thanks for a great resource.

I recently started to learn async programming in Python and noticed there's a lot of room for new patterns - exception handling, mixing async and sync and reading state, context managers... any chance you'd write a bit about it, preferably things that aren't trivially found when one writes "python async" in Google?

Add @coroutine decorator to Coroutines

After reading through the presentation by David Beazley (the link at the bottom of your coroutines page), I noticed he wrote a nice decorator to help set up a coroutine. It looks like this:

def coroutine(func):
    def start(*args,**kwargs):
        cr = func(*args,**kwargs)
        cr.next()
        return cr
    return start

@coroutine
def grep(pattern):
    ...

You may want to add in reasons why people would use coroutines. For example, as part of a pipeline or filter. Slides 2-23 of David Beazley's presentation may be useful to help with examples and explanations.

I'd be interested to see what other uses for coroutines you find, especially since this is the first time I've seen them in Python.

A potential typo and missing link (or misplaced text)

On this link under the "Iterable" heading, there is this line: "(Both of these dunder methods are fully explained in a previous chapter)". Here I think 'dunder' is obviously a typo and this link is perhaps either copy/pasted from somewhere else or misplaced because there isn't any previous chapter that focuses on these two topics.

License?

What license is this book under?

for else

for some condition:
    ;lkasdj;flk
else:
    ;alksdflkj

and

for some condition:
    ;alksdjf
;alskdfj

works the same don't it

Wrong examples in the decorators topic.

class logit(object):
    def __init__(self, logfile='out.log'):
        self.logfile = logfile

    def __call__(self, func):
        log_string = func.__name__ + " was called"
        print(log_string)
        # Open the logfile and append
        with open(self.logfile, 'a') as opened_file:
            # Now we log to the specified logfile
            opened_file.write(log_string + '\n')
        # Now, send a notification
        self.notify()

    def notify(self):
        # logit only logs, no more
        pass
def logit(logfile='out.log'):
    def logging_decorator(func):
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            log_string = func.__name__ + " was called"
            print(log_string)
            # Open the logfile and append
            with open(logfile, 'a') as opened_file:
                # Now we log to the specified logfile
                opened_file.write(log_string + '\n')
        return wrapped_function
    return logging_decorator

In these examples a func will not called.

collections.rst

Typo: "One another very important use case is when you are appending to nested lists..."

should be "One other..."

Improve "Multiple return Values" section

There is no such thing as returning separate values from a function. The last example of the "Multiple return values"-section returns a tuple and is equal to the previous example. This can be easily verified with calling "type" on it:

def profile():
    name = "Danny"
    age = 30
    return name, age

print(type(profile()))
# <class 'tuple'>

The last example does not return multiple values, but uses (tuple-)unpacking to assign it to "name" and "age". This would also work when a list is returned:

Example 1

def func1():
    return [1, 2]

a = func1()
b, c = func1()

print(a, type(a))
# [1, 2] <class 'list'>
print(b, c, type(b))
#1 2 <class 'int'>

Example 2

def func2():
    return (1, 2)

a = func2()
b, c = func2()

print(a, type(a))
# (1, 2) <class 'tuple'>
print(b, c, type(b))
#1 2 <class 'int'>

Example 3

def func3():
    return 1, 2

a = func3()
b, c = func3()

print(a, type(a))
# (1, 2) <class 'tuple'>
print(b, c, type(b))
#1 2 <class 'int'>

This is exactly the same as Example2; only the tuple creation was implicit.

Namedtuple as return value

A nice way to return multiple values are named tuples. They can be used as plain tuples, or with the additional semantic namedtuples offer:

from collections import namedtuple                                                                                     
def func5():
    Person = namedtuple('Person', 'name age')
    return Person(name="Danny", age=31)

# Use as namedtuple
p = func5()
print(p, type(p))
# Person(name='Danny', age=31) <class '__main__.Person'>
print(p.name)
# Danny
print(p.age)
#31

# Use as plain tuple
p = func5()
print(p[0])
# Danny
print(p[1])
#31

# Unpack it immediatly
name, age = func5()
print(name)
# Danny
print(age)
#31

Also Interesting in this context

You might also want to include Extended Iterable Unpacking (PEP3132: https://www.python.org/dev/peps/pep-3132/) maybe in a dedicated variable unpacking section.

def func4():
    return 1,2,3,4,5

a, *b, c = func4()
print(a)
#1
print(b, type(b))
# [2, 3, 4] \<class 'list'\>
print(c)
#5

print(type(func4()))
#  <class 'tuple'>

Note that b is a list even though we return a tuple.

Good job and keep writing!

Hi there!

Just stumbled across the book and wanted to say - nicely done! Thank you for it, bookmarked the book site, this repo and your blog. :-)

Good luck out there and feel free to close this!

Have a :token-of-appreciation:! 💯 :-)

Of course, while the above is mainly for @yasoob I still am thankful to all the others who have put in their work and made it happen. Thank you guys as well!

pprint same as print

http://book.pythontips.com/en/latest/one_liners.html

The example given for pprint is less than compelling because the output is the same as print

from pprint import pprint

my_dict = {'name': 'Yasoob', 'age': 'undefined', 'personality': 'awesome'}
pprint(my_dict)
{'age': 'undefined', 'name': 'Yasoob', 'personality': 'awesome'}

print(my_dict)
{'age': 'undefined', 'name': 'Yasoob', 'personality': 'awesome'}

Translation

Hi,
Do we have permission to translate this book? would you publish translation in original site?

Ternary Operators

This works simply because True == 1 and False == 0,

I think it's not fully correct for Python 2.x, because you can change value for True and False there.
This was changed in Python 3.x
https://wiki.python.org/moin/Python3.0

Make True and False keywords. [6]

Reason: make assignment to them impossible. 

typo

file: exceptions
the final example, the output of the else clause is

This would noly run if no exception occures. And an error here would NOT be caught.
your output is:
This would noly run if no exception occures.

4.1 Maps

The function:

for i in range(5):
    value = map(lambda x: x(i), funcs)
    print(value)

gives me:

<map object at 0x1056c9630>
<map object at 0x1056c94e0>
<map object at 0x1056c9668>
<map object at 0x1056c9588>
<map object at 0x1056c9630>

I believe it should be:

for i in range(5):
    value = list(map(lambda x: x(i), functs))
    print(value)

7.5 Decorator

It is confusing to name the new function variable the same thing as the existing function, i.e.:

a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)

Why not just:

x = a_new_decorator(a_function_requiring_decoration)

When I tried the code in the first section in an python notebook, I got:

I am doing some boring work before executing a_func()
I am doing some boring work before executing a_func()
I am the function which needs some decoration to remove my foul smell
I am doing some boring work after executing a_func()
I am doing some boring work after executing a_func()

However, it worked in IDLE. Any idea why?

one_liners > CSV to json may be incorrect

In the section:

python -c "import csv,json;print json.dumps(list(csv.reader(open('csv_file.csv'))))"

I tried the code in the paragraph with both Python 2 and 3(with modification), sample:

a,b,c,d,e
1,2,3,4,5
f,w,e,r,t
`,1,2,3,4

it returns like:

[["a", "b", "c", "d", "e"], ["1", "2", "3", "4", "5"], ["f", "w", "e", "r", "t"], ["`", "1", "2", "3", "4"]]

Not seems like JSON. So maybe it's wrong.

However, I don't know the sample of the CSV and output in the paragraph, so I didn't create a pull request.

I have code which works, but not in one line:

import csv
import json


def csv_to_json(file_path):
    ret_list = []
    with open(file_path, 'r') as f:
        csv_list = list(csv.reader(f))
        for col in csv_list[1:]:
            ret_list.append(dict(zip(csv_list[0], col)))
    return json.dumps(ret_list)

print(csv_to_json('csv_file.csv'))

returns (with CSV above):

[{"a": "1", "b": "2", "c": "3", "d": "4", "e": "5"}, {"a": "f", "b": "w", "c": "e", "d": "r", "e": "t"}, {"a": "`", "b": "1", "c": "2", "d": "3", "e": "4"}]

Class Magic Method: __str__

I found __str__ method often very helpful. It allows you to do print(object_instance) to display custom created print outputs of the object instance. It can be especially helpful when trying to visualize some custom data structures. Maybe it is worthwhile to mention. Just a thought.

Context manager exit function return

class File(object):
    def __init__(self, file_name, method):
        self.file_obj = open(file_name, method) def __enter__(self):
    def __enter__(self):
        return self.file_obj
    def __exit__(self, type, value, traceback):
        self.file_obj.close()

For this code even though, the exit may close the file correctly , shouldn't it raise an error with the with statement anyways. Because it is not returning anything. And will return None therefore.
In the chapter, it is mentioned that only when exit() returns True, an exception won't be raised.

7.6.1 is not syntax highlighted

For some reason the 7.6.1 example is not syntax highlighted. The document has the .. code:: python in it and the html has the

, so I'm not sure why it isn't actually doing the highlights.

Firefox 41.0.1
Windows 10

improvement: dont' use keyword "input" as name for variable

chapter 5, sets explained, page 16:
"input" as a variable name for a set is problematic because input itself is a python3 keyword.

input = set(['red', 'brown'])
print(input.intersection(valid))

i suggest replacing "input" with "input_set" or some other non-keyword

Parallel sorting technique using lambda's gives an incorrect result

I don't completely understand the zip functionality/sorting of tuples, but when I do

list1 = [1,2,3,4,2,1]
list2 = [6,7,8,7,6,5]
data = zip(list1, list2)
data.sort()
print data
list1, list2 = map(lambda t: list(t), zip(*data))
print "----"
print list1
print list2

It produces the result:

[(1, 5), (1, 6), (2, 6), (2, 7), (3, 8), (4, 7)]
----
[1, 1, 2, 2, 3, 4]
[5, 6, 6, 7, 8, 7]

Here as 7 is before 8. This particular strategy is given in the lambda section

The subclass of email_logit in the decorator section has a problem

Hi all,

the last subclass "email_logit" in the decorator section didn't produce the right result. decorator

Usage:

@email_logit
def myfunc1():
    pass

Output:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in __init__
TypeError: __init__() missing 1 required positional argument: 'func'

[Collections.namedtuple] Tuples also store references to other objects.

In namedtuple, you wrote:
"A tuple is a lightweight object type which allows to store a sequence of immutable Python objects."
That is not quite right. In fact, a tuple doesn't contain objects, it only contains references. Therefore a tuple can also contain a reference to a list:

a = ('sam_favorite_fruit', ['apple', 'pineapple'])

For further explanation, please refer this

map and filter are obsolete, use list comprehensions

map replacement:

items = [1, 2, 3, 4, 5]
squared = [x*x for x in items]

this is simpler/less convoluted

(and x*x is waaay faster than x**2)

filter replacement:

number_list = range(-5, 5)
less_than_zero = [x for x in number_list if x < 0]

Correct default dict example

In this example under defaultdict.
``
from collections import defaultdict

colours = (
('Yasoob', 'Yellow'),
('Ali', 'Blue'),
('Arham', 'Green'),
('Ali', 'Black'),
('Yasoob', 'Red'),
('Ahmed', 'Silver'),
)

favourite_colours = defaultdict(list)

for name, colour in colours:
favourite_colours[name].append(colour)

print(favourite_colours)

output

defaultdict(<type 'list'>,

{'Arham': ['Green'],

'Yasoob': ['Yellow', 'Red'],

'Ahmed': ['Silver'],

'Ali': ['Blue', 'Black']

})

``
We should append colours not colour.

Minor #reduce parameter readability issue

Reduce would read more clearly if the variables in the example explained themselves. After making use of the reduce method outlined in your docs, I ended up further researching the method on additional sites to understand that the variable x is an accumulator. Consider replacing your example with the following, and/or applying the same idea to other examples in your docs. Something like acc and el would also suffice. Thanks for the resource.

from functools import reduce
product = reduce((lambda accumulator, element: accumulator * element), [1, 2, 3, 4])

Add a cool trick, the __contains__ function

you may also be interested to know that what in does is to call the list.contain method, that you can define on any class you write and can get extremely handy to use python at it's full extent.

>>> class ContainsEverything:
    def __init__(self):
        return None
    def __contains__(self, *elem, **k):
        return True


>>> a = ContainsEverything()
>>> 3 in a
True
>>> a in a
True
>>> False in a
True
>>> False not in a
False
>>> 

there is a misdake in 7. Decorators

class email_logit(logit):
'''
A logit implementation for sending emails to admins
when the function is called.
'''
def init(self, email='[email protected]', _args, *_kwargs):
self.email = email
super(logit, self).init(_args, *_kwargs)

def notify(self):
    # Send an email to self.email
    # Will not be implemented here
    pass

super(logit, self).init(_args, *_kwargs) should change to super(email_logit, self).init(_args, *_kwargs)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.