skip to navigation
skip to content

Planet Python

Last update: September 18, 2019 01:48 PM UTC

September 18, 2019


Podcast.__init__

Cultivating The Python Community In Argentina

The Python community in Argentina is large and active, thanks largely to the motivated individuals who manage and organize it. In this episode Facundo Batista explains how he helped to found the Python user group for Argentina and the work that he does to make it accessible and welcoming. He discusses the challenges of encompassing such a large and distributed group, the types of events, resources, and projects that they build, and his own efforts to make information free and available. He is an impressive individual with a substantial list of accomplishments, as well as exhibiting the best of what the global Python community has to offer.

Summary

The Python community in Argentina is large and active, thanks largely to the motivated individuals who manage and organize it. In this episode Facundo Batista explains how he helped to found the Python user group for Argentina and the work that he does to make it accessible and welcoming. He discusses the challenges of encompassing such a large and distributed group, the types of events, resources, and projects that they build, and his own efforts to make information free and available. He is an impressive individual with a substantial list of accomplishments, as well as exhibiting the best of what the global Python community has to offer.

Announcements

  • Hello and welcome to Podcast.__init__, the podcast about Python and the people who make it great.
  • When you’re ready to launch your next app or want to try a project you hear about on the show, you’ll need somewhere to deploy it, so take a look at our friends over at Linode. With 200 Gbit/s private networking, scalable shared block storage, node balancers, and a 40 Gbit/s public network, all controlled by a brand new API you’ve got everything you need to scale up. And for your tasks that need fast computation, such as training machine learning models, they just launched dedicated CPU instances. Go to pythonpodcast.com/linode to get a $20 credit and launch a new server in under a minute. And don’t forget to thank them for their continued support of this show!
  • You listen to this show to learn and stay up to date with the ways that Python is being used, including the latest in machine learning and data analysis. For even more opportunities to meet, listen, and learn from your peers you don’t want to miss out on this year’s conference season. We have partnered with organizations such as O’Reilly Media, Dataversity, Corinium Global Intelligence, and Data Council. Upcoming events include the O’Reilly AI conference, the Strata Data conference, the combined events of the Data Architecture Summit and Graphorum, and Data Council in Barcelona. Go to pythonpodcast.com/conferences to learn more about these and other events, and take advantage of our partner discounts to save money when you register today.
  • Your host as usual is Tobias Macey and today I’m interviewing Facundo Batista about his experiences founding and fostering the Argentinian Python community, working as a core developer, and his career in Python

Interview

  • Introductions
  • How did you get introduced to Python?
  • What was your motivation for organizing a Python user group in Argentina?
  • How does the geography and culture of Argentina influence the focus of the community?
  • Argentina is a fairly large country. What is the reasoning for having the user group encompass the whole nation and how is it organized to provide access to everyone?
  • What are some notable projects that have been built by or for members of PyAr?
    • What are some of the challenges that you faced while building CDPedia and what aspects of it are you most proud of?
  • How did you get started as a core developer?
    • What areas of the language and runtime have you been most involved with?
  • As a core developer, what are some of the most interesting/unexpected/challenging lessons that you have learned?
  • What other languages do you currently use and what is it about Python that has motivated you to spend so much of your attention on it?
  • What are some of the shortcomings in Python that you would like to see addressed in the future?
  • Outside of CPython, what are some of the projects that you are most proud of?
  • How has your involvement with core development and PyAr influenced your life and career?

Keep In Touch

Picks

Closing Announcements

  • Thank you for listening! Don’t forget to check out our other show, the Data Engineering Podcast for the latest on modern data management.
  • Visit the site to subscribe to the show, sign up for the mailing list, and read the show notes.
  • If you’ve learned something or tried out a project from the show then tell us about it! Email hosts@podcastinit.com) with your story.
  • To help other people find the show please leave a review on iTunes and tell your friends and co-workers
  • Join the community in the new Zulip chat workspace at pythonpodcast.com/chat

Links

The intro and outro music is from Requiem for a Fish The Freak Fandango Orchestra / CC BY-SA

September 18, 2019 12:53 PM UTC


Codementor

why python is the best-suited programming language machine learning

Machine Learning is the hottest trend in modern times. According to Forbes, Machine learning patents grew at a 34% rate between 2013 and 2017 and this is only set to increase in the future. And...

September 18, 2019 05:27 AM UTC


Matt Layman

Python alternative to Docker

Deploying a Python app to a server is surprisingly hard. Without blinking, you’ll be dealing with virtual environments and a host of other complications. The landscape of deployment methods is huge. What if I told you that there is a way to build your app into a single file and it isn’t a Docker container? In this article, we’re going to look at common ways of deploying Python apps. We’ll explore the touted benefits of Docker containers to understand why containers are so popular for web apps.

September 18, 2019 12:00 AM UTC

September 17, 2019


Yasoob Khalid

Looking for an internship for Summer 2020

Hi lovely people! 👋 Hope everything is going well on your end. I asked you guys last year for helping me find a kick-ass internship and you all came through. I ended up working at ASAPP over the summer and had an awesome time. I wrote an article about what I learned during my internship.

I am putting out the same request for next summer as well. If you have benefited from any of my articles and work at an amazing company and feel like I would be a good addition to your team, please reach out. I am looking for a 12-14 week internship. I strongly prefer small teams where I can bond with the people I am working with. I am open to most places but bonus points if you work at a hardware based tech company or a fintech startup. However, this is not a hard requirement.

I have done a lot of backend development in Python and GoLang. I am fairly comfortable with dabbling in the front-end code as well. I have also tinkered with open source hardware (Arduino & Raspberry Pi) and wrote a couple of articles about what I did and how I did it. You can take a look at my resume (PDF) to get a better understanding of my expertise. You can also read about how I got into programming through this article.

tldr: I love working with exciting stuff even if it means I have to learn something completely new!

I hope you guys would come through this time as well. Have a fantastic day and keep smiling. If you have any questions/comments/suggestions, please comment below or send me an email at yasoob.khld at gmail.com.

See ya! ♥

 

September 17, 2019 10:29 PM UTC


A. Jesse Jiryu Davis

Free Coaching For PyGotham Speakers

I help organize PyGotham, NYC’s annual conference about the Python programming language. For the third year in a row, we’re giving our speakers free sessions with a professional speaking coach, opera singer Melissa Collom. In the past we’ve limited coaching to first-time speakers, but we’re now able to coach everyone. However, we only have budget guaranteed for the first 20 signups. If you’re speaking at PyGotham, reserve your spot now:

September 17, 2019 10:02 PM UTC


Yasoob Khalid

Filtering & Closing Pull Requests on GitHub using the API

Hi everyone! 👋 In this post, I am going to show you how you can use the GitHub API to query Pull Requests, check the content of a PR and close it.

The motivation for this project came from my personal website. I introduced static comments on the website using Staticman and only after a day or two, got bombarded with spam. I hadn’t enabled Akismet or any honey pot field so it was kinda expected. However, this resulted in me getting 200+ PRs on GitHub for bogus comments which were mainly advertisements for amoxicillin (this was also the first time I found out how famous this medicine is).

I was in no mood for going through the PRs manually so I decided to write a short script which went through them on my behalf and closed the PRs which mentioned certain keywords.

You can see the different PRs opened by staticman. Most of these are spam:

For this project, I decided to use PyGithub library. It is super easy to install it using pip:

pip install pygithub

Now we can go ahead and log in to GitHub using PyGithub. Write the following code in a github_clean.py file:

from github import Github
import argparse

def parse_arguments():
    """
    Parses arguments
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('-u', '--username', 
        required=True, help="GitHub username")
    parser.add_argument('-p', '--password', 
        required=True, help="GitHub password")
    parser.add_argument('-r', '--repository', 
        required=True, help="repository name")
    parsed_args = parser.parse_args()
    if "/" not in parsed_args.repository:
        logging.error("repo name should also contain username like: username/repo_name")
        sys.exit()
    return parsed_args
    
def main():
    args = parse_arguments()
    g = Github(args.username, args.password)
    
if __name__ == '__main__':
    main()

So far I am just using argparse to accept and parse the command line arguments and then using the arguments to create a Github object.

You will be passing in three arguments:

  1. Your GitHub username
  2. Your GitHub password
  3. The repo you want to work with

Next step is to figure out how to loop through all the pull requests and check if their body contains any “spam” words:

repo =  g.get_repo(args.repository)
issues = repo.get_issues()

page_num = 0
while True:
    issue_page = issues.get_page(page_num)
    if issue_page == []:
        break
    for issue in issue_page:
        # Do something with the individual issue
        if spam_word in issue.raw_data['body'].lower():
            print("Contains spam word!!")

First, we query GitHub for a specific repo using g.get_repo and then we query for issues for that repo using repo.get_issues. It is important to note that all PRs are registered as issues as well so querying for issues will return pull requests as well. GitHub returns a paginated result so we just continue asking for successive issues in a while loop until we get an empty page.

We can check the body of an issue (PR) using issue.raw_data['body']. Two important pieces are missing from the above code. One is the spam_word variable and another is some sort of a mechanism to close an issue.

For the spam_word, I took a look at some issues and created a list of some pretty frequent spam words. This is the list I came up with:

spam_words = ["buy", "amoxi", "order", "tablets", 
"pills", "cheap", "viagra", "forex", "cafergot", 
"kamagra", "hacker", "python training"]

Add this list at the top of your github_clean.py file and modify the if statement like this:

closed = False
if any(spam_word in issue.raw_data['body'].lower() for spam_word in spam_words):
    issue.edit(state="closed")
    closed = True
print(f"{issue.number}, closed: {closed}")

With this final snippet of code, we have everything we need. My favourite function in this code snippet is any. It checks if any of the elements being passed in as part of the argument is True.

This is what your whole file should look like:

import argparse
import sys
import re
import logging

from github import Github

spam_words = ["buy", "amoxi", "order", "tablets", 
"pills", "cheap", "viagra", "forex", "cafergot", 
"kamagra", "hacker", "python training"]
logging.basicConfig(level=logging.INFO)

def parse_arguments():
    """
    Parses arguments
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('-u', '--username', 
        required=True, help="GitHub username")
    parser.add_argument('-p', '--password', 
        required=True, help="GitHub password")
    parser.add_argument('-r', '--repository', 
        required=True, help="repository name")
    parsed_args = parser.parse_args()
    if "/" not in parsed_args.repository:
        logging.error("repo name should also contain username like: username/repo_name")
        sys.exit()
    return parsed_args

def process_issue(issue):
    """
    Processes each issue and closes it 
    based on the spam_words list
    """
    closed = False
    if any(bad_word in issue.raw_data['body'].lower() for bad_word in words):
        issue.edit(state="closed")
        closed = True
    return closed

def main():
    """
    Coordinates the flow of the whole program
    """
    args = parse_arguments()
    g = Github(args.username, args.password)
    logging.info("successfully logged in")
    repo =  g.get_repo(args.repository)

    logging.info("getting issues list")
    issues = repo.get_issues()

    page_num = 0
    while True:
        issue_page = issues.get_page(page_num)
        if issue_page == []:
            logging.info("No more issues to process")
            break
        for issue in issue_page:
            closed = process_issue(issue)
            logging.info(f"{issue.number}, closed: {closed}")
        page_num += 1

    
if __name__ == '__main__':
    main()

I just added a couple of different things to this script, like the logging. If you want, you can create a new command-line argument and use that to control the log level. It isn’t really useful here because we don’t have a lot of different log levels.

Now if you run this script you should see something similar to this:

INFO:root:successfully logged in
INFO:root:getting issues list
INFO:root:No more issues to process

It doesn’t process anything in this run because I have already run this script once and there are no more spam issues left.

So there you go! I hope you had fun making this! If you have any questions/comments/suggestions please let me know in the comments below! See you in the next post 🙂 ♥

 

September 17, 2019 07:34 PM UTC


PyCoder’s Weekly

Issue #386 (Sept. 17, 2019)

#386 – SEPTEMBER 17, 2019
View in Browser »

The PyCoder’s Weekly Logo


Call for Proposals for PyCon 2020 Is Open

The submission deadlines are: Tutorial proposals are due November 22, 2019. Talk, Charlas, Poster, and Education Summit proposals are due December 20, 2019.
PYCON.BLOGSPOT.COM

Python vs C++: Selecting the Right Tool for the Job

Explore the similarities and differences you’ll find when comparing Python vs C++. You’ll learn about memory management, virtual machines, object-oriented programming differences, and much more.
REAL PYTHON

Find a Python Job Through Vettery

alt

Vettery specializes in developer roles and is completely free for job seekers. Interested? Submit your profile, and if accepted, you can receive interview requests directly from top companies seeking Python devs. Get started →
VETTERY sponsor

PEP 603: Adding a frozenmap Type to collections

A draft PEP that proposes adding a new fully persistent and immutable mapping type called frozenmap to the collections module in the Python standard library.
PYTHON.ORG

Java Primer for Python Developers

“There are large distinctions between the two programming languages, but I’ll try to give the most notable that I encountered–as I approached Java from a Python-heavy background.”
MAX MAUTNER

The Boring Technology Behind a One-Person Internet Company

The Python-powered tech stack of a one-person company (ListenNotes podcast search engine).
WENBING FANG

Types for Python HTTP APIs

How Instagram uses types to document and enforce a contract for their Python HTTP APIs.
ANIRUDH PADMARAO (INSTAGRAM)

