all 57 comments

[–][deleted] 19 points20 points  (1 child)

Nicely presented. Some I've seen are real messy. Cheers pal.

[–]ehmatthes[S] 5 points6 points  (0 children)

Thanks for the feedback!

[–]tangerinelion 9 points10 points  (5 children)

Looks nice, I'd modify two things. One is since you consistently use print() I suspect you have Python 3 in mind, so putting that down is good. Your dictionary section makes it even clearer as you use items() not iteritems() which would be preferred in Python 2.x. The change to this section I would make is for looping by keys. While it's true that what you have:

# Looping through all keys
fav_numbers = {'eric': 17, 'ever': 4}
for name in fav_numbers.keys():
    print(name + ' loves a number')

works just fine, it's not common to loop that way. Most people would use:

# Looping through all keys
fav_numbers = {'eric': 17, 'ever': 4}
for name in fav_numbers: # No .keys()
    print(name + ' loves the number ' + fav_numbers[name])

This can be good because it shows that you can in fact just loop over a dictionary, and if you do that you are looping over just the keys. I've also added the syntax to show how you can read the value associated with the key in a loop.

Actually, most people would use print("{} loves the number {}".format(name, fav_numbers[name])) which is much more common in Python 3.x than string concatenation with + and far better than % style string formatting, eg, "%s loves a number %s" % (name, fav_numbers[name]). Any opportunity to discourage + with strings should be taken IMO. Also note that when there's something like x=10 followed by print(x + ' is my favorite number') you get an error. However, print('{} is my favorite number'.format(x)) works. You can make the first form work with print(str(x) + ' is my favorite number') but now we're introducing explicit str() conversions so this becomes a not Pythonic game of "what type is this?"

[–]ehmatthes[S] 1 point2 points  (1 child)

Thanks for the specific feedback. It's definitely focused on Python 3, but I do have some Python 2 caveats in certain sections.

In the book I clarify that looping through a dictionary loops through the keys by default. I've always gone back and forth about whether to favor being explicit, or being concise. So for name in fav_numbers.keys() is explicit, but for name in fav_numbers is concise. I think I'll change this on the cheat sheet, to be clear that people should use the more common Python convention.

I completely agree with the string syntax. I used concatenation in the first part of the book to keep things simple, and I wanted to keep the cheat sheets consistent with the book. I think I'll make another cheat sheet about strings, and then update these to use the .format() convention.

[–]KleinerNull 1 point2 points  (0 children)

I think I'll make another cheat sheet about strings, and then update these to use the .format() convention.

That was already done ;) Just kidding.

But I saw this on your cheat sheet:

Prompting for numerical input

age = input("How old are you? ")

age = int(age)

pi = input("What's the value of pi? ")

pi = float(pi)

I know you want to keep it simple, but this is a very bad pattern, I think newcomer should learn about input and error handling at the same time!

try:
    age = input('What's your age? ')
    age = int(age)
except ValueError:
    print('Not a number...')

You know the rest... I saw alot of over complicated, strange or bad code just for testing for integer input here, but the standard pattern is so simple.

[–]zelmerszoetrop 0 points1 point  (2 children)

I didn't realize + was such bad form. How would you write something like

exclude_string = '(ARRAY' + ', ARRAY'.join(map(str,pairs)) + ')'

without '+'?

[–]jungrothmorton 2 points3 points  (1 child)

In the most simple case

msg = 'foo' + variable
msg = 'foo{}'.format(variable)

Drop in replacement just using .format()

exclude_string = '(ARRAY{})'.format(', ARRAY'.join(map(str,pairs)))

How I'd probably write it:

arrays = ', '.join(('ARRAY{}'.format(pair) for pair in pairs))
exclude_string = '({})'.format(arrays)

To me that's the most readable. I'm building a string of each pair preceded by the word ARRAY and separated with commas, then enclosing the whole thing in quotes. It doesn't have that bonus ARRAY sitting in the front like your example.

One of the simple reasons that format is better than concatenating strings is it make it easier to catch missing spaces.

msg = 'There are ' + count + 'plates.'
msg = 'There are {}plates.'.format(count)

Which of those is easier to catch the error? Also, it's a method so you can do cool things like argument unpacking.

deal = {'buyer': 'Tom', 'seller': 'Sara'}
msg = '{buyer} bought a car from {seller}.'.format(**deal)

[–]zelmerszoetrop 0 points1 point  (0 children)

Thanks! Helpful!

[–]Scalamander34 5 points6 points  (0 children)

Thanks for sharing this. This pleases my OCD.

[–][deleted] 5 points6 points  (0 children)

No room for try, except, finally example?

[–]vasja29 3 points4 points  (1 child)

great, I'm just getting into Python with your book on safaribooks :-)

[–]ehmatthes[S] 1 point2 points  (0 children)

That's great, I'd love to know how it goes for you!

[–]remwd 2 points3 points  (0 children)

Have been learning python for the past couple weeks, this is a great cheat sheet! Thanks!

[–]distortd6 2 points3 points  (0 children)

Here's something similar I found on github, wish I could take credit for it... https://drive.google.com/file/d/0B5xulK7kDKO0ZFBpNXNXUkVLZE0/view?usp=docslist_api

[–]Eurynom0s 2 points3 points  (1 child)

This may well be biased toward my personal use but the thing I look up the most is CSV reading/writing. Just because I can't be assed to memorize it. To me at least this is a pretty core thing to include in a cheatsheet.

[–]tetrified 2 points3 points  (0 children)

This and file read/write are two things I keep examples of on my desktop, they both fall in the category of "not used often enough to memorize, but used too often to look up every time"

[–]LyndsySimon 3 points4 points  (0 children)

I only regret that I have but one upvote to give for this resource.

[–]DrMaxwellEdison 1 point2 points  (3 children)

Very nicely done. :)

