Things you’re probably not using in Python 3 – but should

Things you’re probably not using in Python 3 – but should

Many people started switching to Python 3, unfrotunetly most people still write their code like it is Python 2. Below are useful Python 3 features.

All the examples are written in Python 3.7 and each feature contains the minimum required version of Python for that feature.

f-strings (3.6+)

It is difficult to do anything without strings in any programming language and in order to stay sane, you want to have a structured way to work with strings. Most people using Python prefer using the format method.

    user = "Jane Doe"
    action = "buy"
    log_message = 'User {} has logged in and did an action {}.'.format(
      user,
      action
    )
    print(log_message)
    # User Jane Doe has logged in and did an action buy.

Alongside of format, Python 3 offers a flexible way to do string interpolation via f-strings. The same code as above using f-strings looks like this:

    user = "Jane Doe"
    action = "buy"
    log_message = f'User {user} has logged in and did an action {action}.'
    print(log_message)
    # User Jane Doe has logged in and did an action buy.
Pathlib (3.4+)

f-strings are amazing, but some strings like file paths have their own libraries which make their manipulation even easier. Python 3 offers pathlib as a convenient abstraction for working with file paths. If you are not sure why you should be using pathlib, try reading this excellent post – Why you should be using pathlib – by Trey Hunner.

    from pathlib import Path
    root = Path('post_sub_folder')
    print(root)
    # post_sub_folder
    path = root / 'happy_user'
    # Make the path absolute
    print(path.resolve())
    # /home/weenkus/Workspace/Projects/DataWhatNow-Codes/how_your_python3_should_look_like/post_sub_folder/happy_user

Type hinting (3.5+)

Static vs dynamic typing is a spicy topic in software engineering and almost everyone has an opinion on it. I will let the reader decide when they should write types, but I think you should at least know that Python 3 supports type hints.

    def sentence_has_animal(sentence: str) -> bool:
      return "animal" in sentence
    sentence_has_animal("Donald had a farm without animals")
    # True
Enumerations (3.4+)

Python 3 supports an easy way to write enumerations through the Enum class. Enums are a convenient way to encapsulate lists of constants so they are not randomly located all over your code without much structure.

    from enum import Enum, auto
    class Monster(Enum):
        ZOMBIE = auto()
        WARRIOR = auto()
        BEAR = auto()
print(Monster.ZOMBIE)
# Monster.ZOMBIE

An enumeration is a set of symbolic names (members) bound to unique, constant values. Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over.
https://docs.python.org/3/library/enum.html
    for monster in Monster:
        print(monster)
    # Monster.ZOMBIE
    # Monster.WARRIOR
    # Monster.BEAR


Built-in LRU cache (3.2+)

Caches are present in almost any horizontal slice of the software and hardware we use today. Python 3 makes using them very simple by exposing an LRU (Least Recently Used) cache as a decorator called lru_cache.

Below is a simple Fibonacci function that we know will benefit from caching because it does the same work multiple times through a recursion.

    import time
    def fib(number: int) -> int:
        if number == 0: return 0
        if number == 1: return 1
    return fib(number-1) + fib(number-2)
start = time.time()
fib(40)
print(f'Duration: {time.time() - start}s')
# Duration: 30.684099674224854s

Now we can use the lru_cache to optimize it (this optimization technique is called memoization). The execution time goes down from seconds to nanoseconds.

    from functools import lru_cache
    @lru_cache(maxsize=512)
    def fib_memoization(number: int) -> int:
        if number == 0: return 0
        if number == 1: return 1
    return fib_memoization(number-1) + fib_memoization(number-2)
start = time.time()
fib_memoization(40)
print(f'Duration: {time.time() - start}s')
# Duration: 6.866455078125e-05s

Extended iterable unpacking (3.0+)

I will let the code speak here (docs).