Discussions

What Are Some of the Drawbacks of Python?

Also see the related discussion on Hacker News.
QUORA.COM

How Common Is Python in the Enterprise World?

REDDIT

Python Jobs

Python Backend Developer (Kfar Saba, Israel)

3DSignals

Senior Software Engineer (Remote)

Close

Senior Python Developer/PM/Architect (Austin, TX)

InQuest

Senior Software Developer (Edmonton, Canada)

Levven Electronics Ltd.

More Python Jobs >>>

Articles & Tutorials

PyGame: A Primer on Game Programming in Python

Learn how to use PyGame. This library allows you to create games and rich multimedia programs in Python. You’ll see how to draw items on your screen, implement collision detection, handle user input, and much more!
REAL PYTHON

How “Export to Excel” Almost Killed Our System

“Inspired by an actual incident we had in one of our systems caused by an Export to Excel functionality implemented in Python, we go through the process of identifying the problem, experimenting and benchmarking different solutions.”
HAKI BENITA

SQL, Python, and R. All in One Platform. Free Forever.

alt

Mode Studio combines a SQL editor, Python & R notebooks, and visualization builder in one platform. Connect your data warehouse and analyze with your preferred language. Make custom visualizations (D3.js, HTML/CSS) or use out-of-the-box charts.
MODE ANALYTICS sponsor

JPMorgan’s Athena Has 35 Million Lines of Python 2 Code, and Won’t Be Updated to Python 3 in Time

“With 35 million lines of Python code, the Athena trading platform is at the core of JPMorgan’s business operations. A late start to migrating to Python 3 could create a security risk.”
JAMES SANDERS

Should You Use “Dot Notation” or “Bracket Notation” With Pandas?

There are two ways to select a Series from a DataFrame: “dot notation” and “bracket notation” (square brackets). Find out which one you should use, and why.
KEVIN MARKHAM

LEGB? Meet ICPO, Python’s Search Strategy for Attributes

How Python looks up object attributes like obj.name using a “instance, class, parent, object” search algorithm.
REUVEN LERNER

Never Delete PyPI Release

Why you should (almost) never delete a bad release from PyPI—and what to do as a package maintainer instead.
ALEX BECKER • Shared by Alex Becker

“Level Up Your Python” Humble Bundle

Support Pythonic charities like the PSF and get books, software, and videos collectively valued at $867 for a pay-what-you-want price.
HUMBLEBUNDLE.COM sponsor

Python Does What?! Welcome to the float Zone…

A Python “gotcha” involving floating point numbers and tuples.
PYTHONDOESWHAT.COM

Python heapq Module and Heap Data Structure Explained With Examples

MEENAKSHI AGARWAL

Fastest Python Function to Slugify a String

PETER BENGTSSON

Projects & Code

python-intervals: Data Structure and Operations for Intervals

GITHUB.COM/ALEXANDREDECAN • Shared by Alexandre Decan

PyCParser: C Parser and Interpreter Written in Python With Automatic ctypes Interface Generation

GITHUB.COM/ALBERTZ

MyHDL: Design Hardware With Python

MYHDL.ORG

Neural Modules: Toolkit for Conversational AI

GITHUB.COM/NVIDIA

30-seconds-of-python: Collection of Python Snippets That You Can Understand in 30 Seconds or Less

GITHUB.COM/30-SECONDS

ml-workspace: All-In-One Web-Based IDE Specialized for Machine Learning and Data Science

GITHUB.COM/ML-TOOLING • Shared by Lukas Masuch

awesome-python-typing: Python Type Stubs, Plugins, and Tools

GITHUB.COM/TYPEDDJANGO

Events

PyCon TW 2019

September 20 to September 23, 2019
PYCON.TW

DjangoCon US

September 22 to September 28, 2019
DJANGOCON.US

PyWeek 28

September 22 to September 30, 2019
PYWEEK.ORG


Happy Pythoning!
This was PyCoder’s Weekly Issue #386.
View in Browser »

alt

[ Subscribe to 🐍 PyCoder’s Weekly 💌 – Get the best Python news, articles, and tutorials delivered to your inbox once a week >> Click here to learn more ]

September 17, 2019 07:30 PM UTC


Anarcat

FSF resignations

I have been hesitant in renewing my membership to the Free Software Foundation for a while, but now I never want to deal with the FSF until Richard Stallman, president and founder of the free software movement, resigns. So, like many people and organizations, I have written this letter to cancel my membership. (Update: RMS resigned before I even had time to send this letter, but I publish here to share my part of this story.)

My encounters with a former hero

I had the (mis)fortune of meeting rms in person a few times in my life. The first time was at an event we organized for his divine visit to Montreal in 2005. I couldn't attend the event myself, but I had the "privilege" of having dinner with rms later during the week. Richard completely shattered any illusion I had about him as a person. He was arrogant, full of himself, and totally uninterested in the multitude of young hackers he was meeting in his many travels, apart from, of course, arguing with them about proper wording and technicalities. Even though we brought him to the fanciest vegetarian restaurant in town, he got upset because the restaurant was trying to make "fake meat" meals. Somehow my hero, who wrote the GNU manifesto that inspired me to make free software a life goal, has spoiled a delicious meal by being such an ungrateful guest. I would learn later that Stallman has rock star level requirements, with "vegetarian meals served just so" being only one exception out of many. (I don't mind vegetarians of course: I've been a vegetarian for more than 20 years now, but I will never refuse vegetarian food given to me.)

The second time was less frustrating: it was in 2006 during the launch of the GPLv3 discussion draft, an ambitious project to include the community in the rewrite of the GPLv2. Even though I was deeply interested in the legal implications of the changes, everything went a bit over my head and I felt left out of a process that was supposedly designed to include legal geeks like me. At best, I was able to assist Stallman's assistant as she skidded over icy Boston sidewalks with a stereotypical (and maybe a little machismo, I must admit) Canadian winter assurance. At worst, I burned liters of fuel to drive me and some colleagues over the border to see idols speak on a stage.

Finally, I somehow got tangled up with rms in a hallway conversation about open hardware and wireless chipsets at LibrePlanet 2017, the FSF's yearly conference. I forgot the exact details, but we were debating whether or not legislation that forbids certain wireless chipsets to be open was legitimate or not.

(For some reason, rms has ambiguous opinions about "hardware freedom" and sees a distinction between software that runs on a computer (as "in the CPU") and software that is embedded in the hardware, etched into electronic circuits. The fact that this is a continuum that has various in-between incarnations ("firmware", ASIC, FPGA) seems to escape his analysis. But that is besides the point here.)

We "debated" this for a while, but for people who don't know, debating with rms is a little bit like talking with a three year old: they have their deeply rooted opinion, they might recognize you have one as well (if your lucky), but they will generally ignore whatever it is you non-sensical adult are saying because it's incomprehensible anyways. With a three year old, it's kind of hilarious (until they spill an bottle full of vanilla on the floor), but with an adult, it's kind of aggravating and makes you feel like an idiot for even trying.

I mention this anecdote because it's a good example of how Stallman doesn't think rules apply to him. Simple, informal rules like listening to people you're talking to seem like basic courtesy, but rms is above such mundane things. If this was just a hallway conversation, I wouldn't mind that much: after all, I don't need to talk to Richard Stallman. But at LibrePlanet (and in fact anywhere), he believes it is within his prerogative to interrupt any discussion or talk around him . I was troubled by the FSF's silence on Eric Schultz's request for safety at Libre Planet: while I heard the FSF privately reached out to Eric, nothing seemed to have been done to curb Stallman's attitude in public. This is the reason why I haven't returned to Boston for LibrePlanet since then, even though I have dear friends that live there and were deeply involved in the organization.

The final straw before this week's disclosurse was an event in Quebec city where Stallman was speaking at a conference. A friend of mine asked a question involving his daughter as an example user. Stallman responded to the question by asking my friend if he could meet his (underage) daughter, with obvious obscene undertones. Everyone took this as a joke, but, in retrospect, it was just horrible and I had come to conclude that Stallman was now a liability to the free software movement. I just didn't know what to do back then. I wish I had done something.

Why I am resigning from the FSF

Those events at LibrePlanet were the first reason why I haven't renewed my membership yet. But now I want to formally cancel my membership with the FSF because its president went over his usual sexism and weird pedophilia justification from the past. I first treated those as an abhorrent eccentricity or at best an unfortunate intellectual posture, but rms has gone way beyond this position now. Now rms has joined the rank of rape apologists in the Linux kernel development community, an inexcusable position in our community that already struggles too much with issues of inclusion, respect, and just being nice with each other. I am not going to go into details that are better described by this courageous person, but needless to say that this kind of behavior is inexcusable from anyone, and particularly from an historical leader. Stallman did respond to the accusations, but far from issuing an apology, he said his statements were "mischaracterised"; something that looks to me like a sad caricature.

I do not want to have anything to do with the FSF anymore. I don't know if they would be able to function without Stallman, and frankly at this point, I don't care: they have let this gone on for too long. I know how much rms contributed to the free software movement: he wrote most of Emacs, GCC and large parts of the GNU system so many people use on their desktops. I am grateful for that work, but that was a long time ago and this is now. As others have said, we don't need to replace rms. We need a world where such leaders are not necessary, because rock stars too easily become abusers.

Stallman is just the latest: our community is filled with obnoxious leaders like this. It seems our community leaders are (among other things) either assholes, libertarian gun freaks, or pedophilia apologists and sexists. We tolerate their abuse because we somehow believe they are technically exceptional. They aren't: they're just hard-working and privileged. But even if they would be geniuses, but as selamie says:

For a moment, let’s assume that someone like Stallman is truly a genius. Truly, uniquely brilliant. If that type of person keeps tens or even hundreds of highly intelligent but not ‘genius’ people out of science and technology, then they are hindering our progress despite the brilliance.

Or, as Banksy says:

We don't need any more heroes.

We just need someone to take out recycling.

I wish Stallman would just retire already. He's done enough good work for a lifetime, now he's bound to just do more damage.

Update: Richard Stallman resigned from the FSF and from MIT ("due to pressure on MIT and me"), still dodging responsability and characterizing the problem as "a series of misunderstandings and mischaracterizations". Obviously, this man cannot be reformed and we need to move on. Those events happened before I even had time to actually send this letter to the FSF, so I guess I might renew my membership after all. I'll hold off until LibrePlanet, however, we'll see what happens there... In the meantime, I'll see how I can help my friends left the FSF because they must be living through hell now.

September 17, 2019 02:58 PM UTC


Real Python

Python Debugging With pdb

Nowadays, we often take for granted the excellent debuggers built into our favorite IDEs. But how do you debug your Python code when you don’t have the luxury of using an IDE?

pdb, short for Python DeBugger, is a module for interactive source code debugging. It’s built into the Python Standard Library, so it’s always accessible to you. Because it runs in the command line, it’s especially helpful when you’re developing on remote systems.

In this course, you’ll learn how to perform the most common debugging tasks using pdb, including setting breakpoints, stepping through code, viewing stack traces, creating watch lists, and more.

Free Bonus: Click here to get a printable "pdb Command Reference" (PDF) that you can keep on your desk and refer to while debugging.


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

September 17, 2019 02:00 PM UTC


Chris Moffitt

Happy Birthday Practical Business Python!

Introduction

On September 17th, 2014, I published my first article which means that today is the 5th birthday of Practical Business Python. Thank you to all my readers and all those that have supported me through this process! It has been a great journey and I look forward to seeing what the future holds.

This 5 year anniversary gives me the opportunity to reflect on the blog and what will be coming next. I figured I would use this milestone to walk through a few of the stats and costs associated with running this blog for the past 5 years. This post will not be technical but I am hopeful that my readers as well as current and aspiring bloggers going down this path will find it helpful. Finally, please use the comments to let me know what content you would like to see in the future.

Traffic

I’m always curious about other people’s site traffic, so here’s a view of my traffic over time. I’m now averaging around 90K monthly visitors:

Metrics

I remember watching the views when I first started and never expected to see it grow as much as it has. In other ways, it has definitely been a long process to get here.

I also find it interesting to see which articles are driving my traffic. This post is my 70th article and here are the top 5 articles over the lifetime of this blog:

From a personal perspective, one of the articles I refer to the most in my own usage (and am personally proud of) is this one:

Combined, these 5 articles drive 35% of the traffic to the site over this time frame. Some of the articles have been around a lot longer so at some point in the future I might try to adjust these numbers based on the length of time they have been published.

As far as where the traffic comes from, about 85% of the daily traffic is driven by organic search. I would try to given you more details but after converting the site to serve over ssl, the search integration with google broke and for the life of me, I can not figure out how to get the search console to link back to google analytics.

Site Costs and Revenue

There are many options for hosting a blog. Overall, I have been very happy with the static blog hosting using pelican. When the blog started, the AWS costs were pretty minimal. As the traffic has grown, the costs have started to add up. In order to give you a sense for how much it costs to run the blog, here are the year to date costs for AWS:

AWS Costs

The costs started to rise in May and that’s when I realized that my RSS feed was getting really big and was consuming a lot of my bandwidth. After making the simple change described in the tweet below, costs went down considerably.

One of my other big costs is disqus. I think comments are important but I really dislike the distracting ads that could be shown on the site. I decided to pay $108/year in order to remove the disqus ads. I think it’s a good investment.