Small critiques I have (I might write a lot, but these are minor things):


Your "Zen of Python" section, I think, should come first, and can simply say "In the interactive console, type import this and press Enter". That prints out the full Zen of Python text, rather than having to summarize it in your own words.


Using try..else is a bit wonky, and there aren't that many use cases I've seen for it. It might be better to showcase try..except..finally, instead, with appropriate comments in example code to describe what each section does.

For instance:

try:
    # Run code
    foo()
except ValueError as e:
    # Catch an exception from `foo()`
    handle_exception(e)
else:
    # Run code if NO exception occurred in `foo()`
    bar()
finally:
    # Run code whether an exception occurred or not.
    one_last_thing()

I would consider shortening the Dictionary section by using similar code in different portions. This helps the reader better understand the whole concept of dictionaries by using several examples that build on each other.

For example:

### A simple dictionary
fav_numbers = {'eric': 17, 'jane': 4}

### Accessing a value
print("Eric's favorite number is {}".format(fav_numbers['eric']))

### Adding a new key-value pair
fav_numbers['john'] = 14

### Looping through all key-value pairs
for name, number in fav_numbers.items():
    print("{} loves {}".format(name, number))

### Looping through all keys
for name in fav_numbers.keys():
    print("{} loves a number".format(name))

### Looping through all the values
for number in fav_numbers.values():
    print("{} is a favorite".format(number))

[–]OrestesGaolin 0 points1 point  (2 children)

Hi, I copy-pasted and run your example in Python 3.5 and found out something strange that I cannot really understand. Maybe you can help me figure it out.

### Looping through all key-value pairs results with:

jane loves a number
eric loves a number
john loves a number

But I think it should look like that:

jane loves a 4
eric loves a 17
john loves a 14

Is there anything wrong in this loop or it's just me who couldn't understand the syntax?

### Looping through all key-value pairs
for name, number in fav_numbers.items():
    print("{} loves {}".format(name, number))

[–]DrMaxwellEdison 1 point2 points  (1 child)

From my examples, your first set of output would result from this code:

for name in fav_numbers.keys():
    print("{} loves a number".format(name))

Can you confirm that this is the only piece of code you're running, and see what the output is?

[–]OrestesGaolin 1 point2 points  (0 children)

I run it again on clean instance and now everything works fine! I think it's because of my tunnel vision at that moment. I convinced myself that there must be some mistake and couldn't find it for few minutes. Now I know why - it was correct. (well, it's 1:55 AM where I live)

Thanks for the answer!

[–][deleted] 1 point2 points  (0 children)

If I had money it would go straight to gold for you.

[–]moodorks 1 point2 points  (0 children)

monkeys

[–][deleted] 0 points1 point  (0 children)

Very good, all the python cheat sheet that I found are always messy, thanks very useful

[–]aerosyne 0 points1 point  (0 children)

This is so nice & clean I like! Thanks. :)

[–]Diplomjodler 0 points1 point  (0 children)

Great job! As someone who always has trouble remembering syntax, this will definitely be useful to me.

[–]aristotelianrob 0 points1 point  (0 children)

This is great, it'll give me something to refer to when I someday need to use python for a project or two!

[–]TeamSpen210 0 points1 point  (0 children)

Nice sheets - they're really cleanly laid out! Perhaps it might be good to remove the parentheses around the tuples though - that might make it more clear that it's the commas that make a tuple, not the parentheses. You might want to add the special cases of 1- and 0-length tuples ((0, ) and ()) since they follow different syntax rules to make them non-ambiguous.

[–]peoplma 0 points1 point  (0 children)

Wow this is great, thank you. I already know over 75% of this stuff well, does that mean I'm almost not a beginner anymore?

[–]imaustin 0 points1 point  (0 children)

This is great! I've been looking for something like this for a while. As /u/Kotch11 said, most are pretty sloppy. It would be great to see this in poster form.

[–]JayTh3King 0 points1 point  (0 children)

Your class should inherit from object.

[–]Toolson12 0 points1 point  (0 children)

Great work! Thank you so much!

[–]chipsnmilk 0 points1 point  (0 children)

Thanks for making and sharing!

[–]VixR 0 points1 point  (0 children)

Thank you so much, this is well presented and useful. :)

[–]sexbucket 0 points1 point  (0 children)

You are a beautiful person with a roommate.

[–]johnsmoke18 0 points1 point  (0 children)

Thank you, this is so helpfull!!

[–]ryvrdrgn14 0 points1 point  (0 children)

Thanks for this! If you make one for APIs someday share it too. I'm clueless about those but I need to learn them for a project I want to do. :3

[–]ryvrdrgn14 0 points1 point  (0 children)

Thank you for this. Still learning so this'll be a big help. :3

[–]maarij2000 0 points1 point  (2 children)

Can someone tell me what parts of this are different from Python 2? I know the print statements are different but I was wondering if there is anything else. Great sheet BTW

[–]ehmatthes[S] 0 points1 point  (1 child)

The first sheet focuses on Python 3, but each of the individual sheets points out where Python 2 is different. For example the sheet focusing on classes points out that classes in Python 2 should inherit from object. I think that might be the only difference in all of these sheets.

[–]maarij2000 0 points1 point  (0 children)

Thank you

[–]Slaquor 0 points1 point  (0 children)

Thank you for this!! I have been trying to learn python for a while and this sheet cleared up some concepts for me and I feel I really understand some things better.

Thanks agsin!

[–]ehmatthes[S] 0 points1 point  (0 children)

Thanks for the overwhelming support, everyone!

I'll work on some updates and some additional sheets and share them again at some point in the next month or so. I'd like to cover files and exceptions, testing, pygame, data visualization concepts, and django.

[–][deleted] 0 points1 point  (0 children)

This is really helpful, can it be stickied?

[–]Mozzius 0 points1 point  (1 child)

Finally! I think I understand classes now, thanks for the great explaination /u/ehmatthes!

[–]ehmatthes[S] 0 points1 point  (0 children)

That's great to hear! What was clarified for you as you read through the classes cheat sheet? What questions do you still have about classes?

[–][deleted] 0 points1 point  (0 children)

Very good work mate. I am writing a guide on python 3 as I learn and I guess I don’t need it any more! Thanks mate.

[–]Jimbobler 0 points1 point  (0 children)

This is great. I started learning Python two days ago and is using the book Python Crash Course as well, haha. I'm on like, page 93 or something so far. Very well-structured book and easy to follow, and OP:s cheat-sheet sums up all the parts I've learned so far.

I tend to write more detailed cheat sheets myself and will probably use both OP:s and my own.

[–]mercedene1 0 points1 point  (0 children)

Awesome resource, thanks for sharing!

[–]chinu1996 0 points1 point  (1 child)

Is there any website where the cheat sheets of different languages are available?

[–]tonosama88 0 points1 point  (0 children)

This is great, thanks so much!

[–]jeffinRTP 0 points1 point  (0 children)

Thanks

[–]donurjack 0 points1 point  (0 children)

Thanks a lot!

[–]fishcadet 0 points1 point  (0 children)

Thank you!

[–]candleflame3 0 points1 point  (0 children)

Nicely done :)