Writing Pythonic Code - Idiomatic Python
Skills:
AI Pair Programming60%
Key Takeaways
Teaches writing Pythonic code, including idiomatic practices and principles
Full Transcript
hello and welcome to this course that is an introduction to idiomatic python now you might have heard the word pythonic around when people talk or write about python code and idiomatic python and the phrase pythonic essentially mean the same which is that you're writing python in the way that the language was intended to be written now there's a lot to cover here and this course is just going to scratch the surface to give you a quick introduction but you're still going to cover a couple of topics specifically you will learn about the sen of python about how to set up your scripts and about statements in python you will learn about pythonic truth value testing but using built-in functions and methods about how to swap variables in place how to use dictionary default values how to apply the don't repeat yourself principle in python and also how to write idiomatic for loops in python alright let's get started in this first lesson i want to introduce you to the zen of python by tim peters if you enter any more modern python interpreter and then type import this and press enter then you get as a printout to your console a poem called descend of python that was written by tim peters and the sentences in this poem encode a bit the idea of what does it mean to write pythonic code you might see some of the sentences around as well so for example simple is better than complex is quoted quite often or there should be only one obvious way to do something or readability counts you might encounter some of these sentences when a person argues for writing pythonic code and this is where they come from they all originate from the stand of python by tim peters and this poem is a bit of a guideline on how to write pythonic code but at the same time it's also a bit of a joke because the whole module was written in a way that is very unpythonic so it just encodes a bit also this feeling of the python community that yes you want to write very readable code but also that you want to have fun while doing it so this is also why this poem is quite loved by the python community and often quoted so now you know how to get to it you just type import this and then it prints out the sign of python i encourage you to try this in your interpreter and read over the poem think about some of the sentences in there and think about how they relate to the later lessons in this course where you're going to learn about some pythonic ways of writing code that's all about the then of python in the next lesson you'll learn about how to set up your scripts and also how to handle statements in python in this lesson i want to talk to you about statements and about setting up your scripts in python let's start with the quicker one which is that you're supposed to put one statement per line in python so here you see two calls to the print function and you see that they are in two separate lines this is the best way of doing it in python but it's also possible to put two statements in one line so you could separate them with a semicolon like this and just say first statement semicolon second statement and that works as well let me run this to show you so it prints out hello world just like it does when you have them into separate lines but the more idiomatic way of writing python code is to put each statement on its own line and now let's look at script setup so these two lines here at the top you might see them around when you see python scripts and you might be wondering what this is about so the good news is that you probably are not going to have to deal with them very much but it's still interesting to know how they work and what this is about the first one is called a shebang statement and this instructs the operating system on how to run this script that you're writing specifically which program to use and the program that you're defining here is the python 3 program and if you add this shebang to the beginning of your script you can do things like not needing to specify the program when you're actually calling it so here i say use the python program to run this python file but if you're adding the shebang at the top you don't actually need to do this necessarily in some newer versions of windows it's already enough to just add this shebang at the top and then you can just say run this file like that in most unix systems you're gonna run into a permission error which is what happened here but you can still make it executable as well by changing the mode by saying change mode and add the executable flag and then give the name of the script and after doing this if you have the shebang at the top you can execute it and again get the expected output without needing to specify that you want to run this with the python program because you have it specified up top here in the shebang the second line of code is a little outdated and you're probably not going to need it anymore but this defines the encoding for using utf-8 and this is the default for python 3 but if you are dealing with some legacy python scripts you might want to also declare the encoding up top just to make sure that the interpreter knows how to encode the text that is in the script now you might if you have a specific different encoding you could also define it here so you could say this file is encoded in st but generally you're going to want to have your scripts in utf-8 whoops and you won't need to specify this if you're running python3 but as the sign of python says sometimes explicit is better than implicit so now you know what these two setup code comments in python mean and how you can use them and that's all for setting up your scripts and how to write statements in python in the next lesson you're going to learn some more about idiomatic python code in this lesson i want to talk to you about testing for truth values in python and so you might want to do something like writing if true value equals equals true and then print something out and that makes sense but only if the value that you're checking for is actually going to be specifically true so the boolean value true but there's also other values that are truthy in python and for example you have numbers that are non-zero or non-empty strings or non-empty lists any of these would be considered truthy but they would not catch with this statement so let me show you this if i say true value equals the boolean value true and false value equals the boolean value false so these two statements are now going to run as expected because i have another one down here let me comment that out so now it's just checking for the boolean truth value is true and false so when i execute this then these two print statements the conditional statements execute and the print functions they run as expected and print out the results however if i change anything of this for another truthy value or a false value here an empty list would be falsey in python then these checks are not going to work anymore if i run this same script now i don't get any output and this is because you're explicitly testing for the boolean value too now very often you want to just test whether a value is truthy so this one would be considered truthy and this one would be considered falsie for example and if you want to make sure that your checks your truth value checks would also work in that case what you can do instead of this is you can write your code like this you can just say if truth value and that implicitly tests for whether the value is truthy and if not fast value implicitly tests whether it is falsy so if i run this script now we'll see that again i get the expected output and this conditional statements execute so this is generally the better way of testing for truth values in python because it catches more truthy and false values apart from just the boolean true and false and this is preferred unless you specifically want to check for the booleans now another similar thing is if you want to test for none you should write it in this way that you use the is operator to check for the identity of the non-object you have always just one non-object in your running python session and you always want to check for that one instead of using the double equals sign you don't want to do that but instead just use the is operator if you're checking for none so this would these three statements would be a good way of writing your truth value testing in a pythonic idiomatic way
Original Description
What programming idioms are unique to Python? This video is a quick introduction for people coming from other languages as well as a short overview for programming beginners to some of the idiomatic practices within Python.
Click here for more info about the complete course: https://realpython.com/courses/writing-idiomatic-python/
In this video lesson, you’ll learn:
- How to access and interpret The Zen of Python
- How to set up a script
- How to test truth values
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Real Python · Real Python · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
A better Python REPL – bpython vs python interpreter
Real Python
Introducing large-type.com – A Utility Website
Real Python
Reading Hacker News Without Wasting Tons of Time
Real Python
Forward References and Python 3 Type Hints
Real Python
Using Sublime Text as your Git Editor
Real Python
Python Code Linting and Auto-Complete for Sublime Text
Real Python
Make your Python Code More Readable with Custom Exceptions
Real Python
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
How to Use Sublime Text from the Command Line
Real Python
Rename Variables with Multiple Selection in Sublime Text
Real Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
Sublime Text Whitespace Settings for Python Development
Real Python
Function Argument Unpacking in Python
Real Python
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
Using "get()" to Return a Default Value from a Python Dict
Real Python
A Python Shorthand for Swapping Two Variables
Real Python
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
Setting up Sublime Text for Python Developers
Real Python
Sublime Text + Python Guide Overview
Real Python
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
Type-Checking Python Programs With Type Hints and mypy
Real Python
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
My Python Code Looks Ugly and Confusing – Help!
Real Python
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
Programmer Portfolio – Example and Walkthrough
Real Python
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
How to Build Your Public Speaking Skills as a Developer
Real Python
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
Cool New Features in Python 3.6
Real Python
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
Emulating switch/case Statements in Python with Dictionaries
Real Python
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
A Crazy Python Dictionary Expression ?!
Real Python
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
Optional Arguments in Python With *args and **kwargs
Real Python
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
Installing Python Packages with pip and virtualenv / venv
Real Python
"For Each" Loops in Python with enumerate() and range()
Real Python
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
Python Tutorial: List Comprehensions Step-By-Step
Real Python
Leveraging Python's Implicit "return None" Statements
Real Python
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
Writing automated tests for Python command-line apps and scripts
Real Python
How to find great Python packages on PyPI, the Python Package Repository
Real Python
Immutable vs Mutable Objects in Python
Real Python
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
My Experience at PyCon 2017 in Portland
Real Python
Pylint Tutorial – How to Write Clean Python
Real Python
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python
More on: AI Pair Programming
View skill →Related Reads
📰
📰
📰
📰
AI CLI Tools Are Eating Each Other's Lunch
Dev.to · Tracepilot
Loop Engineering: The Skill That Just Made Your AI Workflow Obsolete
Medium · Machine Learning
We built a real-time Pokémon TCG AR overlay for live streams and open-sourced everything
Medium · Deep Learning
I tested the new Claude Desktop on Linux - here's how it compares to rival apps
ZDNet
🎓
Tutor Explanation
DeepCamp AI