In July 2018, I started my mailing list and it has grown to over 2200 subscribers in that time. The one area I am not happy with is the cost of Mailchimp. It now costs $34.99/month for my list which is a lot considering the low volume of email I send. I will likely be looking for another solution in the upcoming months.

The only direct source of revenue I get from the blog is when someone purchases something from my affiliate links. To be honest, most months I generate about enough to almost pay for my AWS costs. Jeff Bezos giveth and Jeff Bezos taketh away!

Closing Thoughts

Clearly I’m not making enough to retire early. So, why am I doing it? I have two main motivations.

First, I want to continue to learn about python. When I started the blog, I knew python but very little about pandas, scikit-learn and python data visualization. Over the past 5 years, I have learned a lot. Learning about concepts and writing them on this blog has been really helpful in expanding my python and data science knowledge.

The second reason is that I want to give back to the python community. Python has been a very useful tool for me and I think it can help a lot of other people. I hope that in some small way this blog has helped others. The other community benefit is that the blog gives me a reason (or excuse) to participate more consistently in the python community. Without the blog, I would have a lot less reason to actively participate in this wonderful community.

I also have a more selfish motivation. At some point in the future, I would like make a move where I am able to spend more time focusing on python. I do not know exactly what that will look like but I suspect this blog will play a key role in that future state.

As far as changes go, I would like to update the site’s style so it looks more modern and less like the default template. I also want to figure out a better cadence for sending content to my email list. There are several articles that I need to update to reflect the most recent changes in python.

Going forward, I will likely continue creating the same type of content. I am always interested in learning about the types of articles you would like to see so please comment below if you have any ideas. I can not guarantee I will write about it but I will do some research and put it on my list for potential future topics.

Thanks again for all your support over the past 5 years and I look forward to seeing what the next 5 will bring!

Credits

Photo by Elisha Terada on Unsplash

September 17, 2019 12:20 PM UTC


Kushal Das

Permanent Record: the life of Edward Snowden

book cover

The personal life and thinking of the ordinary person who did an extraordinary thing.

A fantastic personal narrative of his life and thinking process. The book does not get into technical details, but, it will make sure that people relate to the different events mentioned in the book. It tells the story of a person who is born into the system and grew up to become part of the system, and then learns to question the same system.

I bought the book at midnight on Kindle (I also ordered the physical copies), slept for 3 hours in between and finished it off in the morning. Anyone born in 80s will find so many similarities as an 80s kid. Let it be the Commodore 64 as the first computer we saw or basic as the first-ever programming language to try. The lucky ones also got Internet access and learned to roam around of their own and build their adventure along with the busy telephone lines (which many times made the family members unhappy).

If you are someone from the technology community, I don't think you will find Ed's life was not as much different than yours. It has a different scenario and different key players, but, you will be able to match the progress in life like many other tech workers like ourselves.

Maybe you are reading the book just to learn what happened, or maybe you want to know why. But, I hope this book will help to think about the decisions you make in your life and how that affects the rest of the world. Let it be a group picture posted on Facebook or writing the next new tool for the intelligence community.

Go ahead and read the book, and when you are finished, make sure you pass it across to your friend, or buy them new copies. If you have some free time, you may consider to run a Tor relay or a bridge, a simple step will help many around the world.

On a side note, the book mentions SecureDrop project at the very end, and today is also the release of SecureDrop 1.0.0 (the same day of the book release).

September 17, 2019 04:44 AM UTC


Codementor

Top programming languages of 2019

The most popular languages according to the world’s largest organization for engineering and applied science. It can be hard to gauge which programming language to learn — should you go for the...

September 17, 2019 04:32 AM UTC


Moshe Zadka

Adding Methods Retroactively

The following post was originally published on OpenSource.com as part of a series on seven libraries that help solve common problems.

Imagine you have a "shapes" library. We have a Circle class, a Square class, etc.

A Circle has a radius, a Square has a side, and maybe Rectangle has height and width. The library already exists: we do not want to change it.

However, we do want to add an area calculation. If this was our library, we would just add an area method, so that we can call shape.area(), and not worry about what the shape is.

While it is possible to reach into a class and add a method, this is a bad idea: nobody expects their class to grow new methods, and things might break in weird ways.

Instead, the singledispatch function in functools can come to our rescue:

@singledispatch
def get_area(shape):
    raise NotImplementedError("cannot calculate area for unknown shape",
                              shape)

The "base" implementation for the get_area function just fails. This makes sure that if we get a new shape, we will cleanly fail instead of returning a nonsense result.

@get_area.register(Square)
def _get_area_square(shape):
    return shape.side ** 2
@get_area.register(Circle)
def _get_area_circle(shape):
    return math.pi * (shape.radius ** 2)

One nice thing about doing things this way is that if someone else writes a new shape that is intended to play well with our code, they can implement the get_area themselves:

from area_calculator import get_area

@attr.s(auto_attribs=True, frozen=True)
class Ellipse:
    horizontal_axis: float
    vertical_axis: float

@get_area.register(Ellipse)
def _get_area_ellipse(shape):
    return math.pi * shape.horizontal_axis * shape.vertical_axis

Calling get_area is straightforward:

print(get_area(shape))

This means we can change a function that has a long if isintance()/elif isinstance() chain to work this way, without changing the interface. The next time you are tempted to check if isinstance, try using singledispatch!

September 17, 2019 01:00 AM UTC

September 16, 2019


Roberto Alsina

Episodio 8: Complejo y Complicado

Un intento (probablemente fallido) de explicar complejidad algorítmica, o por lo menos lo más básico del tema sin complicarla demasiado.

September 16, 2019 09:45 PM UTC


Rene Dudfield

post modern C tooling - draft

DRAFT - I'm still working on this, but it's already useful and I'd like some feedback - so I decided to share it early.
 



In 2001 or so people started using the phrase "Modern C++". So now that it's 2019, I guess we're in the post modern era? Anyway, this isn't a post about C++ code, but some of this information applies there too.

This is a post about contemporary C tooling. Tooling for making higher quality C, faster.
The C language has no logo, but it's everywhere.

Welcome to the post modern era.

Some of the C++ people have pulled off one of the cleverest and sneakiest tricks ever. They required 'modern' C99 and C11 features in 'recent' C++ standards. Microsoft has famously still clung onto some 80s version of C with their compiler for the longest time. So it's been a decade of hacks for people writing portable code in C. For a while I thought we'd be stuck in the 80s with C89 forever. However, now that some C99 and C11 features are more widely available in the Microsoft compiler, we can use these features in highly portable code (but forget about C17/C18 ISO/IEC 9899:2018/C2X stuff!!).

So, we have some pretty modern language features in C with C11.  But what about tooling?

Tools and protection for our feet.

C, whilst a work horse being used in everything from toasters, trains, phones, web browsers, ... (everything basically) - is also an excellent tool for shooting yourself in the foot.

Noun

footgun (plural footguns)
  1. (informal, humorous, derogatory) Any feature whose addition to a product results in the user shooting themselves in the foot. C.

Tools like linters, test coverage checkers, static analyzers, memory checkers, documentation generators, thread checkers, continuous integration, nice error messages, ... and such help protect our feet.

How do we do continuous delivery with a language that lets us do the most low level footgunie things ever? On a dozen CPU architectures, 32 bit, 64bit, little endian, big endian, 64 bit with 32bit pointers (wat?!?), with multiple compilers, on a dozen different OS, with dozens of different versions of your dependencies?

Surely there won't be enough time to do releases, and have time left to eat my vegan shaved ice desert after lunch?



Reverse debugger

Normally a program runs forwards. But what about when you are debugging and you want to run the program backwards?

How do you tame non determinism to allow a program to run the same way it did when it crashed? In C and with threads some times it's really hard to reproduce problems.

rr helps with this. It's actual magic.

https://rr-project.org/



Portable building, and package management

C doesn't have a package manager... or does it?

Ever since Debian dpkg, Redhat rpm, and Perl started doing package management in the early 90s people world wide have been able to share pieces of software more easily.

Following those systems, many other systems like Ruby gems, JavaScript npm, and Pythons cheese shop came into being. Allowing many to share code easily.

But what about C? How can we define dependencies on different 'packages' or libraries and have them compile on different platforms?

How do we build with Microsofts compiler, with gcc, with clang, or Intels C compiler? How do we build on Mac, on Windows, on Ubuntu, on Arch linux?

Part of the answer to that is CMake. "Modern CMake" lets you define your dependencies,


There are several 

https://conan.io/




Testing coverage.

Tests let us know that some certain function is running ok. Which code do we still need to test?

gcov, a tool you can use in conjunction with GCC to test code coverage in your programs.
lcov, LCOV is a graphical front-end for GCC's coverage testing tool gcov.


Instructions from codecov.io on how to use it with C, and clang or gcc. (codecov.io is free for public open source repos).
https://github.com/codecov/example-c


Here's documentation for how CPython gets coverage results for C.
 https://devguide.python.org/coverage/#measuring-coverage-of-c-code-with-gcov-and-lcov

Here is the CPython Travis CI configuration they use.
https://github.com/python/cpython/blob/master/.travis.yml#L69
    - os: linux