head, *body, tail = range(5)
print(head, body, tail)
# 0 [1, 2, 3] 4
py, filename, *cmds = "python3.7 script.py -n 5 -l 15".split()
print(py)
print(filename)
print(cmds)
# python3.7
# script.py
# ['-n', '5', '-l', '15']
first, _, third, *_ = range(10)
print(first, third)
# 0 2
Data classes (3.7+)

Python 3 introduces data classes which do not have many restrictions and can be used to reduce boilerplate code because the decorator auto-generates special methods, such as init() and __repr()__. From the official proposal, they are described as “mutable named tuples with defaults”.

    class Armor:
    def __init__(self, armor: float, description: str, level: int = 1):
        self.armor = armor
        self.level = level
        self.description = description
                 
    def power(self) -> float:
        return self.armor * self.level
    
armor = Armor(5.2, "Common armor.", 2)
armor.power()
# 10.4
print(armor)
# <__main__.Armor object at 0x7fc4800e2cf8>


The same implementation of Armor using data classes.

    from dataclasses import dataclass
@dataclass
class Armor:
armor: float
description: str
level: int = 1

    def power(self) -> float:
        return self.armor * self.level
    
armor = Armor(5.2, "Common armor.", 2)
armor.power()
# 10.4
print(armor)
# Armor(armor=5.2, description='Common armor.', level=2)

Implicit namespace packages (3.3+)

One way to structure Python code is in packages (folders with an init.py file). The example below is given by the official Python documentation.

    sound/                          Top-level package
init.py Initialize the sound package
formats/ Subpackage for file format conversions
init.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
effects/ Subpackage for sound effects
init.py
echo.py
surround.py
reverse.py
...
filters/ Subpackage for filters
init.py
equalizer.py
vocoder.py
karaoke.py
...

In Python 2, every folder above had to have an init.py file which turned that folder into a Python package. In Python 3, with the introduction of Implicit Namespace Packages, these files are no longer required.

    sound/                          Top-level package
init.py Initialize the sound package
formats/ Subpackage for file format conversions
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
effects/ Subpackage for sound effects
echo.py
surround.py
reverse.py
...
filters/ Subpackage for filters
equalizer.py
vocoder.py
karaoke.py
...

EDIT: as some people have said, this is not as simple as I pointed it out in this section, from the official PEP 420 Specificationinit.py is still required for regular packages, dropping it from the folder structure will turn it into a native namespace package which comes with additional restrictions, the official docs on native namespace packages show a great example of this, as well as naming all the restrictions.


Closing note

Like almost any list on the internet, this one is not complete. I hope this post has shown you at least one Python 3 functionality you did not know existed before, and that it will help you write cleaner and more intuitive code. As always, all the code can be found on GitHub.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Learn More

Complete Python Bootcamp: Go from zero to hero in Python 3

Machine Learning A-Z™: Hands-On Python & R In Data Science

Python and Django Full Stack Web Developer Bootcamp

Complete Python Masterclass

The Python Bible™ | Everything You Need to Program in Python

Python at Netflix

MySQL Databases With Python Tutorial

Build Your First Python and Django Application