language: c
compiler: gcc
env: OPTIONAL=true
addons:
apt:
packages:
- lcov
- xvfb
before_script:
- ./configure
- make coverage -s -j4
# Need a venv that can parse covered code.
- ./python -m venv venv
- ./venv/bin/python -m pip install -U coverage
- ./venv/bin/python -m test.pythoninfo
script:
# Skip tests that re-run the entire test suite.
- xvfb-run ./venv/bin/python -m coverage run --pylib -m test --fail-env-changed -uall,-cpu -x test_multiprocessing_fork -x test_multiprocessing_forkserver -x test_multiprocessing_spawn -x test_concurrent_futures
after_script: # Probably should be after_success once test suite updated to run under coverage.py.
# Make the `coverage` command available to Codecov w/ a version of Python that can parse all source files.
- source ./venv/bin/activate
- make coverage-lcov
- bash > (curl -s https://codecov.io/bash)




Static analysis

"Static analysis has not been helpful in finding bugs in SQLite." -- https://www.sqlite.org/testing.html

According to David Wheeler in "How to Prevent the next Heartbleed" (https://dwheeler.com/essays/heartbleed.html#static-not-found the security problem with a logo, a website, and a marketing team) only one static analysis tool found the Heartbleed vulnerability before it was known. This tool is called CQual++. One reason for projects not using these tools is that they have been (and some still are) hard to use. The LLVM project only started using the clang static analysis tool on it's own projects recently for example. However, since Heartbleed tools have improved in both usability and their ability to detect issues.

I think it's generally accepted that static analysis tools are incomplete, in that each tool does not guarantee detecting every problem or even always detecting the same issues all the time. Using multiple tools can therefore be said to find multiple different types of problems.

Compiling code with gcc "-Wall -Wextra -pedantic" options catches quite a number of potential or actual problems (https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html). Other compilers check different things as well. So using multiple compilers with their warnings can find plenty of different types of issues for you.

Note, that static analysis can be much slower than the analysis usually provided by compilation. It trades off more CPU time for (perhaps) better results.

In the talk "Clang Static Analysis" (https://www.youtube.com/watch?v=UcxF6CVueDM) talks about an LLVM tool called codechecker (https://github.com/Ericsson/codechecker). Clang's Static Analyzer, a free static analyzer based on Clang.  Not that XCode IDE on Mac includes the clang static analyser.

Visual studio by Microsoft can also do static code analysis too. ( https://docs.microsoft.com/en-us/visualstudio/code-quality/code-analysis-for-c-cpp-overview?view=vs-2017)

cppcheck focuses of low false positives and can find many actual problems.
Coverity, a commercial static analyzer, free for open source developers
CppDepend, a commercial static analyzer based on Clang
codechecker, https://github.com/Ericsson/codechecker
cpplint, Cpplint is a command-line tool to check C/C++ files for style issues following Google's C++ style guide.
Awesome static analysis, a page full of static analysis tools for C/C++. https://github.com/mre/awesome-static-analysis#cc


Probably one of the most useful parts of static analysis is being able to write your own checks. This allows you to do checks specific to your code base in which general checks will not work. One example of this is the gcc cpychecker (https://gcc-python-plugin.readthedocs.io/en/latest/cpychecker.html). With this, gcc can find within CPython extensions written in C reference counting bugs, and NULL pointer dereferences, and other types of issues. You can write custom checkers with LLVM as well in the "Checker Developer Manual" (https://clang-analyzer.llvm.org/checker_dev_manual.html)




Performance profiling and measurement

“The objective (not always attained) in creating high-performance software is to make the software able to carry out its appointed tasks so rapidly that it responds instantaneously, as far as the user is concerned.”  Michael Abrash. “Michael Abrash’s Graphics Programming Black Book.”
Reducing energy usage, and run time requirements of apps can often be a requirement or very necessary. For a mobile or embedded application it can mean the difference of being able to run the program at all. Performance can directly be related to user happiness but also to the financial performance of a piece of software.

But how to we measure the performance of a program, and how to we know what parts of a program need improvement? Tooling can help.

Valgrind

Valgrind has its own section here because it does lots of different things for us. It's a great tool, or set of tools for improving your programs. It used to be available only on linux, but is now also available on MacOS.

Apparently Valgrind would have caught the heartbleed issue if it was used with a fuzzer.

http://valgrind.org/docs/manual/quick-start.html

Apple Performance Tools

Apple provides many performance related development tools. Along with the gcc and llvm based tools, the main tool is called Instruments. Instruments (part of Xcode) allows you to record and analyse programs for lots of different aspects of performance - including graphics, memory activity, file system, energy and other program events. By being able to record and analyse different types of events together can make it convienient to find performance issues.

Many of the low level parts of the tools in XCode are made open source through the LLVM project. See "LLVM Machine Code Analyzer" ( https://llvm.org/docs/CommandGuide/llvm-mca.html) as one example.

Free and Open Source performance tools.



Microsoft performance tools.





Caching builds

https://ccache.samba.org/

ccache is very useful for reducing the compile time of large C projects. Especially when you are doing a 'rebuild from scratch'. This is because ccache can cache the compilation of parts in this situation when the files do not change.
http://itscompiling.eu/2017/02/19/speed-cpp-compilation-compiler-cache/

This is also useful for speeding up CI builds, and especially when large parts of the code base rarely change.


Distributed building.


distcc https://github.com/distcc/distcc
icecream https://github.com/icecc/icecream


Complexity of code.


How complex is your code?
http://www.gnu.org/software/complexity/

complexity src_c/*.c


Testing your code on different OS/architectures.

Sometimes you need to be able to fix an issue on an OS or architecture that you don't have access to. Luckily these days there are many tools available to quickly use a different system through emulation, or container technology.


Vagrant
Virtualbox
Docker
Launchpad, compile and run tests on many architectures.
Mini cloud (ppc machines for debugging)

If you pay Travis CI, they allow you to connect to the testing host with ssh when a test fails.


Code Formatting

clang-format

clang-format - rather than manually fix various formatting errors found with a linter, many projects are just using clang-format to format the code into some coding standard.



Services

LGTM is an 'automated code review tool' with github (and other code repos) support. https://lgtm.com/help/lgtm/about-automated-code-review

Coveralls provides a store for test coverage results with github (and other code repos) support. https://coveralls.io/



How are other projects tested?

We can learn a lot by how other C projects are going about their business today.
Also, thanks to CI testing tools defining things in code we can see how automated tests are run on services like Travis CI and Appveyor.

SQLite

"How SQLite Is Tested"

Curl

"Testing Curl"
https://github.com/curl/curl/blob/master/.travis.yml

Python

"How is CPython tested?"
https://github.com/python/cpython/blob/master/.travis.yml

OpenSSL

"How is OpenSSL tested?"

https://github.com/openssl/openssl/blob/master/.travis.yml
They use Coverity too: https://github.com/openssl/openssl/pull/9805
https://github.com/openssl/openssl/blob/master/fuzz/README.md

libsdl

"How is SDL tested?" [No response]


Linux

As of early 2019, Linux used no unit testing within the kernel tree (some unit tests exist outside of the kernel tree).

There's no in-tree unit tests, but linux is probably one of the most highly tested pieces of code there is.

Linux relies a lot on community testing. With thousands of developers working on Linux every day, that is a lot of people testing things out. Additionally, because all of the source code is available for Linux many more people are able to try things out, and test things on different systems.


https://stackoverflow.com/questions/3177338/how-is-the-linux-kernel-tested

https://www.linuxjournal.com/content/linux-kernel-testing-and-debugging


Haproxy

https://github.com/haproxy/haproxy/blob/master/.travis.yml







September 16, 2019 07:22 PM UTC


Stack Abuse

Reading and Writing YAML to a File in Python

Introduction

In this tutorial, we're going to learn how to use the YAML library in Python 3. YAML stands for Yet Another Markup Language.

In recent years it has become very popular for its use in storing data in a serialized manner for configuration files. Since YAML essentially is a data format, the YAML library is quite brief, as the only functionality required of it is the ability to parse YAML formatted files.

In this article we will start with seeing how data is stored in a YAML file, followed by loading that data into a Python object. Lastly, we will learn how to store a Python object in a YAML file. So, let's begin.

Before we move further, there are a few prerequisites for this tutorial. You should have a basic understanding of Python's syntax, and/or have done at least beginner level programming experience with some other language. Other than that, the tutorial is quite simple and easy to follow for beginners.

Installation

The installation process for YAML is fairly straight forward. There are two ways to do it; we'll start with the easy one first:

Method 1: Via Pip

The easiest way to install the YAML library in Python is via the pip package manager. If you have pip installed in your system, run the following command to download and install YAML:

$ pip install pyyaml

Method 2: Via Source

In case you do not have pip installed, or are facing some problem with the method above, you can go to the library's source page. Download the repository as a zip file, open the terminal or command prompt, and navigate to the directory where the file is downloaded. Once you are there, run the following command:

$ python setup.py install

YAML Code Examples

In this section, we will learn how to handle (manipulate) YAML files, starting with how to read them i.e. how to load them into our Python script so that we can use them as per our needs. So, let's start.

Reading YAML Files in Python

In this section, we will see how to read YAML files in Python.

Let's start by making two YAML formatted files.

The contents of the first file are as follows:

# fruits.yaml file

apples: 20
mangoes: 2
bananas: 3
grapes: 100
pineapples: 1

The contents of the second file are as follows:

# categories.yaml file

sports:

  - soccer
  - football
  - basketball
  - cricket
  - hockey
  - table tennis

countries:

  - Pakistan
  - USA
  - India
  - China
  - Germany
  - France
  - Spain

You can see that the fruits.yaml and categories.yaml files contain different types of data. The former contains information only about one entity, i.e. fruits, while the latter contains information about sports and countries.

Let's now try to read the data from the two files that we created using a Python script. The load() method from the yaml module can be used to read YAML files. Look at the following script:

# process_yaml.py file

import yaml

with open(r'E:\data\fruits.yaml') as file:
    # The FullLoader parameter handles the conversion from YAML
    # scalar values to Python the dictionary format
    fruits_list = yaml.load(file, Loader=yaml.FullLoader)

    print(fruits_list)

Output:

{ 'apples': 20, 'mangoes': 2, 'bananas': 3, 'grapes': 100, 'pineapples': 1 }

In the script above we specified yaml.FullLoader as the value for the Loader parameter which loads the full YAML language, avoiding the arbitrary code execution. Instead of using the load function and then passing yaml.FullLoader as the value for the Loader parameter, you can also use the full_load() function, as we will see in the next example.

Let's now try and read the second YAML file in a similar manner using a Python script:

# read_categories.py file

import yaml

with open(r'E:\data\categories.yaml') as file:
    documents = yaml.full_load(file)

    for item, doc in documents.items():
        print(item, ":", doc)

Since there are 2 documents in the categories.yaml file, we ran a loop to read both of them.

Output:

sports : ['soccer', 'football', 'basketball', 'cricket', 'hockey', 'table tennis']
countries : ['Pakistan', 'USA', 'India', 'China', 'Germany', 'France', 'Spain']

As you can see from the last two examples, the library automatically handles the conversion of YAML formatted data to Python dictionaries and lists.

Writing YAML Files in Python

Now that we have learned how to convert a YAML file into a Python dictionary, let's try to do things the other way around i.e. serialize a Python dictionary and store it into a YAML formatted file. For this purpose, let's use the same dictionary that we got as an output from our last program.

import yaml

dict_file = [{'sports' : ['soccer', 'football', 'basketball', 'cricket', 'hockey', 'table tennis']},
{'countries' : ['Pakistan', 'USA', 'India', 'China', 'Germany', 'France', 'Spain']}]

with open(r'E:\data\store_file.yaml', 'w') as file:
    documents = yaml.dump(dict_file, file)

The dump() method takes the Python dictionary as the first, and a File object as the second parameter.

Once the above code executes, a file named store_file.yaml will be created in your current working directory.

# store_file.yaml file contents:

- sports:

  - soccer
  - football
  - basketball
  - cricket
  - hockey
  - table tennis
- countries:

  - Pakistan
  - USA
  - India
  - China
  - Germany
  - France
  - Spain

Another useful functionality that the YAML library offers for the dump() method is the sort_keys parameter. To show what it does, let's apply it on our first file, i.e. fruits.yaml:

import yaml

with open(r'E:\data\fruits.yaml') as file:
    doc = yaml.load(file, Loader=yaml.FullLoader)

    sort_file = yaml.dump(doc, sort_keys=True)
    print(sort_file)

Output:

apples: 20
bananas: 3
grapes: 100
mangoes: 2
pineapples: 1

You can see in the output that the fruits have been sorted in the alphabetical order.

Conclusion

In this brief tutorial, we learned how to install Python's YAML library (pyyaml) to manipulate YAML formatted files. We covered loading the contents of a YAML file into our Python program as dictionaries, as well as serializing Python dictionaries in to YAML files and storing their keys. The library is quite brief and only offers basic functionalities.

September 16, 2019 06:46 PM UTC


NumFOCUS

Introducing Our Newest Corporate Sponsorship Prospectus

The post Introducing Our Newest Corporate Sponsorship Prospectus appeared first on NumFOCUS.

September 16, 2019 05:14 PM UTC


TechBeamers Python

Python Multiple Inheritance (with Examples)

In this tutorial, we’ll describe Python Multiple Inheritance concept and explain how to use it in your programs. We’ll also cover multilevel inheritance, the super() function, and focus on the method resolution order. In the previous tutorial, we have gone through Python Class and Python (Single) Inheritance. There, you have seen that a child class inherits from a base class. However, Multiple Inheritance is a feature where a class can derive attributes and methods from more than one base classes. Hence, it creates a high level of complexity and ambiguity and known as the diamond problem in the technical world.

The post Python Multiple Inheritance (with Examples) appeared first on Learn Programming and Software Testing.

September 16, 2019 05:07 PM UTC


Real Python

PyGame: A Primer on Game Programming in Python

When I started learning computer programming late in the last millennium, it was driven by my desire to write computer games. I tried to figure out how to write games in every language and on every platform I learned, including Python. That’s how I discovered pygame and learned how to use it to write games and other graphical programs. At the time, I really wanted a primer on pygame.

By the end of this article, you’ll be able to:

This primer assumes you have a basic understanding of writing Python programs, including user-defined functions, imports, loops, and conditionals. You should also be familiar with how to open files on your platform. A basic understanding of object-oriented Python is helpful as well. pygame works with most versions of Python, but Python 3.6 is recommended and used throughout this article.

You can get all of the code in this article to follow along:

Clone Repo: Click here to clone the repo you'll use to learn how to use PyGame in this tutorial.

Background and Setup

pygame is a Python wrapper for the SDL library, which stands for Simple DirectMedia Layer. SDL provides cross-platform access to your system’s underlying multimedia hardware components, such as sound, video, mouse, keyboard, and joystick. pygame started life as a replacement for the stalled PySDL project. The cross-platform nature of both SDL and pygame means you can write games and rich multimedia Python programs for every platform that supports them!

To install pygame on your platform, use the appropriate pip command:

$ pip install pygame

You can verify the install by loading one of the examples that comes with the library:

$ python3 -m pygame.examples.aliens

If a game window appears, then pygame is installed properly! If you run into problems, then the Getting Started guide outlines some known issues and caveats for all platforms.

Basic PyGame Program

Before getting down to specifics, let’s take a look at a basic pygame program. This program creates a window, fills the background with white, and draws a blue circle in the middle of it:

 1 # Simple pygame program
 2 
 3 # Import and initialize the pygame library
 4 import pygame
 5 pygame.init()
 6 
 7 # Set up the drawing window
 8 screen = pygame.display.set_mode([500, 500])
 9 
10 # Run until the user asks to quit
11 running = True
12 while running:
13 
14     # Did the user click the window close button?
15     for event in pygame.event.get():
16         if event.type == pygame.QUIT:
17             running = False
18 
19     # Fill the background with white
20     screen.fill((255, 255, 255))
21 
22     # Draw a solid blue circle in the center
23     pygame.draw.circle(screen, (0, 0, 255), (250, 250), 75)
24 
25     # Flip the display
26     pygame.display.flip()
27 
28 # Done! Time to quit.
29 pygame.quit()

When you run this program, you’ll see a window that looks like this:

A simple pygame program

Let’s break this code down, section by section:

That’s the pygame version of “Hello, World.” Now let’s dig a little deeper into the concepts behind this code.

PyGame Concepts

As pygame and the SDL library are portable across different platforms and devices, they both need to define and work with abstractions for various hardware realities. Understanding those concepts and abstractions will help you design and develop your own games.

Initialization and Modules

The pygame library is composed of a number of Python constructs, which include several different modules. These modules provide abstract access to specific hardware on your system, as well as uniform methods to work with that hardware. For example, display allows uniform access to your video display, while joystick allows abstract control of your joystick.

After importing the pygame library in the example above, the first thing you did was initialize PyGame using pygame.init(). This function calls the separate init() functions of all the included pygame modules. Since these modules are abstractions for specific hardware, this initialization step is required so that you can work with the same code on Linux, Windows, and Mac.

Displays and Surfaces

In addition to the modules, pygame also includes several Python classes, which encapsulate non-hardware dependent concepts. One of these is the Surface which, at its most basic, defines a rectangular area on which you can draw. Surface objects are used in many contexts in pygame. Later you’ll see how to load an image into a Surface and display it on the screen.

In pygame, everything is viewed on a single user-created display, which can be a window or a full screen. The display is created using .set_mode(), which returns a Surface representing the visible part of the window. It is this Surface that you pass into drawing functions like pygame.draw.circle(), and the contents of that Surface are pushed to the display when you call pygame.display.flip().

Images and Rects

Your basic pygame program drew a shape directly onto the display’s Surface, but you can also work with images on the disk. The image module allows you to load and save images in a variety of popular formats. Images are loaded into Surface objects, which can then be manipulated and displayed in numerous ways.

As mentioned above, Surface objects are represented by rectangles, as are many other objects in pygame, such as images and windows. Rectangles are so heavily used that there is a special Rect class just to handle them. You’ll be using Rect objects and images in your game to draw players and enemies, and to manage collisions between them.

Okay, that’s enough theory. Let’s design and write a game!

Basic Game Design

Before you start writing any code, it’s always a good idea to have some design in place. Since this is a tutorial game, let’s design some basic gameplay for it as well:

When he was describing software projects, a former colleague of mine used to say, “You don’t know what you do until you know what you don’t do.” With that in mind, here are some things that won’t be covered in this tutorial:

You’re free to try your hand at adding these and other features to your own program.

Let’s get started!

Importing and Initializing PyGame

After you import pygame, you’ll also need to initialize it. This allows pygame to connect its abstractions to your specific hardware:

 1 # Import the pygame module
 2 import pygame
 3 
 4 # Import pygame.locals for easier access to key coordinates
 5 # Updated to conform to flake8 and black standards
 6 from pygame.locals import (
 7     K_UP,
 8     K_DOWN,
 9     K_LEFT,
10     K_RIGHT,
11     K_ESCAPE,
12     KEYDOWN,
13     QUIT,
14 )
15 
16 # Initialize pygame
17 pygame.init()

The pygame library defines many things besides modules and classes. It also defines some local constants for things like keystrokes, mouse movements, and display attributes. You reference these constants using the syntax pygame.<CONSTANT>. By importing specific constants from pygame.locals, you can use the syntax <CONSTANT> instead. This will save you some keystrokes and improve overall readability.

Setting Up the Display

Now you need something to draw on! Create a screen to be the overall canvas:

 1 # Import the pygame module
 2 import pygame
 3 
 4 # Import pygame.locals for easier access to key coordinates
 5 # Updated to conform to flake8 and black standards
 6 from pygame.locals import (
 7     K_UP,
 8     K_DOWN,
 9     K_LEFT,
10     K_RIGHT,
11     K_ESCAPE,
12     KEYDOWN,
13     QUIT,
14 )
15 
16 # Initialize pygame
17 pygame.init()
18 
19 # Define constants for the screen width and height
20 SCREEN_WIDTH = 800
21 SCREEN_HEIGHT = 600
22 
23 # Create the screen object
24 # The size is determined by the constant SCREEN_WIDTH and SCREEN_HEIGHT
25 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

You create the screen to use by calling pygame.display.set_mode() and passing a tuple or list with the desired width and height. In this case, the window is 800x600, as defined by the constants SCREEN_WIDTH and SCREEN_HEIGHT on lines 20 and 21. This returns a Surface which represents the inside dimensions of the window. This is the portion of the window you can control, while the OS controls the window borders and title bar.

If you run this program now, then you’ll see a window pop up briefly and then immediately disappear as the program exits. Don’t blink or you might miss it! In the next section, you’ll focus on the main game loop to ensure that your program exits only when given the correct input.

Setting Up the Game Loop

Every game from Pong to Fortnite uses a game loop to control gameplay. The game loop does four very important things:

  1. Processes user input
  2. Updates the state of all game objects
  3. Updates the display and audio output
  4. Maintains the speed of the game

Every cycle of the game loop is called a frame, and the quicker you can do things each cycle, the faster your game will run. Frames continue to occur until some condition to exit the game is met. In your design, there are two conditions that can end the game loop:

  1. The player collides with an obstacle. (You’ll cover collision detection later.)
  2. The player closes the window.

The first thing the game loop does is process user input to allow the player to move around the screen. Therefore, you need some way to capture and process a variety of input. You do this using the pygame event system.

Processing Events

Key presses, mouse movements, and even joystick movements are some of the ways in which a user can provide input. All user input results in an event being generated. Events can happen at any time and often (but not always) originate outside the program. All events in pygame are placed in the event queue, which can then be accessed and manipulated. Dealing with events is referred to as handling them, and the code to do so is called an event handler.

Every event in pygame has an event type associated with it. For your game, the event types you’ll focus on are keypresses and window closure. Keypress events have the event type KEYDOWN, and the window closure event has the type QUIT. Different event types may also have other data associated with them. For example, the KEYDOWN event type also has a variable called key to indicate which key was pressed.

You access the list of all active events in the queue by calling pygame.event.get(). You then loop through this list, inspect each event type, and respond accordingly:

27 # Variable to keep the main loop running
28 running = True
29 
30 # Main loop
31 while running:
32     # Look at every event in the queue
33     for event in pygame.event.get():
34         # Did the user hit a key?
35         if event.type == KEYDOWN:
36             # Was it the Escape key? If so, stop the loop.
37             if event.key == K_ESCAPE:
38                 running = False
39 
40         # Did the user click the window close button? If so, stop the loop.
41         elif event.type == QUIT:
42             running = False

Let’s take a closer look at this game loop:

When you add these lines to the previous code and run it, you’ll see a window with a blank or black screen:

An empty, but persistent, pygame window

The window won’t disappear until you press the Esc key, or otherwise trigger a QUIT event by closing the window.

Drawing on the Screen

In the sample program, you drew on the screen using two commands:

  1. screen.fill() to fill the background
  2. pygame.draw.circle() to draw a circle

Now you’ll learn about a third way to draw to the screen: using a Surface.

Recall that a Surface is a rectangular object on which you can draw, like a blank sheet of paper. The screen object is a Surface, and you can create your own Surface objects separate from the display screen. Let’s see how that works:

44 # Fill the screen with white
45 screen.fill((255, 255, 255))
46 
47 # Create a surface and pass in a tuple containing its length and width
48 surf = pygame.Surface((50, 50))
49 
50 # Give the surface a color to separate it from the background
51 surf.fill((0, 0, 0))
52 rect = surf.get_rect()

After the screen is filled with white on line 45, a new Surface is created on line 48. This Surface is 50 pixels wide, 50 pixels tall, and assigned to surf. At this point, you treat it just like the screen. So on line, 51 you fill it with black. You can also access its underlying Rect using .get_rect(). This is stored as rect for later use.

Using .blit() and .flip()

Just creating a new Surface isn’t enough to see it on the screen. To do that, you need to blit the Surface onto another Surface. The term blit stands for Block Transfer, and .blit() is how you copy the contents of one Surface to another. You can only .blit() from one Surface to another, but since the screen is just another Surface, that’s not a problem. Here’s how you draw surf on the screen:

54 # This line says "Draw surf onto the screen at the center"
55 screen.blit(surf, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
56 pygame.display.flip()

The .blit() call on line 55 takes two arguments:

  1. The Surface to draw
  2. The location at which to draw it on the source Surface

The coordinates (SCREEN_WIDTH/2, SCREEN_HEIGHT/2) tell your program to place surf in the exact center of the screen, but it doesn’t quite look that way:

Blitting a surface onto the screen

The reason why the image looks off-center is that .blit() puts the top-left corner of surf at the location given. If you want surf to be centered, then you’ll have to do some math to shift it up and to the left. You can do this by subtracting the width and height of surf from the width and height of the screen, dividing each by 2 to locate the center, and then passing those numbers as arguments to screen.blit():

54 # Put the center of surf at the center of the display
55 surf_center = (
56     (SCREEN_WIDTH-surf.get_width())/2,
57     (SCREEN_HEIGHT-surf.get_height())/2
58 )
59 
60 # Draw surf at the new coordinates
61 screen.blit(surf, surf_center)
62 pygame.display.flip()

Notice the call to pygame.display.flip() after the call to blit(). This updates the entire screen with everything that’s been drawn since the last flip. Without the call to .flip(), nothing is shown.

Sprites

In your game design, the player starts on the left, and obstacles come in from the right. You can represent all the obstacles with Surface objects to make drawing everything easier, but how do you know where to draw them? How do you know if an obstacle has collided with the player? What happens when the obstacle flies off the screen? What if you want to draw background images that also move? What if you want your images to be animated? You can handle all these situations and more with sprites.

In programming terms, a sprite is a 2D representation of something on the screen. Essentially, it’s a picture. pygame provides a Sprite class, which is designed to hold one or several graphical representations of any game object that you want to display on the screen. To use it, you create a new class that extends Sprite. This allows you to use its built-in methods.

Players

Here’s how you use Sprite objects with the current game to define the player. Insert this code after line 18:

20 # Define a Player object by extending pygame.sprite.Sprite
21 # The surface drawn on the screen is now an attribute of 'player'
22 class Player(pygame.sprite.Sprite):
23     def __init__(self):
24         super(Player, self).__init__()
25         self.surf = pygame.Surface((75, 25))
26         self.surf.fill((255, 255, 255))
27         self.rect = self.surf.get_rect()

You first define Player by extending pygame.sprite.Sprite on line 22. Then .__init__() uses .super() to call the .__init__() method of Sprite. For more info on why this is necessary, you can read Supercharge Your Classes With Python super().

Next, you define and initialize .surf to hold the image to display, which is currently a white box. You also define and initialize .rect, which you’ll use to draw the player later. To use this new class, you need to create a new object and change the drawing code as well. Expand the code block below to see it all together:

 1 # Import the pygame module
 2 import pygame
 3 
 4 # Import pygame.locals for easier access to key coordinates
 5 # Updated to conform to flake8 and black standards
 6 from pygame.locals import (
 7     K_UP,
 8     K_DOWN,
 9     K_LEFT,
10     K_RIGHT,
11     K_ESCAPE,
12     KEYDOWN,
13     QUIT,
14 )
15 
16 # Define constants for the screen width and height
17 SCREEN_WIDTH = 800
18 SCREEN_HEIGHT = 600
19 
20 # Define a player object by extending pygame.sprite.Sprite
21 # The surface drawn on the screen is now an attribute of 'player'
22 class Player(pygame.sprite.Sprite):
23     def __init__(self):
24         super(Player, self).__init__()
25         self.surf = pygame.Surface((75, 25))
26         self.surf.fill((255, 255, 255))
27         self.rect = self.surf.get_rect()
28 
29 # Initialize pygame
30 pygame.init()
31 
32 # Create the screen object
33 # The size is determined by the constant SCREEN_WIDTH and SCREEN_HEIGHT
34 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
35 
36 # Instantiate player. Right now, this is just a rectangle.
37 player = Player()
38 
39 # Variable to keep the main loop running
40 running = True
41 
42 # Main loop
43 while running:
44     # for loop through the event queue
45     for event in pygame.event.get():
46         # Check for KEYDOWN event
47         if event.type == KEYDOWN:
48             # If the Esc key is pressed, then exit the main loop
49             if event.key == K_ESCAPE:
50                 running = False
51         # Check for QUIT event. If QUIT, then set running to false.
52         elif event.type == QUIT:
53             running = False
54 
55     # Fill the screen with black
56     screen.fill((0, 0, 0))
57 
58     # Draw the player on the screen
59     screen.blit(player.surf, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
60 
61     # Update the display
62     pygame.display.flip()

Run this code. You’ll see a white rectangle at roughly the middle of the screen:

Basic player sprite being drawn

What do you think would happen if you changed line 59 to screen.blit(player.surf, player.rect)? Try it and see:

55 # Fill the screen with black
56 screen.fill((0, 0, 0))
57 
58 # Draw the player on the screen
59 screen.blit(player.surf, player.rect)
60 
61 # Update the display
62 pygame.display.flip()

When you pass a Rect to .blit(), it uses the coordinates of the top left corner to draw the surface. You’ll use this later to make your player move!

User Input

So far, you’ve learned how to set up pygame and draw objects on the screen. Now, the real fun starts! You’ll make the player controllable using the keyboard.

Earlier, you saw that pygame.event.get() returns a list of the events in the event queue, which you scan for KEYDOWN event types. Well, that’s not the only way to read keypresses. pygame also provides pygame.event.get_pressed(), which returns a dictionary containing all the current KEYDOWN events in the queue.

Put this in your game loop right after the event handling loop. This returns a dictionary containing the keys pressed at the beginning of every frame:

54 # Get the set of keys pressed and check for user input
55 pressed_keys = pygame.key.get_pressed()

Next, you write a method in Player to accepts that dictionary. This will define the behavior of the sprite based off the keys that are pressed. Here’s what that might look like:

29 # Move the sprite based on user keypresses
30 def update(self, pressed_keys):
31     if pressed_keys[K_UP]:
32         self.rect.move_ip(0, -5)
33     if pressed_keys[K_DOWN]:
34         self.rect.move_ip(0, 5)
35     if pressed_keys[K_LEFT]:
36         self.rect.move_ip(-5, 0)
37     if pressed_keys[K_RIGHT]:
38         self.rect.move_ip(5, 0)

K_UP, K_DOWN, K_LEFT, and K_RIGHT correspond to the arrow keys on the keyboard. If the dictionary entry for that key is True, then that key is down, and you move the player .rect in the proper direction. Here you use .move_ip(), which stands for move in place, to move the current Rect.

Then you can call .update() every frame to move the player sprite in response to keypresses. Add this call right after the call to .get_pressed():

52 # Main loop
53 while running:
54     # for loop through the event queue
55     for event in pygame.event.get():
56         # Check for KEYDOWN event
57         if event.type == KEYDOWN:
58             # If the Esc key is pressed, then exit the main loop
59             if event.key == K_ESCAPE:
60                 running = False
61         # Check for QUIT event. If QUIT, then set running to false.
62         elif event.type == QUIT:
63             running = False
64 
65     # Get all the keys currently pressed
66     pressed_keys = pygame.key.get_pressed()
67 
68     # Update the player sprite based on user keypresses
69     player.update(pressed_keys)
70 
71     # Fill the screen with black
72     screen.fill((0, 0, 0))

Now you can move your player rectangle around the screen with the arrow keys:

Keypresses moving a sprite in pygame

You may notice two small problems:

  1. The player rectangle can move very fast if a key is held down. You’ll work on that later.
  2. The player rectangle can move off the screen. Let’s solve that one now.

To keep the player on the screen, you need to add some logic to detect if the rect is going to move off screen. To do that, you check whether the rect coordinates have moved beyond the screen’s boundary. If so, then you instruct the program to move it back to the edge:

25 # Move the sprite based on user keypresses
26 def update(self, pressed_keys):
27     if pressed_keys[K_UP]:
28         self.rect.move_ip(0, -5)
29     if pressed_keys[K_DOWN]:
30         self.rect.move_ip(0, 5)
31     if pressed_keys[K_LEFT]:
32         self.rect.move_ip(-5, 0)
33     if pressed_keys[K_RIGHT]:
34         self.rect.move_ip(5, 0)
35 
36     # Keep player on the screen
37     if self.rect.left < 0:
38         self.rect.left = 0
39     if self.rect.right > SCREEN_WIDTH:
40         self.rect.right = SCREEN_WIDTH
41     if self.rect.top <= 0:
42         self.rect.top = 0
43     if self.rect.bottom >= SCREEN_HEIGHT:
44         self.rect.bottom = SCREEN_HEIGHT

Here, instead of using .move(), you just change the corresponding coordinates of .top, .bottom, .left, or .right directly. Test this, and you’ll find the player rectangle can no longer move off the screen.

Now let’s add some enemies!

Enemies

What’s a game without enemies? You’ll use the techniques you’ve already learned to create a basic enemy class, then create a lot of them for your player to avoid. First, import the random library:

 4 # Import random for random numbers
 5 import random

Then create a new sprite class called Enemy, following the same pattern you used for Player:

55 # Define the enemy object by extending pygame.sprite.Sprite
56 # The surface you draw on the screen is now an attribute of 'enemy'
57 class Enemy(pygame.sprite.Sprite):
58     def __init__(self):
59         super(Enemy, self).__init__()
60         self.surf = pygame.Surface((20, 10))
61         self.surf.fill((255, 255, 255))
62         self.rect = self.surf.get_rect(
63             center=(
64                 random.randint(SCREEN_WIDTH + 20, SCREEN_WIDTH + 100),
65                 random.randint(0, SCREEN_HEIGHT),
66             )
67         )
68         self.speed = random.randint(5, 20)
69 
70     # Move the sprite based on speed
71     # Remove the sprite when it passes the left edge of the screen
72     def update(self):
73         self.rect.move_ip(-self.speed, 0)
74         if self.rect.right < 0:
75             self.kill()

There are four notable differences between Enemy and Player:

  1. On lines 62 to 67, you update rect to be a random location along the right edge of the screen. The center of the rectangle is just off the screen. It’s located at some position between 20 and 100 pixels away from the right edge, and somewhere between the top and bottom edges.

  2. On line 68, you define .speed as a random number between 5 and 20. This specifies how fast this enemy moves towards the player.

  3. On lines 73 to 76, you define .update(). It takes no arguments since enemies move automatically. Instead, .update() moves the enemy toward the left side of the screen at the .speed defined when it was created.

  4. On line 74, you check whether the enemy has moved off-screen. To make sure the Enemy is fully off the screen and won’t just disappear while it’s still visible, you check that the right side of the .rect has gone past the left side of the screen. Once the enemy is off-screen, you call .kill() to prevent it from being processed further.

So, what does .kill() do? To figure this out, you have to know about Sprite Groups.

Sprite Groups

Another super useful class that pygame provides is the Sprite Group. This is an object that holds a group of Sprite objects. So why use it? Can’t you just track your Sprite objects in a list instead? Well, you can, but the advantage of using a Group lies in the methods it exposes. These methods help to detect whether any Enemy has collided with the Player, which makes updates much easier.

Let’s see how to create sprite groups. You’ll create two different Group objects:

  1. The first Group will hold every Sprite in the game.
  2. The second Group will hold just the Enemy objects.

Here’s what that looks like in code:

82 # Create the 'player'
83 player = Player()
84 
85 # Create groups to hold enemy sprites and all sprites
86 # - enemies is used for collision detection and position updates
87 # - all_sprites is used for rendering
88 enemies = pygame.sprite.Group()
89 all_sprites = pygame.sprite.Group()
90 all_sprites.add(player)
91 
92 # Variable to keep the main loop running
93 running = True

When you call .kill(), the Sprite is removed from every Group to which it belongs. This removes the references to the Sprite as well, which allows Python’s garbage collector to reclaim the memory as necessary.

Now that you have an all_sprites group, you can change how objects are drawn. Instead of calling .blit() on just Player, you can iterate over everything in all_sprites:

117 # Fill the screen with black
118 screen.fill((0, 0, 0))
119 
120 # Draw all sprites
121 for entity in all_sprites:
122     screen.blit(entity.surf, entity.rect)
123 
124 # Flip everything to the display
125 pygame.display.flip()

Now, anything put into all_sprites will be drawn with every frame, whether it’s an enemy or the player.

There’s just one problem… You don’t have any enemies! You could create a bunch of enemies at the beginning of the game, but the game would quickly become boring when they all left the screen a few seconds later. Instead, let’s explore how to keep a steady supply of enemies coming as the game progresses.

Custom Events

The design calls for enemies to appear at regular intervals. This means that at set intervals, you need to do two things:

  1. Create a new Enemy.
  2. Add it to all_sprites and enemies.

You already have code that handles random events. The event loop is designed to look for random events occurring every frame and deal with them appropriately. Luckily, pygame doesn’t restrict you to using only the event types it has defined. You can define your own events to handle as you see fit.

Let’s see how to create a custom event that’s generated every few seconds. You can create a custom event by naming it:

78 # Create the screen object
79 # The size is determined by the constant SCREEN_WIDTH and SCREEN_HEIGHT
80 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
81 
82 # Create a custom event for adding a new enemy
83 ADDENEMY = pygame.USEREVENT + 1
84 pygame.time.set_timer(ADDENEMY, 250)
85 
86 # Instantiate player. Right now, this is just a rectangle.
87 player = Player()

pygame defines events internally as integers, so you need to define a new event with a unique integer. The last event pygame reserves is called USEREVENT, so defining ADDENEMY = pygame.USEREVENT + 1 on line 83 ensures it’s unique.

Next, you need to insert this new event into the event queue at regular intervals throughout the game. That’s where the time module comes in. Line 84 fires the new ADDENEMY event every 250 milliseconds, or four times per second. You call .set_timer() outside the game loop since you only need one timer, but it will fire throughout the entire game.

Add the code to handle your new event:

100 # Main loop
101 while running:
102     # Look at every event in the queue
103     for event in pygame.event.get():
104         # Did the user hit a key?
105         if event.type == KEYDOWN:
106             # Was it the Escape key? If so, stop the loop.
107             if event.key == K_ESCAPE:
108                 running = False
109 
110         # Did the user click the window close button? If so, stop the loop.
111         elif event.type == QUIT:
112             running = False
113 
114         # Add a new enemy?
115         elif event.type == ADDENEMY:
116             # Create the new enemy and add it to sprite groups
117             new_enemy = Enemy()
118             enemies.add(new_enemy)
119             all_sprites.add(new_enemy)
120 
121     # Get the set of keys pressed and check for user input
122     pressed_keys = pygame.key.get_pressed()
123     player.update(pressed_keys)
124 
125     # Update enemy position
126     enemies.update()

Whenever the event handler sees the new ADDENEMY event on line 115, it creates an Enemy and adds it to enemies and all_sprites. Since Enemy is in all_sprites, it will get drawn every frame. You also need to call enemies.update() on line 126, which updates everything in enemies, to ensure they move properly:

Enemies flying by in pygame

However, that’s not the only reason there’s a group for just enemies.

Collision Detection

Your game design calls for the game to end whenever an enemy collides with the player. Checking for collisions is a basic technique of game programming, and usually requires some non-trivial math to determine whether two sprites will overlap each other.

This is where a framework like pygame comes in handy! Writing collision detection code is tedious, but pygame has a LOT of collision detection methods available for you to use.

For this tutorial, you’ll use a method called .spritecollideany(), which is read as “sprite collide any.” This method accepts a Sprite and a Group as parameters. It looks at every object in the Group and checks if its .rect intersects with the .rect of the Sprite. If so, then it returns True. Otherwise, it returns False. This is perfect for this game since you need to check if the single player collides with one of a Group of enemies.

Here’s what that looks like in code:

130 # Draw all sprites
131 for entity in all_sprites:
132     screen.blit(entity.surf, entity.rect)
133 
134 # Check if any enemies have collided with the player
135 if pygame.sprite.spritecollideany(player, enemies):
136     # If so, then remove the player and stop the loop
137     player.kill()
138     running = False

Line 135 tests whether player has collided with any of the objects in enemies. If so, then player.kill() is called to remove it from every group to which it belongs. Since the only objects being rendered are in all_sprites, the player will no longer be rendered. Once the player has been killed, you need to exit the game as well, so you set running = False to break out of the game loop on line 138.

At this point, you’ve got the basic elements of a game in place:

Pygame window

Now, let’s dress it up a bit, make it more playable, and add some advanced capabilities to help it stand out.

Sprite Images

Alright, you have a game, but let’s be honest… It’s kind of ugly. The player and enemies are just white blocks on a black background. That was state-of-the-art when Pong was new, but it just doesn’t cut it anymore. Let’s replace all those boring white rectangles with some cooler images that will make the game feel like an actual game.

Earlier, you learned that images on disk can be loaded into a Surface with some help from the image module. For this tutorial, we made a little jet for the player and some missiles for the enemies. You’re welcome to use this art, draw your own, or download some free game art assets to use. You can click the link below to download the art used in this tutorial:

Clone Repo: Click here to clone the repo you'll use to learn how to use PyGame in this tutorial.

Altering the Object Constructors

Before you use images to represent the player and enemy sprites, you need to make some changes to their constructors. The code below replaces the code used previously:

 7 # Import pygame.locals for easier access to key coordinates
 8 # Updated to conform to flake8 and black standards
 9 # from pygame.locals import *
10 from pygame.locals import (
11     RLEACCEL,
12     K_UP,
13     K_DOWN,
14     K_LEFT,
15     K_RIGHT,
16     K_ESCAPE,
17     KEYDOWN,
18     QUIT,
19 )
20 
21 # Define constants for the screen width and height
22 SCREEN_WIDTH = 800
23 SCREEN_HEIGHT = 600
24 
25 
26 # Define the Player object by extending pygame.sprite.Sprite
27 # Instead of a surface, use an image for a better-looking sprite
28 class Player(pygame.sprite.Sprite):
29     def __init__(self):
30         super(Player, self).__init__()
31         self.image = pygame.image.load("jet.png").convert()
32         self.image.set_colorkey((255, 255, 255), RLEACCEL)
33         self.rect = self.image.get_rect()

Let’s unpack line 31 a bit. pygame.image.load() loads an image from the disk. You pass it a path to the file. It returns a Surface, and the .convert() call optimizes the Surface, making future .blit() calls faster.

Line 32 uses .set_colorkey() to indicate the color pygame will render as transparent. In this case, you choose white, because that’s the background color of the jet image. The RLEACCEL constant is an optional parameter that helps pygame render more quickly on non-accelerated displays. This is added to the pygame.locals import statement on line 11.

Nothing else needs to change. The image is still a Surface, except now it has a picture painted on it. You still use it in the same way.

Here’s what similar changes to the Enemy look like:

59 # Define the enemy object by extending pygame.sprite.Sprite
60 # Instead of a surface, use an image for a better-looking sprite
61 class Enemy(pygame.sprite.Sprite):
62     def __init__(self):
63         super(Enemy, self).__init__()
64         self.surf = pygame.image.load("missile.png").convert()
65         self.surf.set_colorkey((255, 255, 255), RLEACCEL)
66         # The starting position is randomly generated, as is the speed
67         self.rect = self.surf.get_rect(
68             center=(
69                 random.randint(SCREEN_WIDTH + 20, SCREEN_WIDTH + 100),
70                 random.randint(0, SCREEN_HEIGHT),
71             )
72         )
73         self.speed = random.randint(5, 20)

Running the program now should show that this is the same game you had before, except now you’ve added some nice graphics skins with images. But why stop at just making the player and enemy sprites look nice? Let’s add a few clouds going past to give the impression of a jet flying through the sky.

Adding Background Images

For background clouds, you use the same principles as you did for Player and Enemy:

  1. Create the Cloud class.
  2. Add an image of a cloud to it.
  3. Create a method .update() that moves the cloud toward the left side of the screen.
  4. Create a custom event and handler to create new cloud objects at a set time interval.
  5. Add the newly created cloud objects to a new Group called clouds.
  6. Update and draw the clouds in your game loop.

Here’s what Cloud looks like:

 83 # Define the cloud object by extending pygame.sprite.Sprite
 84 # Use an image for a better-looking sprite
 85 class Cloud(pygame.sprite.Sprite):
 86     def __init__(self):
 87         super(Cloud, self).__init__()
 88         self.surf = pygame.image.load("cloud.png").convert()
 89         self.surf.set_colorkey((0, 0, 0), RLEACCEL)
 90         # The starting position is randomly generated
 91         self.rect = self.surf.get_rect(
 92             center=(
 93                 random.randint(SCREEN_WIDTH + 20, SCREEN_WIDTH + 100),
 94                 random.randint(0, SCREEN_HEIGHT),
 95             )
 96 
 97     # Move the cloud based on a constant speed
 98     # Remove the cloud when it passes the left edge of the screen
 99     def update(self):
100         self.rect.move_ip(-5, 0)
101         if self.rect.right < 0:
102             self.kill()

That should all look very familiar. It’s pretty much the same as Enemy.

To have clouds appear at certain intervals, you’ll use event creation code similar to what you used to create new enemies. Put it right below the enemy creation event:

116 # Create custom events for adding a new enemy and a cloud
117 ADDENEMY = pygame.USEREVENT + 1
118 pygame.time.set_timer(ADDENEMY, 250)
119 ADDCLOUD = pygame.USEREVENT + 2
120 pygame.time.set_timer(ADDCLOUD, 1000)

This says to wait 1000 milliseconds, or one second, before creating the next cloud.

Next, create a new Group to hold each newly created cloud:

125 # Create groups to hold enemy sprites, cloud sprites, and all sprites
126 # - enemies is used for collision detection and position updates
127 # - clouds is used for position updates
128 # - all_sprites is used for rendering
129 enemies = pygame.sprite.Group()
130 clouds = pygame.sprite.Group()
131 all_sprites = pygame.sprite.Group()
132 all_sprites.add(player)

Next, add a handler for the new ADDCLOUD event in the event handler:

137 # Main loop
138 while running:
139     # Look at every event in the queue
140     for event in pygame.event.get():
141         # Did the user hit a key?
142         if event.type == KEYDOWN:
143             # Was it the Escape key? If so, then stop the loop.
144             if event.key == K_ESCAPE:
145                 running = False
146 
147         # Did the user click the window close button? If so, stop the loop.
148         elif event.type == QUIT:
149             running = False
150 
151         # Add a new enemy?
152         elif event.type == ADDENEMY:
153             # Create the new enemy and add it to sprite groups
154             new_enemy = Enemy()
155             enemies.add(new_enemy)
156             all_sprites.add(new_enemy)
157 
158         # Add a new cloud?
159         elif event.type == ADDCLOUD:
160             # Create the new cloud and add it to sprite groups
161             new_cloud = Cloud()
162             clouds.add(new_cloud)
163             all_sprites.add(new_cloud)

Finally, make sure the clouds are updated every frame:

167 # Update the position of enemies and clouds
168 enemies.update()
169 clouds.update()
170 
171 # Fill the screen with sky blue
172 screen.fill((135, 206, 250))

Line 172 updates the original screen.fill() to fill the screen with a pleasant sky blue color. You can change this color to something else. Maybe you want an alien world with a purple sky, a toxic wasteland in neon green, or the surface of Mars in red!

Note that each new Cloud and Enemy are added to all_sprites as well as clouds and enemies. This is done because each group is used for a separate purpose:

You create multiple groups so that you can change the way sprites move or behave without impacting the movement or behavior of other sprites.

Game Speed

While testing the game you may have noticed that the enemies move a little fast. If not, then that’s okay, as different machines will see different results at this point.

The reason for this is that the game loop processes frames as fast as the processor and environment will allow. Since all the sprites move once per frame, they can move hundreds of times each second. The number of frames handled each second is called the frame rate, and getting this right is the difference between a playable game and a forgettable one.

Normally, you want as high a frame rate as possible, but for this game, you need to slow it down a bit for the game to be playable. Fortunately, the module time contains a Clock which is designed exactly for this purpose.

Using Clock to establish a playable frame rate requires just two lines of code. The first creates a new Clock before the game loop begins:

106 # Setup the clock for a decent framerate
107 clock = pygame.time.Clock()

The second calls .tick() to inform pygame that the program has reached the end of the frame:

188 # Flip everything to the display
189 pygame.display.flip()
190 
191 # Ensure program maintains a rate of 30 frames per second
192 clock.tick(30)

The argument passed to .tick() establishes the desired frame rate. To do this, .tick() calculates the number of milliseconds each frame should take, based on the desired frame rate. Then, it compares that number to the number of milliseconds that have passed since the last time .tick() was called. If not enough time has passed, then .tick() delays processing to ensure that it never exceeds the specified frame rate.

Passing in a smaller frame rate will result in more time in each frame for calculations, while a larger frame rate provides smoother (and possibly faster) gameplay:

Setting the frame rate in pygame

Play around with this number to see what feels best for you!

Sound Effects

So far, you’ve focused on gameplay and the visual aspects of your game. Now let’s explore giving your game some auditory flavor as well. pygame provides mixer to handle all sound-related activities. You’ll use this module’s classes and methods to provide background music and sound effects for various actions.

The name mixer refers to the fact that the module mixes various sounds into a cohesive whole. Using the music sub-module, you can stream individual sound files in a variety of formats, such as MP3, Ogg, and Mod. You can also use Sound to hold a single sound effect to be played, in either Ogg or uncompressed WAV formats. All playback happens in the background, so when you play a Sound, the method returns immediately as the sound plays.

Note: The pygame documentation states that MP3 support is limited, and unsupported formats can cause system crashes. The sounds referenced in this article have been tested, and we recommend testing any sounds thoroughly before releasing your game.

As with most things pygame, using mixer starts with an initialization step. Luckily, this is already handled by pygame.init(). You only need to call pygame.mixer.init() if you want to change the defaults:

106 # Setup for sounds. Defaults are good.
107 pygame.mixer.init()
108 
109 # Initialize pygame
110 pygame.init()
111 
112 # Set up the clock for a decent framerate
113 clock = pygame.time.Clock()

pygame.mixer.init() accepts a number of arguments, but the defaults work fine in most cases. Note that if you want to change the defaults, you need to call pygame.mixer.init() before calling pygame.init(). Otherwise, the defaults will be in effect regardless of your changes.

After the system is initialized, you can get your sounds and background music setup:

135 # Load and play background music
136 # Sound source: http://ccmixter.org/files/Apoxode/59262
137 # License: https://creativecommons.org/licenses/by/3.0/
138 pygame.mixer.music.load("Apoxode_-_Electric_1.mp3")
139 pygame.mixer.music.play(loops=-1)
140 
141 # Load all sound files
142 # Sound sources: Jon Fincher
143 move_up_sound = pygame.mixer.Sound("Rising_putter.ogg")
144 move_down_sound = pygame.mixer.Sound("Falling_putter.ogg")
145 collision_sound = pygame.mixer.Sound("Collision.ogg")

Lines 138 and 139 load a background sound clip and begin playing it. You can tell the sound clip to loop and never end by setting the named parameter loops=-1.

Lines 143 to 145 load three sounds you’ll use for various sound effects. The first two are rising and falling sounds, which are played when the player moves up or down. The last is the sound used whenever there is a collision. You can add other sounds as well, such as a sound for whenever an Enemy is created, or a final sound for when the game ends.

So, how do you use the sound effects? You want to play each sound when a certain event occurs. For example, when the ship moves up, you want to play move_up_sound. Therefore, you add a call to .play() whenever you handle that event. In the design, that means adding the following calls to .update() for Player:

26 # Define the Player object by extending pygame.sprite.Sprite
27 # Instead of a surface, use an image for a better-looking sprite
28 class Player(pygame.sprite.Sprite):
29     def __init__(self):
30         super(Player, self).__init__()
31         self.surf = pygame.image.load("jet.png").convert()
32         self.surf.set_colorkey((255, 255, 255), RLEACCEL)
33         self.rect = self.surf.get_rect()
34 
35     # Move the sprite based on keypresses
36     def update(self, pressed_keys):
37         if pressed_keys[K_UP]:
38             self.rect.move_ip(0, -5)
39             move_up_sound.play()
40         if pressed_keys[K_DOWN]:
41             self.rect.move_ip(0, 5)
42             move_down_sound.play()

For a collision between the player and an enemy, you play the sound for when collisions are detected:

201 # Check if any enemies have collided with the player
202 if pygame.sprite.spritecollideany(player, enemies):
203     # If so, then remove the player
204     player.kill()
205 
206     # Stop any moving sounds and play the collision sound
207     move_up_sound.stop()
208     move_down_sound.stop()
209     collision_sound.play()
210 
211     # Stop the loop
212     running = False

Here, you stop any other sound effects first, because in a collision the player is no longer moving. Then you play the collision sound and continue execution from there.

Finally, when the game is over, all sounds should stop. This is true whether the game ends due to a collision or the user exits manually. To do this, add the following lines at the end of the program after the loop:

220 # All done! Stop and quit the mixer.
221 pygame.mixer.music.stop()
222 pygame.mixer.quit()

Technically, these last few lines are not required, as the program ends right after this. However, if you decide later on to add an intro screen or an exit screen to your game, then there may be more code running after the game ends.

That’s it! Test it again, and you should see something like this:

Pygame window

A Note on Sources

You may have noticed the comment on lines 136-137 when the background music was loaded, listing the source of the music and a link to the Creative Commons license. This was done because the creator of that sound required it. The license requirements stated that in order to use the sound, both proper attribution and a link to the license must be provided.

Here are some sources for music, sound, and art that you can search for useful content:

As you make your games and use downloaded content such as art, music, or code from other sources, please be sure that you are complying with the licensing terms of those sources.

Conclusion

Throughout this tutorial, you’ve learned how game programming with pygame differs from standard procedural programming. You’ve also learned how to:

To do this, you used a subset of the pygame modules, including the display, mixer and music, time, image, event, and key modules. You also used several pygame classes, including Rect, Surface, Sound, and Sprite. But these only scratch the surface of what pygame can do! Check out the official pygame documentation for a full list of available modules and classes.

You can find all of the code, graphics, and sound files for this article by clicking the link below:

Clone Repo: Click here to clone the repo you'll use to learn how to use PyGame in this tutorial.

Feel free to leave comments below as well. Happy Pythoning!


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

September 16, 2019 03:27 PM UTC


Reuven Lerner

Last change to join Weekly Python Exercise: Beginner objects

If you have been using Python, but don’t quite understand how and when to write and use the language’s object-oriented facilities, then I have good news and bad news:

Here’s what people have previously said about Weekly Python Exercise:

Remember, if you’re dissatisfied, then I offer a 100%, no questions asked, refund. 

So, don’t wait: Read more about Weekly Python Exercise (at https://WeeklyPythonExercise.com/). Questions or comments? Just e-mail me at reuven@lerner.co.il, or contact me on Twitter as @reuvenmlerner. I’ll answer your query right away!

The post Last change to join Weekly Python Exercise: Beginner objects appeared first on Reuven Lerner.

September 16, 2019 02:18 PM UTC


Mike Driscoll

PyDev of the Week: Veronica Hanus

This week we welcome Veronica Hanus (@veronica_hanus) as our PyDev of the Week! Veronica is a regular tech speaker at Python and other tech conferences and meetups. You can see some of her talks and her schedule on her website. She has been active in the Python community for the past few years. Let’s take a few moments to get to know her better!

Veronica Hanus

Can you tell us a little about yourself (hobbies, education, etc):

I enjoy writing and taking pictures. For me, the challenge is to help someone feel what I was feeling when I decided the moment was picture- or story-worthy, and both take a combination of skill-that-you-can-study and plain-old-caring that I find immensely rewarding. Photo-taking excursions are one of my favorite ways to spend time with friends, because they’re a nice combination of “quiet, contemplative side-by-side activity” and “let’s get out and do something”!

I once carved out time to take silly pictures with a new conference friend in a funny upside-down room at the conference venue. It amazed me how nice it felt to be fussed over after the stress of my first conference talk. As I started speaking more, I started offering to take pictures of conference attendees and many shared the same sentiment. Many people find conferences overwhelming and it’s nice to take a few minutes and relax, make a new friend, and maybe go home with new headshots.

My education often surprises people because it violates many people’s expectations: I don’t hold a CS degree, and I never attended a bootcamp. In college, I studied Geology with a combined geochemical and planetary science twist. Since shifting into software, I have heard countless times “Geology!? That must have been such a… change”. Even today, comments like that feel challenging and exclusionary and early in my career shift it felt terrible. We hear again and again that having folks from diverse backgrounds help teams innovate, but when meeting someone who doesn’t fit our expectations, most of us still do a double-take. If I get that as a white, degree-touting former-scientist, imagine the uncomfortable responses folks in groups with more bias encounter when we express our surprise!

It turns out that my winding path toward programming has allowed me to make some of my most useful contributions. We don’t talk about it enough, but many use programming skills even if they haven’t written a line of code. If you’re considering development but are wondering how you will fit in, I encourage you to take a peek at communities like Write the Docs (their Slack), #CodeNewbie (their Twitter), or send me a hello via my Twitter or email.

How has your background in science influenced your programming career?

It wasn’t until I was doing research at JPL that I started to understand what programming was. There was a fair bit of “grit” need: I needed to learn MATLAB the semester before my internship so I found the one professor whose research relied on MATLAB and set up an independent study with him. The licensed computer was in the basement of a building across campus. He allowed me to practice during his office hours, so I hoofed it over there twice a week to learn as much MATLAB as I could. When my summer research mentor was from a code-heavy tech-school and when he saw me stumbling, he commented “and I thought you went to a good school.”

I didn’t learn to program that summer, but I started acting as a liaison between our team’s developer and the other interns who were testing his program by hand. During those meetings, we busted many of my personal programming myths. For example, up until that time I believed that proficient programmers would write a program in the same way I would write a letter to a friend, mostly top to bottom (maybe going back for a misspelling or two). That programs could be made from libraries of existing code and some “glue” blew my mind. I started reading our program and soon was pointing and suggesting changes. I started to compare the modules in our program to the processes we might run in the lab environment I was used to. Working in a programming-adjacent field made programming more accessible, even if I did need to beg my way into someone’s basement lab along the way!

Veronica Hanus

Why did you start using Python?

Two things drew me to the Python community: Python’s proximity to so many fields of science (with so many libraries developed for specific applications) and their welcoming community.

Everyone I spoke to as I was deciding to explore programming underscored the importance of a welcoming community and recommended I start with Python. Python got themselves a new “lifer”. While I found many of the general “programming” communities overwhelming (I may never carve out a place for myself on Stack Overflow), I quickly found my place at Boston Python (they had weekend-long tutorials running and I both attended and TA-ed with them). The email list of the Harvard Astro group, whose research questions sometimes overlapped with my interests, became my place to lurk and see how those who relied on Python used the language to solve their problems. There are lots of different ways to learn!

The interest in Python has only grown and there are a multitude of ways to engage with the community. I encourage you to find the way(s) that make the most sense for your learning and socializing styles. We aren’t all Meetup/conference people!

Online communities/forums: CodeNewbies and dev.to are two of my favorites! They have twitter check-ins, podcasts, blog post. I’m also part of the Recurse Center, lovingly called “the world’s best programming community with a three-month onboarding process” and pop into their chats from time to time.

Meetups: Vary by city, but I have most enjoyed ones that rotate their themes, publicize & support other Meetup communities, and make efforts to document resources. Some have active Slack communities that allow people to communicate easily between meetings!

Conferences: Are wonderful (for me) and each have their own culture. I’ve found the ones intentional about culture-building to give the best experiences for attendees and speakers (if they work to clarify attendees’ needs or explain the PacMan rule, I’m in!)

Informal resources: Having a few folks that you go to for advice is invaluable. Seek out those folks and nurture those relationships.
There are many ways to find support but it takes time to find the spaces you can grow in. Experiment!

What other programming languages do you know and which is your favorite?

I am pretty comfortable with HTML/CSS/JS, Django, and LaTeX. Python and LaTeX are my first loves and will probably always be my favorites. Few folks know about LaTeX, so I’ll share my story there.

LaTeX is a typesetting language created by Donald Knuth, who—besides his seminal work in the analysis of algorithmic complexity—measured kerning and leading space by hand to find the most visually appealing combination and the result is frankly gorgeous. LaTeX is widely used by academics in math and math-heavy subjects (eg. Physics) and appreciated by a few other typesetting nerds. I have run workshops on LaTeX, hoping to interest people in industry to use it. Alas, LaTeX is still waiting to become popular outside of CS and the sciences. At the moment, it remains a gem reserved mostly for academic use.

I dove into LaTeX because at both the internship I had during college and the first job I had after (at Caltech and MIT, respectively), I saw folks typing their homework, papers, and notes (I heard some were skilled enough to typeset even their class notes!) with beautiful results! I was from a liberal arts school and had never seen this before—math became as beautiful as art! I decided if I would put the hours into my math sets that I needed to, I might as well be able to make them look like an artist had arranged the words/symbols on the page! I started typesetting everything, motivated both by the beauty and desire to fit in, and to this day the sight of my resume (designed and typeset by me) brings a smile to my face. Learning LaTeX was the first time I felt the excitement, joy, and mastery of programming.

What projects are you working on now?

My favorite project right now is analyzing results for a 200-person survey on developer use of in-code comments. I was motivated to learn more about commenting practices after I saw so many new programmers encouraged to avoid comments, although they seem useful in many circumstances. I’ve started speaking about the results and will create an open dataset from the responses.

What advice do you have for others who want to speak at conferences?

I felt I “wasn’t the right person” to give talks for years although I wanted to (and I’m not alone! 75% of people avoid public speaking), so I am full of advice!

Brainstorm with friends for a jump start! Everyone has their own favorite method of putting their ideas onto paper and do whatever helps you turn off your self-doubt filter. I’ve found it especially effective to gather some folks who are also brainstorming and, after drawing up a list of broad categories (eg. “What was an interesting bug you’ve had?”), each person writes on their own sheet of paper their answers (as many as you can think of in 1 minute!). Group members swap papers and mark each of the ideas they would like to learn more about. You’ll quickly see not only how interesting your ideas are but hear some helpful suggestions.

Embrace the vulnerability and don’t give into the temptation to undersell your ideas, either to yourself or others! It is common, when asking for help, for folks to share their (often fantastic) idea and then immediately hedge with “oh but I’m not sure it will work”, “sorry to bother you”, etc. Instead, get as far as you can into talk prep–folks are much more willing (and able!) to help when you can provide them with material to give feedback on.

Get yourself a review team. I have five folks who I regularly send writing to and their comments (even just “I like it!”) give me the energy to move forward when I’m struggling.

It wasn’t until I overheard a seasoned speaker (he seemed to speak at every conference I attend!) say that he normally submits at least five proposals to each conference that I realized there’s a lot more to proposal selection than talk quality! Organizers work to curate a talk lineup that will have something for each of their attendees. If your submission is about a hot new piece of tech, it may be compared to several (or dozens!) of other submissions exploring that technology. It may take a while to create multiple proposals that you feel good about, but hopefully knowing that even the most seasoned among us take this precaution will help you push forward regardless of the outcomes of your first submissions!

Join a review committee! Most conferences put out a call for reviewers on Twitter. By reviewing, read enough proposals that you’ll recognize the most common errors (eg. when the author leaves out important information) and see styles you’ll want to emulate in your own proposals. You’ll also be providing support for your favorite conference and being exposed to areas of the field or language new to you.

Remember this secret: There are very, very few “bad talk ideas” and creating a successful talk relies far more on your continued interest and willingness to research, accept feedback, and revise than your idea. Remind yourself of this as many times as you need to put your worst “weird” ideas out there and see what you can make of them.

Anything else you want to say?

Having gone through both the “what, you’re a geologist?” part of my programming transition and the “maybe speaking is for other people” part of my journey to speaking, I’ve seen first-hand just how much who is seen speaking matters. By giving talks, we not only share our programming adventures but have the chance to share our mis-adventures and hearing about the parts of the journey that are difficult can be powerful—for everyone but especially for the folks who relate to us, because of shared experiences or identities. No one can tell your story like you can.

Thanks for doing the interview, Veronica!

The post PyDev of the Week: Veronica Hanus appeared first on The Mouse Vs. The Python.

September 16, 2019 05:05 AM UTC


Programiz

How to get current date and time in Python?

In this article, you will learn to get today's date and current date and time in Python. We will also format the date and time in different formats using strftime() method.

September 16, 2019 04:03 AM UTC


Samuel Sutch

Why Python Has Become an Industry Favorite Among Programmers

With the world stepping towards a new age of technology development, it isn’t hard to imagine a future that will be full of screens. And if so be the case then, demand for people with strong programming skills will definitely rise with more number of people required to develop and support the applications. Python Training is always a good idea for those wishes to be a part of this constantly developing industry. Python language is not only easy to grasp, but emphasizes less on syntax which is why a few mistakes here and there doesn’t give as much trouble as some other languages does.

What Makes Python a Preferred Choice Among Programmers?

Python happens to be an easy programming language which offers its support to various application types starting from education to scientific computing to web development. Tech giants like Google along with Instagram have also made use of Python and its popularity continues to rise. Discussed below are some of the advantages offered by Python:

First Steps in the World of Programming

Aspiring programmers can use Python to enter the programming world. Like several other programming languages such as Ruby, Perl, JavaScript, C#, C++, etc. Python is also object oriented based programming language. People who have thorough knowledge of Python can easily adapt to other environments. It is always recommended to acquire working knowledge so as to become aware of the methodologies that are used across different applications.

Simple and Easy to Understand and Code

Many people will agree to the fact that, learning and understanding a programming language isn’t that exciting as compared to a tense baseball game. But, Python on the other hand was specifically developed keeping in mind newcomers. Even to the eye of a layman, it will seem meaningful and easy to understand. Curly brackets and tiring variable declarations are not part of this programming language thus, making it a lot easier to learn language.

Getting Innovative

Python has helped in bringing real world and computing a lot close with it Raspberry Pi. This inexpensive, card-sized microcomputer helps tech enthusiasts to build various DIY stuffs like video gaming consoles, remote controlled cars and robots. Python happens to be the programming language that powers this microcomputer. Aspirants can select from different DIY projects available online and enhance their skills and motivations by completing such projects.

Python also Supports Web Development

With its huge capabilities, Python is also a favorite among web developers to build various types of web applications. The web application framework, Django has been developed using Python and serves as the foundation for popular websites like ‘The Guardian’, ‘The NY Times’, ‘Pinterest’ and more.

Last Words

Python provides aspiring programmers a solid foundation based on which they can branch out to different fields. Python programming training ensures that students are able to use this highly potential programming language to the best of its capabilities in an exciting and fun way. Those who are keen to make a great career as software programmers are definite to find Python live up to their expectations.

Source by Jiya Kumari Verma

September 16, 2019 03:15 AM UTC

September 15, 2019


Samuel Sutch

Python Programming Language Is Considered Better Than Other Languages

Python is a high-level scripting language. It is easy to learn and powerful than other languages because of its dynamic nature and simple syntax which allow small lines of code. Included indentation and object-oriented functional programming make it simple. Such advantages of Python makes it different from other languages and that’s why Python is preferred for development in companies mostly. In industries, machine learning using python has become popular. This is because it has standard libraries which are used for scientific and numerical calculations. Also, it can be operated on Linux, Windows, Mac OS and UNIX. Students who want to make future in Python are joining online video training courses and python programming tutorial.

Features of Python: A question to arise is why machine learning using python is preferred over other languages? This is because Python has some features over other programming languages. Here are some basic features of Python making it better than other languages:

Applications of Python: There are a lot of advantages of Python making it different from others. Its applications have made it a demanded language for software development, web development, graphic designing and other use cases. Its standard libraries which support internet protocols such as HTML, JSON, XML, IMAP, FTP and many more. Libraries are able to support many operations like Data Scraping, NLP and other applications of machine learning. Due to such advantages and uses, students are preferring python programming tutorial rather than other languages. Also, there are many online video training courses available, user or any interested candidate can buy them from any place. No need to worry about location, it can be learned from their home.

How to Learn Python: Since Python has shown its enormous applications and use cases. It is mostly used in Machine Learning and Artificial intelligence companies as a basic programming language. Students who want to start their career in AI and machine learning should have a basic understanding of Python. There are many online video training courses and python programming tutorial available to join. Further, it is an easy programming language to learn as a beginner. Online courses or tutorials can help the beginners to learn Python. It can be learned quickly because user can think like a programmer due to its readable and understandable syntax. With Python we can develop anything by computer programs, only need is to spend time to understand Python and its standard libraries. PyCharm is its IDE which makes interface so easy and comfortable while learning. With the help of debugging feature of PyCharm we can easily analyse the output of each line and the error can be detected easily.

Conclusion: Python is used in many big companies such as Google, Instagram, Dropbox, Reddit and many more which means more job scopes in Python. Due to increasing demand of Python programmers, students and beginners in industries are choosing Python as their core programming language. Also the features of Python make it very easy to learn. It can be concluded that Python is best language for beginners to start as well as a powerful language for development. It is good for scientific and numerical operations. Thus many students are opting online video training courses for python programming tutorial. So, they can learn from anywhere and make their career in Python programming.

Source by Gunjan Dogra

September 15, 2019 07:46 PM UTC

September 14, 2019


Weekly Python StackOverflow Report

(cxciv) stackoverflow python report

These are the ten most rated questions at Stack Overflow last week.
Between brackets: [question score / answers count]
Build date: 2019-09-14 20:44:02 GMT


  1. How to create a list of dictionaries from a dictionary with lists of different lengths - [15/4]
  2. Numpy strange behavior past end of array - [9/1]
  3. exec() not working with unicode characters - [9/1]
  4. Turning values into columns - [7/5]
  5. I have some problem with my homework. It's about stop the loops - [7/4]
  6. How to count the number of occurences before a particular value in dataframe python? - [7/3]
  7. Comma operator precedence - [6/3]
  8. Why does float.__repr__ return a different representation compared to the equivalent formatting option? - [6/1]
  9. Jaden Casing String: How to return a sentence string with capitalised words? - [6/1]
  10. String Matching with wildcard in Python - [5/4]

September 14, 2019 08:44 PM UTC