Exploring Python Basics (Free eBook

An A-Z of useful Python tricks

A Complete Machine Learning Project Walk-Through in Python

Learning Python: From Zero to Hero

Originally published on https://datawhatnow.com

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Description
Learn Hands-On Python Programming By Creating Projects, GUIs and Graphics

Python is a dynamic modern object -oriented programming language
It is easy to learn and can be used to do a lot of things both big and small
Python is what is referred to as a high level language
Python is used in the industry for things like embedded software, web development, desktop applications, and even mobile apps!
SQL-Lite allows your applications to become even more powerful by storing, retrieving, and filtering through large data sets easily
If you want to learn to code, Python GUIs are the best way to start!

I designed this programming course to be easily understood by absolute beginners and young people. We start with basic Python programming concepts. Reinforce the same by developing Project and GUIs.

Why Python?

The Python coding language integrates well with other platforms – and runs on virtually all modern devices. If you’re new to coding, you can easily learn the basics in this fast and powerful coding environment. If you have experience with other computer languages, you’ll find Python simple and straightforward. This OSI-approved open-source language allows free use and distribution – even commercial distribution.

When and how do I start a career as a Python programmer?

In an independent third party survey, it has been revealed that the Python programming language is currently the most popular language for data scientists worldwide. This claim is substantiated by the Institute of Electrical and Electronic Engineers, which tracks programming languages by popularity. According to them, Python is the second most popular programming language this year for development on the web after Java.

Python Job Profiles
Software Engineer
Research Analyst
Data Analyst
Data Scientist
Software Developer
Python Salary

The median total pay for Python jobs in California, United States is $74,410, for a professional with one year of experience
Below are graphs depicting average Python salary by city
The first chart depicts average salary for a Python professional with one year of experience and the second chart depicts the average salaries by years of experience
Who Uses Python?

This course gives you a solid set of skills in one of today’s top programming languages. Today’s biggest companies (and smartest startups) use Python, including Google, Facebook, Instagram, Amazon, IBM, and NASA. Python is increasingly being used for scientific computations and data analysis
Take this course today and learn the skills you need to rub shoulders with today’s tech industry giants. Have fun, create and control intriguing and interactive Python GUIs, and enjoy a bright future! Best of Luck
Who is the target audience?

Anyone who wants to learn to code
For Complete Programming Beginners
For People New to Python
This course was designed for students with little to no programming experience
People interested in building Projects
Anyone looking to start with Python GUI development
Basic knowledge
Access to a computer
Download Python (FREE)
Should have an interest in programming
Interest in learning Python programming
Install Python 3.6 on your computer
What will you learn
Build Python Graphical User Interfaces(GUI) with Tkinter
Be able to use the in-built Python modules for their own projects
Use programming fundamentals to build a calculator
Use advanced Python concepts to code
Build Your GUI in Python programming
Use programming fundamentals to build a Project
Signup Login & Registration Programs
Quizzes
Assignments
Job Interview Preparation Questions
& Much More

Guide to Python Programming Language

Guide to Python Programming Language

Guide to Python Programming Language

Description
The course will lead you from beginning level to advance in Python Programming Language. You do not need any prior knowledge on Python or any programming language or even programming to join the course and become an expert on the topic.

The course is begin continuously developing by adding lectures regularly.

Please see the Promo and free sample video to get to know more.

Hope you will enjoy it.

Basic knowledge
An Enthusiast Mind
A Computer
Basic Knowledge To Use Computer
Internet Connection
What will you learn
Will Be Expert On Python Programming Language
Build Application On Python Programming Language

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Description
Hello and welcome to brand new series of wiredwiki. In this series i will teach you guys all you need to know about python. This series is designed for beginners but that doesn't means that i will not talk about the advanced stuff as well.

As you may all know by now that my approach of teaching is very simple and straightforward.In this series i will be talking about the all the things you need to know to jump start you python programming skills. This series is designed for noobs who are totally new to programming, so if you don't know any thing about

programming than this is the way to go guys Here is the links to all the videos that i will upload in this whole series.

In this video i will talk about all the basic introduction you need to know about python, which python version to choose, how to install python, how to get around with the interface, how to code your first program. Than we will talk about operators, expressions, numbers, strings, boo leans, lists, dictionaries, tuples and than inputs in python. With

Lots of exercises and more fun stuff, let's get started.

Download free Exercise files.

Dropbox: https://bit.ly/2AW7FYF

Who is the target audience?

First time Python programmers
Students and Teachers
IT pros who want to learn to code
Aspiring data scientists who want to add Python to their tool arsenal
Basic knowledge
Students should be comfortable working in the PC or Mac operating system
What will you learn
know basic programming concept and skill
build 6 text-based application using python
be able to learn other programming languages
be able to build sophisticated system using python in the future

To know more: