Explore Free Python Programming Tutorials – GameDev Academy https://gamedevacademy.org Tutorials on Game Development, Unity, Phaser and HTML5 Wed, 22 Feb 2023 21:14:27 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://gamedevacademy.org/wp-content/uploads/2015/09/cropped-GDA_logofinal_2015-h70-32x32.png Explore Free Python Programming Tutorials – GameDev Academy https://gamedevacademy.org 32 32 A Guide to Using Enum in Python for Finite Data States https://gamedevacademy.org/python-enum-tutorial/ Sun, 18 Dec 2022 14:07:31 +0000 https://pythonmachinelearning.pro/?p=3175 Read more]]> This post is going to explore the Python enum module, a powerful tool for handling sets of data that don’t change.

Not only is this integral for generalized software development, but is something you’ll also find commonly featured in games – making it an important skill and foundation to learn regardless of your personal coding goals!

Let’s dive in, and explore this fascinating topic of using enum in Python!

Prerequisites

The reader is expected to have a working knowledge of the Python programming language. Familiarity with how to write classes will also be helpful since Python enums are implemented as Python classes.

If you’re in need of beginner-friendly Python material, we recommend checking out our other Python tutorials or checking out the Python Mini-Degree – a full-feature curriculum of courses focusing on everything you might want to get you started.

For educators looking to bring Python into the classroom, we also recommend checking out Zenva Schools. This K12 platform offers online courses on Python (and other popular topics) along with tools for managing the classroom, reporting on student progress, and beyond.

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

What is a Python Enum?

Let’s discuss what a Python enum is. Short for enumerations, this language feature defines a set of names that are bound to constant values such as numbers, strings etc. Python enums are useful to represent data that represent a finite set of states such as days of the week, months of the year, etc.

They were added to Python 3.4 via PEP 435. However, it is available all the way back to 2.4 via pypy. As such, you can expect them to be a staple as you explore Python programming.

Illustration of woman at computer

Simple Example

We define a simple enum class (i.e. a class derived from Enum) containing the months of the year. Each month (i.e. enum member) is assigned a unique numeric constant.

from enum import Enum, unique, Flag

class Months(Enum) :
    JANUARY=1
    FEBRUARY=2
    MARCH =  3
    APRIL=4
    MAY=5
    JUNE=6
    JULY=7
    AUGUST=8
    SEPTEMBER=9
    OCTOBER=10
    NOVEMBER=11
    DECEMBER=12

Printing out the members of the Python enum

There are several ways we can do this.

# by numerical index
print (Months(7)
Months.JULY

# item index
print (Months['JULY'])
Months.JULY

# by name
print (Months.JULY)
Months.JULY

# by name
print (Months.JULY.name)
JULY

# by value
print (Months.JULY.value)
JULY

Ensuring uniqueness

Adding a @unique decorator to the class, ensures that duplicate elements don’t exist in the Python enum.

from enum import Enum, unique, Flag

>> @unique
... class Months(Enum) :
...     JANUARY=1
...     JANUARY=1
...     FEBRUARY=2
...     MARCH =  3
...     APRIL=4
...     MAY=5
...     JUNE=6
...     JULY=7
...     AUGUST=8
...     SEPTEMBER=9
...     OCTOBER=10
...     NOVEMBER=11
...     DECEMBER=12
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 4, in Months
  File "/home/raghavan/anaconda3/lib/python3.8/enum.py", line 112, in __setitem__
    raise TypeError('Attempted to reuse key: %r' % key)
TypeError: Attempted to reuse key: 'JANUARY'

A TypeError occurs when the Python interpreter tries to create this Python enum.

Alternative way to create an Enum.

The Python Enum class is callable and the following Functional API can be invoked to create it.

>> quarter1= Enum('Q1', [('January', 1), ('February', 2), ('March', 3)])
>> print (quarter1(3))
Q1.March

# can also be written as
>> quarter1= Enum('Q1', ('January February March'))
>> print (quarter1)
<enum 'Q1'>

# item access
>>> quarter1['January']
<Q1.January: 1>

>>> Quarter1.March
<Q1.March: 3>

>>> Quarter1.March.value
3

Pictures of coding on a computer screen

Iterating over the elements

For loop

A simple for loop can be used to print out the members.

# simple for loop
for month in (Months) :
    print (month)

Months.JANUARY
Months.FEBRUARY
Months.MARCH
Months.APRIL
Months.MAY
Months.JUNE
Months.JULY
Months.AUGUST
Months.SEPTEMBER
Months.OCTOBER
Months.NOVEMBER
Months.DECEMBER

The __members__ attribute

__members__ is a read-only class level attribute providing a mapping from names to members. It can be iterated over to produce a similar output as above.

# iteration over elements
for name, member in Months.__members__.items():
    print (name, member)

JANUARY Months.JANUARY
FEBRUARY Months.FEBRUARY
MARCH Months.MARCH
APRIL Months.APRIL
MAY Months.MAY
JUNE Months.JUNE
JULY Months.JULY
AUGUST Months.AUGUST
SEPTEMBER Months.SEPTEMBER
OCTOBER Months.OCTOBER
NOVEMBER Months.NOVEMBER
DECEMBER Months.DECEMBER

Hashing

Python enums can be used as dictionary keys as follows.

>> months = {}
>> months[Months.JULY] = 'Many Birthdays'
>> months[Months.JANUARY] = 'First Month of the Year'

>> print (months[Months(7)])
Many Birthdays

Auto values

The values corresponding to the names can be populated automatically using auto() as demonstrated below.

# member values using auto
from enum import auto
class Quarter(Enum):
    Q1 = auto()
    Q2 = auto()
    Q3 = auto()
    Q4 = auto()


for qtr in Quarter:
    print (qtr.value)

# Output
1
2
3
4

The values, by default, are numeric. However, they can be converted into say string values by overriding _generate_next_value_ in the class.

# member values using auto
from enum import auto
class Quarter(Enum):
    def _generate_next_value_(name, start, count, last_values):
         return "[" + name + "]"
    Q1 = auto()
    Q2 = auto()
    Q3 = auto()
    Q4 = auto()

# test the values
for qtr in Quarter:
    print (qtr.value)

# Output
[Q1]
[Q2]
[Q3]
[Q4]

Woman's hands typing on a laptop

Derived Enumerations

Flag

Flag is quite similar to Enum except it has support for bitwise operations (|, &, ^, ~). These operators can be used to combine multiple Python enum elements into a mask.

The class Planets is derived from Flag and contains the 8 planets currently recognized by the International Astronomical Union. The values of the elements are required to be multiples of two while combinations need not follow that restriction.

class Planets(Flag):
    MERCURY = 1
    VENUS   = 2
    EARTH   = 4
    MARS    = 8
    SATURN  = 10
    URANUS  = 12
    NEPTUNE = 14

my_planet = {
              Planets.MERCURY: "Red Planet",
              Planets.EARTH:   "People !!!!!",
              Planets.MARS:    "Martians !!!!"
            }

# bitwise OR mask => Mercury / Earth.
mercury_earth = Planets.MERCURY|Planets.EARTH

# we check which planets in the given dictionary are
# MARS or EARTH by doing a Bitwise AND with the mask above.

for planet_name in myplanet.keys() :
    found = bool(planet_name & mercury_earth)
    print ("Found:" + str(planet_name) + ":" + str(found))

# Output

Found:Planets.MERCURY:True
Found:Planets.EARTH:True
Found:Planets.MARS:False
  1. The Planets class derives from Flag. It contains the names and values of the 8 planets.
  2. The my_planet dictionary contains the enum names of Mercury, Earth and Mars as keys.
  3. Create a bit mask by OR-ing Planets.MERCURY and Planets.EARTH.
  4. Iterate through the planet names in the dictionary and do a bit wise AND between the planet name and the mask created in Step 3. Convert the resultant value into a boolean value.
  5. The bitwise & operation will return True where the element key matches Planets.MERCURY or Planets.EARTH and False for any other planet. The output reflects this.

IntEnum

IntEnum is a derived Python enum that also derives from int. Consequently it supports int operations. It provides ordered comparisons that are not provided by the Python Enum class.

>>> from enum import Enum, auto
>>> class Quarter(Enum):
...     Q1 = auto()
...     Q2 = auto()
...     Q3 = auto()
...     Q4 = auto()


# numerical comparisons other than '==' and '!='
>>> Quarter.Q1 < Quarter.Q2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'Quarter' and 'Quarter'


# IntEnum supports comparisons, sorting.

>>> from enum import IntEnum, Enum, auto
>>> class Quarter (IntEnum):
...     Q1 = auto() 
...     Q2 = auto() 
...     Q3 = auto() 
...     Q4 = auto()
...
>>> Quarter.Q1
<Quarter.Q1: 1>
>>> Quarter.Q2
<Quarter.Q2: 2>

>>> Quarter.Q1 < Quarter.Q2
True

>>> sorted ([Quarter.Q2, Quarter.Q1, Quarter.Q4, Quarter.Q3])
[<Quarter.Q1: 1>, <Quarter.Q2: 2>, <Quarter.Q3: 3>, , <Quarter.Q4: 4>]

# integer operations
>>> Quarter.Q1 + 10
11
  1. Inherit Quarter from Enum.
  2. Try a “<” numerical comparison between Quarter.Q1 and Quarter.Q2. It fails with a TypeError.
  3. Redefine Quarter by inheriting Quarter from IntEnum,
  4. The same comparison now succeeds.
  5. We are also able to sort the members of the IntEnum.
  6. Finally, we can perform integer operations on the IntEnum member.

IntFlag

This variation of enum is a subclass of int. The members of this Python enum are ints. These values can be combined using bitwise operators and the result is also an IntFlag member. Any other operators used on the members could remove them from IntFlag membership.

from enum import IntFlag, auto
class DaysOfWeek(IntFlag) :
    Monday = auto()
    Tuesday = auto()
    Wednesday = auto()
    Thursday = auto()
    Friday = auto()
    Saturday = auto()
    Sunday = auto()

week_end = DaysOfWeek.Saturday | DaysOfWeek.Sunday

is_mon_weekend = DaysOfWeek.Monday & week_end

print (bool(is_mon_weekend))
False

is_sun_weekend = DaysOfWeek.Sunday & week_end
print (bool(is_sun_weekend))
True
  1. We inherit DaysOfWeek from IntFlag. It contains the days of the week as members.
  2. We create a weekend mask (week_end) by bitwise-ORing Saturday and Sunday.
  3. We bitwise-AND this mask with Monday which correctly gives us a False value.
  4. We bitwise-AND this mask with Sunday which correctly gives us a True value.

Lego business man looking stressed at desk

Custom Ordering

Both IntEnum and IntFlag allows us to do custom ordering of the members where natural ordering does not help.

IntEnum

"GREEN" < "BLUE"
False

class Colors(IntEnum) :
    GREEN = 1
    BLUE  = 2

Colors.GREEN < Colors.BLUE
True
  1. The string GREEN cannot be alphabetically made less than the string BLUE.
  2. However, defining them as members of an IntEnum makes this possible.

References / Additional Reading

We’ve covered the basics, but now it’s time for you to explore Python enums yourself! Check out some of the links below to get yourself started, either with enums or with further Python programming topics.

Conclusion

Python enums are extremely useful in managing data that takes a finite set of states. They are also useful in imposing a custom ordering on data. As discussed, there are 3 variations of Python Enum i.e. IntEnum, IntFlag, and Flag. Flag and IntFlag can be used in combining states using bitwise operators, while IntEnum and IntFlag are useful for numeric comparisons and sorting.

Where you go with this newfound knowledge is up to you, though. Perhaps you’re interested in making a calendar program suited for a business suite of software. Or, maybe you’re interested in making a game and using enumerations in Python for different status effects. The uses here are pretty limitless, but we hope you’ve come away with some new information at your disposal and are able to use the Python enum to your benefit and success!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Free Course – Learn Object-Oriented Programming with Python https://gamedevacademy.org/python-oop-tutorial/ Fri, 02 Dec 2022 01:00:50 +0000 https://gamedevacademy.org/?p=19262 Read more]]>

Master object-oriented programming techniques for games using Python to store and manipulate program data. You can explore more about object-oriented programming techniques using Python in the full course below!

PYTHON PROJECTS – OBJECT-ORIENTED GAME

About

In this course taught by instructor Nimish Narang, you’ll learn object-oriented programming principles for creating classes and objects. You’ll explore some of the paradigm’s key techniques, including how to use variables to represent attributes and properties of an object. You’ll also practice by implementing a GameObject with properties and methods, and learn how to create (or instantiate) a GameObject that uses your class design. Regardless of what kind of coding projects interest you, these game and OOP foundations will prepare you to pursue any number of interactive projects with responsible habits.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
How to Use Python Map() – An Efficient Way to Transform Data https://gamedevacademy.org/python-map-tutorial/ Tue, 22 Feb 2022 08:49:37 +0000 https://pythonmachinelearning.pro/?p=3048 Read more]]> This post introduces the reader to Python maps, implemented by the built-in map() function of Python.

Map is a powerful function that not only gives us new ways to transform data, but also aids us in reducing our code to just a few efficient lines in some select cases.

If you’re ready to bolster your Python programming skills, let’s dive in.

Prerequisites

The reader is expected to have a working knowledge of Python programming.

We will be looking at using Python built in functions as well as custom functions in Python as an argument to the map function. The reader is therefore expected to also have written at least a few simple functions using Python, though previous knowledge of the built in function map is obviously not required.

The code in this example has been tested using Python 3.8.8 though the map function has been around much longer. The code hence will work with earlier versions of Python as well.

What Python Maps are for

Map is an important function in the functional programming paradigm of Python. In functional programming, a function/set of functions operate on a piece of data to transform it. map is an excellent function to learn, to cut down on the amount of code that for loops take up.

If the data was a set of integers, examples of transformation on this data could include squaring the numbers, calculating their factorials, a Fibonacci sequence, etc. If the data were a set of sentences, we might consider stripping these sentences of punctuation. If the data were a set of words, we could capitalize the first letter of each word, etc.

Person typing at a computer

Syntax

map(function, iterable)

Map is a function that takes in a function and an iterable(s) and applies the function to every element of the iterable. Let’s look at an example of an iterable map object that squares every element of a list.

def square(num) :
     return num**2

>> sqr = map(square, [1,2,3,4,5])
>> print (sqr)
<map object at 0x7faa1d2483a0>

# convert map to list
>> print (list (sqr))
[1, 4, 9, 16, 25]
  1. square is a function that takes in a number and returns its square.
  2. Call map passing in square as the function and the list [1,2,3,4,5] and assign the result to sqr.
  3. Printing the value of sqr gives us a map object.
  4. Convert this map object into a list and print its contents.
  5. The result [1, 4, 9, 16, 25] is the list of squares of each individual element of the list.

The function passed to map as the first argument can also be an anonymous lambda expression. We get the same response by rewriting the above example as a lambda function:

# square the numbers passed in
>>> sqr = map(lambda x: x*x, [1,2,3,4,5])
>>> list(sqr)
[1, 4, 9, 16, 25]

# capitalize the first letter of every word
>>> sentence = 'the curfew tolls the knell of the parting day'
>>> m = map(lambda word : word[0].upper() + word[0:] , sentence.split()))

>>> print(list(map))
['The', 'Curfew', 'Tolls', 'The', 'Knell', 'Of', 'The', 'Parting', 'Day']

Multiple iterables with map

The following example shows how multiple iterables can be passed to the map function. We call map, passing in the operator module and 2 lists.

>> import operator
>> list(map(operator.mod, [4,6], [3,4]))

# output
>> [1, 2]
  1. Import the operator module.
  2. Pass operator.mod and 2 lists to the map function. [4,6] contains the first argument to the mod function in the expression and [3,4] contains the 2nd argument. The two expressions being evaluated are 4%3 and 6%4.
  3. The output list contains the remainders of the expression evaluation i.e. [1, 2] as expected.

When 2 iterables of different length are passed to map, the resultant iterable is only as long as the shorter iterable. Modifying the above example, we see this effect when the function iterates through.

>>> list(map (operator.mod, [4,6,8], [3,4]))
[1, 2]

We notice that the number 8 is ignored in the evaluation and the output result.

Replacing a for loop with map

One of the most common uses of map is to replace a for loop of several lines with a single expression. The following example uses a for loop to check if corresponding items in a list are greater than or equal to numbers in another list and prints out a boolean list as result. The output list contains True where the comparison succeeded and False where it failed.

import operator
boundaries  = [200, 30, 45]
numbers = [201, 31, 44]
result = []

# with a for loop
for idx in range(len(boundaries))  :
    if numbers[idx] >= boundaries[idx] :
        result.append(True)
    else :
       result.append(False)

print (result)
[True, True, False]


# syntax using map()
print (list(map(operator.ge,numbers,boundaries)))
[True, True, False]
  1. Import operator for use with map.
  2. The boundaries list contains a list of numbers to compare against.
  3. The numbers list contains the numbers that are being compared.
  4. The result list will contain boolean values to indicate the success/failure of the comparison.
  5. The for loop loops over the indices of boundaries and then compares corresponding elements of the numbers and boundaries lists.
  6. If numbers[i] >= boundaries[i], True is appended to the result list. Otherwise False is appended.
  7. After the for loop terminates, the result [True, True, False] is printed.
  8. The same result i.e. [True, True, False], can be achieved with a single map call using operators.ge as the function and numbers and boundaries as the iterables. This shows the power of the map function.

Silhouetted woman working at computer

Comparing map() with List Comprehensions and Generators

List Comprehension

A map expression can be replaced with a list comprehension which is more expressive. The square example above can be used as an example. The code in the list comprehension is seen to be more intuitive. It also automatically produces the list iterable without needing an explicit list() call like the map function does.

However, the list comprehension creates the list right away, adding memory and processing load up front whereas the map function does not do that.

def square(num) :
     return num**2

# using map
>> list(map(square, [1,2,3,4])

# can be replaced with a list comprehension
>> [square(x) for x in [1,2,3,4]]


# Output (in both cases):
[1,4,8,16]

Generator

A generator can also be used in lieu of a map function call. Maps and generators both return an iterator and both need to be explicitly converted into a list. Both a generator and the result of the map call can be iterated over using the next() function. Thus, using a generator or a map call are not very different.

def square(num) :
     return num**2

# using map
list(map(square, [1,2,3,4])

# iterating using map
m =  map (square, [1,2,3,4)
i = iter(m)
>>> next(i)
1
>>> next(i)
4
>>> next(i)
9
>>> next(i)
16
>>> next(i)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration


# can be replaced with a generator expression
list(square(x) for x in [1,2,3,4])

# iterating over the generator
>>> s = (square(x) for x in [1,2,3,4])
>>> s
<generator object <genexpr> at 0x7f6c303b6eb0>
>>> next(s)
1
>>> next(s)
4
>>> next(s)
9
>>> next(s)
16
>>> next(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration


Output:
[1,4,9,16]

Vector artwork of a video call with students

References / Additional Reading

Want to learn more about Python map or Python programming in general? Take a look at some of the amazing resources below.

Conclusion

The Python map() function is extremely useful in replacing verbose for loops of several lines with a single line of code. While this is not necessary in every situation, it can result in cleaner looking code that is not only easier to work with, but slightly more efficient. We encourage you to continue to experiment with using this wonderful built in function, especially in terms of using lambda functions which we only covered briefly.

That being, there are always more options. Python list comprehensions and generators can also be used in lieu of the map function. Of these, the generator use is quite similar to that of the map() function. The list comprehension, while more intuitive, requires upfront creation of a list – whereas, in the case of the map() function, this step can be delayed to later using iteration. Regardless of your personal choice, though, Python map() is a useful skill for your toolbox and future Python projects.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
How to Use the Datetime Module in Python – Beginner’s Guide https://gamedevacademy.org/python-datetime-tutorial/ Tue, 22 Feb 2022 06:25:38 +0000 https://pythonmachinelearning.pro/?p=3110 Read more]]> In this post, we’re going to dive into the Python datetime module and explore how we can effectively implement date and time data into our Python code.

Regardless of what area of Python programming you’re pursuing, this is a must-know module with an endless amount of uses and tons of professional career applications.

Let’s get started!

Prerequisites :  The reader is expected to have a working knowledge of the Python programing language.

About Python Datetime

The Python datetime module contains various classes to represent and manipulate dates and times. The key classes in datetime are date, time, datetime, timedelta, tzinfo, timezone. We will look briefly at the date, time, and timedelta objects and in more detail at the datetime objects. Timezone is not covered in this article.

Aware Vs Naive Objects

Date and Time objects that contain timezone and daylight saving time (DST) info are called aware objects. An aware object represents a moment in time that is not open to interpretation and can locate itself relative to other aware objects.  Naive objects are simpler, and represent either UTC or local time etc. and cannot locate themselves relative to other aware objects.

date objects are naive. datetime and time objects may be naive or aware.

Classes

datetime.date

Creating date objects

A date object represents a date. The constructor for date objects is date(year, month, day). A date can also be created from an existing date by using the replace method to replace the year/month/date. We can also set the day of the week as well.

# date constructor
>>> d = date (1999, 5, 26)

# methods to get data
>>> d.day
26

>>> d.month
5

>>> d.year
1999

# Monday = 0, Sunday = 6
>>> d.weekday()
2

# Monday = 1, Sunday = 7
>>>> d.isoweekday()
3

>>> d.replace (month=11)
datetime.date(1999, 11, 26)

Important date class methods

The following methods are defined on the date class and provide information about the range of dates supported by the date class.

# the earliest representable date
>>> print (date.min)
0001-01-01

# the latest representable date
>>> print (date.max)
9999-12-31

# the smallest possible difference between 2 non-equal date objects.
>>> print (date.resolution)
1 day, 0:00:00

Photo of an hour glass on rocks

Formatting date

The date object can be formatted in different ways using different methods of the date class. strftime is a powerful formatting method that supports several formats. We will look at it in detail in a subsequent section.

>>> d = date (1999, 5, 26)

>>> d.isoformat()
'1999-05-26'

>>> d.ctime()
'Wed May 26 00:00:00 1999'

>>> d.strftime('%d%m%y')
'260599'

strftime for the date object

The general syntax of strftime is as follows:

datetime.date.strftime(format_string)

strftime is an instance method on the datetime, date, time objects. It converts a date object into a formatted string. It supports numerous formatting strings described in detail in the Python Documentation. In this section, we look at a few examples of strftime formatting in the context of the date object.

The formatting codes for hour, minute, seconds, microseconds should not be used here as they don’t apply to date objects. If used, they are substituted with 0.

>>> d.strftime('%A %B %Y')
'Wednesday May 1999'

>>> d.strftime('%a %b %y')
'Wed May 99'

# %j = day of the year
>>> d.strftime('%a %b %y %j')
'Wed May 99 146'

# %U = week of the year (Sunday = 1)
>>> d.strftime('%j %U')
'146 21'

datetime.time

A time object represents a time of day, independent of day. It can be adjusted using a timezone (tzinfo) object. Arithmetic is not supported on time objects.

Creating time objects

A time object can be created by using the time constructor, from an existing time object by using the replace method (to replace the hour/minute/second/microsecond) or from an iso formatted string.

The constructor for the time object is as follows.

datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0
from datetime import time

>>> t = time(12, 25, 9)

>>> t.hour
12
>>> t.second
9

>>> t.minute
25

>>> t.microsecond
0

>>> t.isoformat() 
'12:25:09' 

>>> t.strftime('%H:%M:%S') 
'12:25:09'

# New date from existing date by replacing minute
>>> t2 = t.replace(minute=44) 

>>> t2.isoformat()
'12:44:09'

# new time from isoformatted string
>>> t3 = time.fromisoformat('14:45:59')

>>> t3
datetime.time(14, 45, 59)

>>> t3.isoformat()
'14:45:59'

strftime for the time object

strftime is an instance method on the datetime, date, time objects. It converts a time object into a formatted string. It supports numerous formatting strings described in detail in the Python Documentation. In this section, we look at a few examples of strftime formatting in the context of the time object.

The formatting strings for year, month, and day should not be used here as they don’t apply to time objects. If used, 1900 is substituted for the year, and 1 for the month and day.

>>> t = time(12, 25, 9)

# 24-hour clock
>>> t.strftime('%H:%M:%S')
'14:45:59'

# 12-hour clock
>>> t.strftime('%I:%M:%S %p')
'02:45:59 PM'

# 1 substituted for month, day, 1900 for year
>>> t.strftime('%c')
'Mon Jan 1 14:45:59 1900'

Important time class methods

The following methods are defined on the time class and provide information on the range of time supported by the time class.

# the earliest representable time 
>>> print (time.min) 
00:00:00

# the latest representable time 
>>> print (date.max) 
23:59:59.999999

# the smallest possible difference between 2 non-equal time objects. 
>>> print (date.resolution) 
0:00:00.000001

People looking at the sky from inside a clock

datetime.timedelta

timedelta is a time duration expressing the difference between 2 date / time / datetime objects to microsecond precision. It’s important to remember that arithmetic is not supported on time objects. Hence we have to convert time objects into datetime objects with any valid date and then compute the difference. Alternately a dummy date object can be combined with each of the time objects and the resultant datetime objects could be used to compute the difference.

# difference between dates
>>> d1 = date(2000, 11, 24)
>>> d2 = date(2001, 11, 24)
>>> td = d2 -d1
'365 days, 0:00:00'

# arithmetic between times not allowed.
>>> t1 = time(12, 56, 57)
>>> t2 = time(12, 57, 54)
>>> str(t2 - t1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

# convert time objects into datetime objects (with the same date) 
# and then do the math
>>> dt1 = datetime(2000, 11, 24, 12, 57, 54)
>>> dt2 = datetime(2000, 11, 24, 10, 56, 53)

# diff = 2 hrs, 1 minute, 1 second
>>> str(dt1 - dt2)
'2:01:01'

# total difference in seconds
>>> (dt2 - dt1).total_seconds()
2584739.0

datetime.datetime

datetime is an important object of the datetime module, containing information from a date and a time object.

Creating datetime objects

datetime objects can be created using a constructor, from iso strings, POSIX timestamps, UTC time stamps, combining date and time objects. The current date and time can also be returned using methods like now() and today(). We look at a few of these methods below. For a comprehensive treatise on creating datetime objects, see the Python documentation.

The constructor format is as follows :

# datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

# example
>>> d = datetime(1999, 7, 23, 23, 56, 59)

>>> d.year
1999

>>> d.month
7

>>>> d.day
23

>>> d.hour 
23

>>> d.minute
56

>>> d.second
59

>>> d.isoformat()
1999-07-23T23:56:59

>>> d.timestamp()
932754419.0

datetime.now() can be used to get the current local date, time as a datetime object.

from datetime import datetime as dt

# print the current local date, time
now = dt.now()
print (now)

# yyyy-mm-dd hh:mm:ss.microseconds
2021-07-26 16:39:07.104867

# day
>>> print (now.day)
26

# month
>>> print (now.month)
7

>>> print (now.hour)
16

# minute
>>> print (now.minute)
39

>>> iso format
print (now.isoformat())
'2021-07-26T16:39:07.104867'

datetime from the ISO format

A datetime object can be created from an ISO formatted string as follows.

>>> datetime.fromisoformat('2011-11-04T00:05:23') 
datetime.datetime(2011, 11, 4, 0, 5, 23)

Combining date and time objects into datetime

date and time objects can be combined into a datetime object using the combine method.

>>> d = date(1999, 8,25)
>>> t = time(23, 4, 55)
>>> 
>>> dt = datetime.combine(d, t)
>>> dt
datetime.datetime(1999, 8, 25, 23, 4, 55)

Pile of wooden clocks

Arithmetic with datetime objects

Datetime objects can be added or subtracted to/from  timedelta objects to produce a datetime object. The example below adds and subtracts a timedelta of 30 days to the current date to produce datetime objects,  1 month later and 1 month earlier than the current date.

# today is a datetime object
>>> today = datetime.now()
>>> today
datetime.datetime(2021, 7, 27, 15, 25, 8, 89016)

# thirty_days is a timedelta object
>>> thirty_days = timedelta(days=30)
>>> thirty_days
datetime.timedelta(days=30)

>>> thirty_days + today
datetime.datetime(2021, 8, 26, 15, 25, 8, 89016)


>>> today - thirty_days
datetime.datetime(2021, 6, 27, 15, 25, 8, 89016)


>>> today.strftime("%a %x") 
'Tue 07/27/21'

strftime and strptime for datetime

strftime is a method to convert a datetime object into a formatted string under  the control of a format string. strptime is a datetime class method that converts a string representing date-time into a datetime object using a format string.

Examples of strftime

>>> today = datetime.now()

>>> today.strftime("%d %B %Y") 
'27 July 2021'

>>> today.strftime("%d %B %Y %H %M %S%p") 
'27 July 2021 15 25 08PM'

>>> today.strftime("%c") 
'Tue Jul 27 15:25:08 2021'

>>> today.strftime("%x") 
'07/27/21'

>>> today.strftime("%a %x") 
'Tue 07/27/21'

Examples of strptime

>>> datetime.strptime('07/27/21', "%x")
datetime.datetime(2021, 7, 27, 0, 0)

>>> datetime.strptime('Wed 07/28/21', "%a %x")
datetime.datetime(2021, 7, 28, 0, 0)

>>> datetime.strptime('27 July 2021 15 25 08PM', "%d %B %Y %H %M %S%p")
datetime.datetime(2021, 7, 27, 15, 25, 8)

Timestamp

A timestamp is a  way of representing datetime objects as a UNIX epoch i.e. the number of seconds that have elapsed from Jan 1st 1970 UTC.  It’s very simple to convert  between a datetime object and the time stamp.

# datetime => timestamp
>>> dt = datetime(2002, 7, 24, 7, 18, 22)
>>> dt.timestamp()
1027475302.0

# timestamp => datetime
>>> ts = dt.timestamp()
>>> dt2 = datetime.fromtimestamp(ts)
>>> dt2
datetime.datetime(2002, 7, 24, 7, 18, 22)

Additional Reading/References

Ready to learn more about Python datetime or Python in general? Explore some of the links below!

Conclusion

And there we have it – you now have a greater understanding of the Python datetime module and how you can use it for whatever you might need in a Python program. As we discussed, the Python datetime module has various classes to handle dates and times. The key classes are date, time, datetime, timedelta, tzinfo and, timezone.  The date class represents just a date, the time object represents the time independent of date, and datetime represents both the date and time.

Further, we also showed how datetime objects can be created in various ways – using a constructor, combining date and time objects, etc. We also explored formatting: strftime allows us to represent a date/time/datetime object as a string using a format string as guide. strptime uses a format string to convert a string containing the date, time into a datetime object.

However, there is more to learn from here. Though this article does not cover it, the module supports the creation and manipulation of date and times in various time zones, which gives you even more power for your Python programming needs. You can also explore other concepts related to dates, such as getting Daylight Saving Time information, more techniques for dealing with the local time zone, and beyond.

Regardless, with these tools, you can quickly achieve success and build the programs to your desire. We wish you the best of luck with your Python programs!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Learn About Python for Beginners: What is Python Programming https://gamedevacademy.org/python-programming-for-beginners-2/ Tue, 11 Jan 2022 16:00:10 +0000 https://pythonmachinelearning.pro/?p=2932 Read more]]> Did you know that the Python programming language is one of the most in-demand languages in the industry right now?

In fact, a survey of developers by CodinGame lists Python as the #1 most loved programming language, as well as the third most known programming language. Whether web development, advanced data analysis, or even the realm of mobile apps, Python has wormed its way into almost all realms of the industry – and for good reason! Learning Python programming can not only make your coding skills versatile, but also gives you the flexibility to do simple and advanced tasks in relatively easy ways. It should be no wonder why the programming language has gained such a foothold and is quickly becoming one of the most used languages around.

If you’re new to programming or Python, though, you still might be a bit skeptical about what the hubbub is about this (fantastic) programming language. In this beginner-friendly post, we will help you familiarize yourself with Python and take that first step into understanding what Python is, why you should learn Python, and how you can learn about Python with helpful Python tutorials. Let’s waste no time and dive into understanding the Python programming language!

Person clicking folders on device and papers of graphs coming out

What is Python and Python Programming?

Python is a programming language that has been around since 1991. Created by Guido van Rossum, it is a general-purpose language that can be used for software, apps, web development, and more, which attributes largely to the foothold it has managed to gain in development. It is also a high-level, interpreted language, meaning it is far from machine code (thus more human-readable) and executed freely at runtime, making it an easy language to work with and alter on the go.

In fact, the entire design philosophy behind Python was to create a programming language with optimal human readability. As such, compared to other languages, Python code has a higher emphasis on the use of whitespace and indentation. Additionally, it does away with pesky punctuation (like semicolons, the bane of many experienced programmers) and instead ends instructions by line – overall resulting in a clean look for human programmers to read and understanding.

Oh, also, don’t worry. You can use Python for object-oriented programming as well.

What can you do with Python?

Now that some of the technical information is out of the way, let’s talk about what you can actually do with Python programming. As mentioned above, Python is a general-purpose programming language, so the only real limit is your own imagination. However, we’ve broken down some of the main areas below to understand just a little bit of the full scope and power at your fingertips.

Woman looking at phone with various technical text overlays

Automate

One area that interests many people when they first learn about Python is automation. We all have those tedious tasks in our life we just don’t want to do – like editing files with the same information, backing up specific files more frequently than others, etc. With Python code, people have found it easy to create small scripts and programs that do these tasks for us. Need to add a watermark to 100s of images? Automate it! Need to delete files in a folder on a regular basis? Automate it!

In fact, you can take this a step further and combine Python with the web! This means, for example, you can have Python send you e-mail alerts when it’s time to backup your computer. Or perhaps you want to be alerted when a specific webpage updates with new information. As you guessed it, this is another thing you can automate with Python. The list goes on and on, but as a human-readable programming language, more and more people have managed to take tedious tasks off their shoulders and sit back worry-free while their program chugs away doing them automatically – saving time for the more important things in life.

Cute toy robot working at a computer

Data Science

In today’s business world, data collection is paramount for success. Customer activity, industry forecasts, marketing campaign progress, and more all are what truly run today’s world into the expansive field of data science. However, you need a way to both collect data and manipulate that data for interpretation. This is where Python’s ease of use has truly shined, since it is the programming language people have turned to for both tasks. Not only can Python be scripted to collect data, but with the right frameworks, it is easy to automatically create graphs, tables, and more so businesses can interpret the data and make those crucial decisions that much quicker. This has also made it easier for businesses to A/B test and improve their products and services little by little with data that proves the correct direction.

Beyond this, data science also includes things like web scraping, as Python has the ability to go through numerous webpages and pull specific data from them. This is not to mention its applications for databases that are full of data for Python code to take advantage of and automatically use for actionable, data-driven tasks. Overall, when combined with automation, Python makes dealing with data a breeze!

Pie chart and horizontal bar graph about developers

Machine Learning, Computer Vision, and AIs

There is no question our machines are becoming “smarter.” If they weren’t, we wouldn’t be able to have things like self-driving cars, Instagram filters, and similar. However, as you might imagine, teaching a computer to be smart, or even just to “see” an image is a very complicated task that involves lots of finite tweaking and immense amounts of data to train the program. This is one area where there is no question about why Python is, thus, the top choice.

As mentioned, the Python programming language is a high-level, interpreted language. This allows experienced programmers to not only code these complicated tasks in ways that are easy to read, but also use the fact it’s interpreted to more easily tweak things on the fly without having to deal with the time-consuming process of compiling and re-compiling their code every time they change a simple number. There are few contenders when it comes to Python in this area, so if you want to make smart machines that can recognize images or simply learn to write stories, Python is the way to go.

Classification results for an image

Software, Games, & Apps

While we’ve already covered the main areas the Python programming language is widely used for, remember that Python can do a wide range of tasks. As such, while not usually the go-to for a lot of developers, Python can still be used to create software, games, and apps. In fact, there are a variety of frameworks and engines like Ren’Py, PyGame, and Kivy that exist for this express purpose to make it easier – and this doesn’t include frameworks suited for software development. Due to Python’s readability, it also makes it attractive for this area.

It is worth noting that many software, while not written in Python as the main language, will still be integrated with Python interpreters to allow users and developers to create scripts. One such example is the open-source modeling software Blender, which not only lets users access API elements of the program, but also provides the backbone for some of Blender’s tools. Thus, all around, Python is recognized as a powerhouse that is fantastic at certain tasks that are perhaps more tedious in other languages.

Language quiz app made with Python and Kivy

Web Development

Last but definitely not least, Python can be used for the web. We already mentioned that Python is capable of crawling the web and scraping data from it, which is definitely one powerful use for it depending on your web project! However, Python web development goes far beyond this.

Once again, thanks to Python’s ability to handle data in human-readable ways, Python has found extensive use for controlling website backends. This includes things like communicating with databases, handling CRUD (Create, Read, Update, Delete) functions, or even manipulating the DOM if necessary. Similarly to software, games, and apps, there are even specific frameworks designed around the language to make integrating Python not only easy, but beneficial to creating a smooth web project.

Various code in SQL for managing a database

Why Learn Python?

At this point, we’ve learned quite a bit about what the Python programming language is and where you’ll find it. However, maybe you still aren’t quite sure why you should learn Python, especially compared to other languages that are equally beloved. In this brief section, we’re going to break down the main points of why you would want to learn python programming and how it will benefit you.

  • It’s beginner-friendly. 
    As mentioned many times already, Python’s design principle was around human readability. Comparatively, it is much easier to read and write than other programming languages, which all have their own specific quirks when it comes to syntax. This clean look makes it immensely easy to learn for first-time programmers and get them started making their own projects. It is also helpful as you become more experienced, as fields like data science can get complicated the more experienced you become.
  • It’s easy to use for complex tasks.
    For data-heavy tasks seen in data science and machine learning, Python’s readability once again makes it stand out. Python can be used quickly and efficiently to break these sorts of complex tasks down into as few lines of code as possible. It also makes it easy for you, the programmer, to come back later, understand what you were doing, and adjust the code quickly and easily without having to fuss over the complexity in the backend.
  • It’s versatile.
    Maybe you’re one of those developers who wants to make games, websites, software, data science solutions, and automation scripts all at the same time – if only just because you can. Since Python is a general-purpose language, it can do all this and more. This sheer amount of versatility cannot be found in all programming languages, so if you want skills that can be applied in several areas, Python is a good choice.

Bar graph displaying desired skills for data science

  • Python is highly in-demand.
    Particularly in the fields of data analysis and manipulation, Python is the most requested skill-set. As a growing industry, this puts Python on the fast-track to overshadow other languages. However, even outside of this subfield, the Python programming language is noted by CodinGame’s survey to be the third most popular language in general, so you can rest assured you’ll be gaining skills others want!
  • There are great salary opportunities.
    Depending on where you specialize with your Python skills and are located, salary earnings can be immense. For instance, Indeed lists Python developers (with no stated specialization), to earn $110,305 per year in the US on average. Other fields like data scientists and machine learning engineers average at $74,239/year and $130,954/year respectively. Some polling places put the salaries even higher – so suffice it to say, there is fantastic earning potential.
  • There are ample amounts of frameworks and libraries.
    For anyone familiar with coding, you’ll know that frameworks and libraries can be essential for simplifying certain tasks you want to do. As such a popular language, there are a ton of frameworks and libraries available for Python. This includes frameworks that help you train your AIs, create graphs based on simple lines of code, master data science, or even help integrate Python into your website. With the amount of support available, it is very easy to find a framework (and corresponding Python tutorial) to make your life even easier!
  • There is a large community.
    Coding alone can be a drag if you need help with something – especially when we start talking about complicated fields like data science and machine learning. Thankfully, since Python is so popular, there is a huge community ready and willing to help you learn – making it all the easier to learn by association. So don’t fret when it comes to community resources available.

Bar graph showing job growth for specific Python related fields

How do I learn Python?

We’ve mastered the ideas of what the Python programming language is, so the last question remaining is how one might learn this popular and fantastic language to create Python programs. Below, we have created three broad sections that will help you master using Python programming in no time with a variety of Python tutorials.

Master Python syntax & coding principles

As the saying goes, you have to learn to crawl before you can walk. In the case of programming, regardless of language, this is very true. Before you dive into anything else related to Python, it’s important to learn the coding basics. This includes not only Python syntax (i.e. the language’s “grammar”) but also high-level concepts like variables, loops, arrays, and so forth. Without these, no programs can be created – even if you just want to do some basic data science. To get started, we’ve compiled some of our favorite resources below, so please check out each Python tutorial:

Basic linear regression model

Learn relevant Python frameworks & languages

Once you learn the basics of using Python, you’ll also want to explore Python’s frameworks and libraries. Now, this is definitely no easy task even with the many Python tutorials available, as one of Python’s strengths is the immense amount of frameworks and libraries that exist for it. Additionally, because Python is used just about everywhere, many frameworks are specialized for specific tasks such as data science or machine learning. That being said, it is good to explore some of the basic frameworks available to get your feet wet and further solidify the basics of Python.

While we can’t cover every single framework and standard library, we’ve gathered some of our favorites, introduced what they’re for, and provided learning resources below.

NumPy – A library focused on matrices and multi-dimensional arrays. Widely used for data science as a computational tool.

Pandas – A data-oriented software library with a specific focus on manipulating data and analyzing it. Used often for data science.

Matplotlib – A library focused on data visualization for data science. Primarily concerned with creating a variety of charts to understand data.

Tensorflow – A library focused on controlling data flow, making it one of the top libraries used for machine learning neural networks.

Infographic displaying image recognition

Keras – A library focused on neural networks and being user-friendly for machine learning. Works fantastically with Tensorflow!

PyGame  – A cross-platform framework used to make games with Python.

Kivy – A framework focused on creating well-designed and touch-compatible UIs. Sees particular use for mobile apps and web applications.

Django – A web framework designed to make creating web applicationss easier with Python.

Frogger style game made with Python

Create a project

Finally, with Python and an understanding of some of the frameworks available, the next step is to combine it all and actually learn how to use Python and those frameworks to make some Python programs. Once again, we’ve compiled a list of Python tutorials focused on building projects that you can make with your newfound software development skills. What sort of project you make is up to you, whether you dive into software, machine learning, data science, or something else – but learning to actually apply the programming knowledge you learn is half the battle.

Automation

Data Science

Raspberry Pi security camera made with computer vision and machine learning

Machine Learning & Computer Vision

Software/Game/App Python Development

Web Development with Python

Example of an interactive chart made with matplotlib

Conclusion

We hope that you have come to love Python just as much as we do. There is a good reason it is one of the most popular programming languages, and we’re confident any programmer, whether a first-time programmer or experienced programmer, can learn to thrive with the language since Python is used so extensively. Plus, there are so many Python tutorials, it’s easy to find a Python tutorial to suit your specific learning style.

Whether data science, the web, or even games, learning Python programming can be a rewarding experience that will prepare you for a career in development in a number of fields. Even if you’re just a hobbyist, this Python software foundation still serves as a great language to test your skills and provide you with new ways to create and edit the programs you create. Ultimately, though, the future looks bright for the language, and we expect to see more and more developers adopt the skills under the belts.

So what are you waiting for? Get out there, master some Python skills, and take a step into a new world!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
How to Use Data Types & the Python Type() Function https://gamedevacademy.org/python-type-tutorial/ Tue, 03 Aug 2021 05:50:51 +0000 https://pythonmachinelearning.pro/?p=3106 Read more]]> This article discusses types in the Python programming language and the uses of the Python type() function.

While not previously a standard for Python programming, this concept has allowed newer versions of Python to integrate much more smoothly with third-party tools that are made more for statically typed languages and give developers a powerful arsenal for creating their code.

If you’re ready to learn about both object types in Python and the Python type() function, let’s go!

Prerequisites : The reader is expected to have an understanding of Python programming and should have worked with basic Python types such as strings, numbers, etc. The code in this article has been run on Python 3.8. Type annotations were introduced in Python 3.5, so any code related to type annotations is not expected to run on previous versions of Python.

The Python type() function.

Python is a dynamically typed language i.e. a variable is not declared with a specific type as in languages like ‘C’, ‘Java’, etc.  A type is assigned to a variable when it is assigned a value. Gradual typing (type annotations/type hints) was introduced in PEP 484.  However, there is no compile/runtime checking of types. Annotations were introduced mainly for third-party static tools such as lint checkers to perform static checks on the code.

The built in function Python type() has 2 signatures.

1-Argument Version

This version simply returns a return value type object of the object passed in as a single parameter. We will use this signature in various examples below.

# Syntax : class type(object)

# examples
>>> type('Python Types')
<class 'str'>

>>> type(10)
<class 'int'>

3-Argument version

This version is used to dynamically create a new type object (class). We will look at this version later. The examples in the sections below use the 1-argument version of type() on various built-in and custom data types.

Robots painting a wall

Dynamic Typing

Implicit Typing

Python is a dynamically typed language i.e. the type of a variable comes from its value via assignment and not the variable itself. They are type checked just before an assignment or operation (e.g.. +) is performed on them.

# assignment
>>> x = 10
>>> type(x)
class 'int'>

# operation
>>> 'abc' + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
  1. x in the above example gets the type int only after 10 is assigned to it.
  2. In the second example, the type checking on ‘abc’ and 1 happens when the ‘+’ operator is applied.

Explicit Typing/Conversion

Python also allows explicit typing and conversion via various functions. The examples below explicitly convert from a string to a specific type.

>>> s = str("Python types")
>>> type(s)
<class 'str'>

>>> i = int('10')
>>> type(i)
<class 'int'>

>>> f = float('3.5')
>>> type(f)
<class 'float'>

Python Built-in Types

Python primitive types

The 4 primitives in Python are string, integer, float, boolean.

  • Strings are immutable sequences of Unicode characters.
  • Integers represent whole nos (e.g. 5, 10) from negative to positive infinity
  • Floats represent rational nos. Examples include decimal numbers such as 4.5.
  • Booleans represent True / False values.
# String
mystr = "Python Types"

>>> type(mystr)
<class 'str'>

# Int
>>> a = 9

>>> type(a)
<class 'int'>

# Float
>>> f = 4.55555566666

>>> type(f)
<class 'float'>

# Boolean
>>> b = False

>>> type(b)
<class 'bool'>

Photo of Python code on computer screen

Python Non-primitive types

Examples of Python non-primitive types include array, list, tuples, dictionary, and set.

  • Arrays are very similar in functionality to arrays in languages like ‘C’ and ‘Java. They are defined in the array module.
  • Lists store a sequence of values.  They are similar to arrays but allow elements of different data types to be mixed in a sequence. Duplicate elements are allowed.
  • Tuples are similar to lists but are immutable. Duplicate elements are allowed.
  • Dictionaries allow key-value pairs to be stored. The key is required to be immutable.
  • Sets store sequences of values with no duplicates.
>>> from array import array

# integer array
>>> arrint = array("i", [10, 5, 6,])

>>> type(arrint)
<class 'array.array'>
>>> arrint[2]= 15
>>> arrint
array('i', [10, 5, 15])

# list 
>>> l = [1, 2, 'abc'] 
>>> type(l) 
<class 'list'>

#tuple
t = (1,2,'abc')
>>> type(t) 
<class 'tuple'>

# dictionary
>>> d = {'sport': ''Basketball', 'greatest': 'Jordan'}
>>> type(d)
<class dict>

# set
>>> s = set(['John', 'Henry', 'Pooja', 'Katherine'])
>>> type(s)
<class 'set'>

Custom types

Any user-defined class is a custom type in Python. A classes members can be a combination of Python primitive data types and other custom types. Below in the following code, we define a new type (class) called Person.

class Person:
    Person(self, fname, lname, dob, city, state, country) :
        self.first_name = fname
        self.last_name  = lname
        self.dob        = dob
        self.adress     = address
    
>>> p = Person('John', 'Fowler', '05/10/1999', 'Raleigh', 'NC', 'USA')
>>> print (type(p))

<class '__main__.Person'>

3-argument version of type()

The 3-argument version of the type() function returns a new type object.

 class type(name, bases, dict, **kwds)

The name (__name__ attribute) argument is the class name. The bases (__bases__ attribute) argument is the list of base classes  and defaults to object if left unspecified. dict (__dict__ attribute) contains the attributes and methods of the class.

The 2 following statements are equivalent. This version is thus a dynamic way to declare a class.

# static definition
class Person :
    name = "Guido"

# dynamic definition
Person2 = type('Person2', (), dict(name='Guido'))

# class dictionary
>>> Person2.__dict__
mappingproxy({'name': 'Guido', '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Person2' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None})

# instance
>>> p = Person2()
>>> p.role = "BDFL"

# instance dictionary
>>> p.__dict__
{'role': 'BDFL'}
  1. Define a static class Person2 with a single attribute name assigned to value Guido.
  2. Define a dynamic class with the name Person2 and a class level attribute name assigned to value Guido.
  3. Print the class level dictionary. We see the name attribute.
  4. Create an instance p of type Person2.
  5. Attach an instance level attribute role (with value “BDFL”) to it.
  6. Print the instance level dictionary. We see the role attribute.

Let’s look at a more complete example of dynamic class creation and use. The example below contrasts the static definition of the Person class with the dynamic definition of the Person2 class.  The Person2 class dynamically defines its class attributes (counter), its constructor __init__ and a method name2, whose definition is the function fn_name2.

# static class definition
class Person:
    count = 0

    def __init__(self, name):
        self.name = name

    def name(self):
        return "Hi, I am " + self.name

# dynamic class definition

# define methods to be attached to the class definition.
def init_Person(self, name):
    self.name = name

def fn_name2(self):
return "Hello, I am " + self.name

# dynamic class definition
Person2 = type("Person2", (), { "counter":0,
                                "__init__": init_Person,
                                "name2":fn_name2
                              })

>>> x = Person2("Python Types")
>>> print(x.name)
Python Types

>>> print(x.name2())
Hello, I am Python Types

>>> print(x.__dict__)
{'name': 'Python Types'}
  1. Define the static class Person for reference.
  2. Define methods init_Person and fn_name2. These methods will be used in the dynamic class definition Person2.
  3. Define the dynamic class Person2. Similar to Person, It has a class level attribute, counter, an __init__ constructor initialized to init_Person and the name2 method initialized to fn_name2.
  4. Create an object of class Person2 passing in “Python Types” as the name.
  5. Print the object’s name attribute. This shows that the __init__ method of Person2 i.e. init_Person was invoked and that the name attribute was initialized to “Python Types”.
  6. Invoke the object’s name2 method. This prints out the “Hello, I am Python Types” message indicating that the fn_name2 method was invoked properly.
  7. Finally print the object’s dictionary which shows the name attribute.

Two screens being looked at through glasses

Python Type Annotations

Type Annotations is the closest that Python gets to compile-time type checking in languages like ‘C’. Added in Python 3.5 (via PEP 484), this feature is a mere hint to external tools as Visual IDEs or tools such mypy to produce errors when run on the code. These type annotations are not enforceable by the Python runtime. Thus annotations are a useful feature to use in the CI/CD pipeline (via tools like mypy) to detect errors that may cause crashes later.

python interpreter not enforcing annotation

# add10.py - annotation
def add10(n: int) -> int: 
    return n + 10

(mypy) >python add10.py 
Traceback (most recent call last):
File "add10.py", line 6, in <module>
add10("10")
File "add10.py", line 3, in add10
return n + 10 
TypeError: can only concatenate str (not "int") to str

mypy enforcing annotation.

(mypy)> mypy add10.py 
add10.py:6: error: Argument 1 to "add10" has incompatible type "str"; expected "int"
Found 1 error in 1 file (checked 1 source file)

type Vs isinstance

type() only displays the object’s class whereas isinstance takes inheritance into account. The Python documentation recommends the use of isinstance over type for this reason.

class A:
    i = 10

    def __init__(self, name) :
        self.name = name

class B(A) :
    def __init__(self, name, age) :
        super().__init__(name)
        self.age = age

    def __str__(self):
        return (self.name + ':' + str(self.age))


>>> b = B('Mukul', 10)
>>> print (str(b))
Mukul:10
>>> print (type(b))
<class '__main__.B'>

# b is an instance of B and A
>>> print (isinstance(b, B))
True
>>> print (isinstance(b, A))
True

Person at a computer using a mouse

References / Additional Reading:

Besides this article, you can check out more about Python type() and Python in general via the following links below.

Conclusion

And that brings this explanation to a close. By now, you should have a stronger understanding not only in how data types are handled within Python programming, but how Python type() is a useful function to quickly make sure that a Python object is of a particular variable type. The single argument version of type() allows us to do this. As discussed, though, while type() reveals the object type, it does not take the inheritance chain of the object into consideration. We can use the isinstance() function to check the parent classes of the object

While type annotations are not enforced by the Python runtime, they can still be extremely useful (just as many built in functions for Python are). For instance, they help external IDEs and tools such as mypy to provide error messages when a type violation is found in the code. For any experienced coders, you’ll know the more information when debugging the better. However, the uses here are fairly endless, and all just depend on your particular program’s needs. Either way, we hope you get out there and do some Python programming of your very own!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Python Tuple Tutorial: Python Programming for Beginners https://gamedevacademy.org/python-tuple-tutorial/ Fri, 30 Jul 2021 08:38:07 +0000 https://pythonmachinelearning.pro/?p=3108 Read more]]> In this article, we will explore the concept of the Python tuple – immutable, ordered collections of heterogeneous data.

Knowing how to use Python tuples will prove instrumental not only in how you store data, but will help strengthen your knowledge of the basics of Python programming.

Let’s dive in, find out how they work, and learn how we can start creating a tuple!

Prerequisites: The reader is expected to have familiarity with the Python programming language. An understanding of Python lists will be useful as an analogy.

What are Python Tuples

Tuples are immutable, ordered collections of heterogeneous data in Python.  They are immutable in the sense that once created, they cannot be modified in any way. We will look at a caveat below.  Once declared, the order of elements is fixed. They can contain a mixture of data types. They can also contain duplicate elements.

Below, we will explore their various properties.

Creating Tuples

There are a couple of ways to create tuples. Any set of elements separated by comma default to a tuple. However, it is better to explicitly declare a tuple inside of parentheses as shown below.

A tuple constructor can also be used to create the tuple.

>>> a = 'abc', 123, 555, 555
>>> type(a)
<class 'tuple'>

# parentheses
>>> b = ('abc', 123, 555, 555)
>>> type(a)
<class 'tuple'>

# tuple constructor.
>>> my_tuple3 = tuple((1, 2, 3, 4.5, 'Python'))
>>> my_tuple3[4]
'Python'

Elements of a tuple

Tuples can contain either similar or mixed data types. They can also contain duplicate elements.

# elements of similar type
my_tuple = (1, 2, 2, 3, 4, 5)

# elements of mixed types
my_tuple2 = (1, 'Bob', [3.0, 5.0], 'Barbara')

Indexing Tuples

Tuple elements can be accessed by indexing into the tuple. Let’s use the my_tuple2 tuple declared above.

# the first element (o-based indexing)
>>> my_tuple2[0]
1

# the third element
>>> my_tuple2[2]
[3.0, 5.0]

# the second element of the third element 
>>> my_tuple2[2][1]
5.0

Laptop running code

Slicing/Reversing Tuples

Tuples can be sliced just like lists. Let’s use the my_tuple2 tuple declared above.

# first and second elements
>>> my_tuple2[1:3]
('Bob', [3.0, 5.0])

# second and third elements
>>> my_tuple2[2:4]
([3.0, 5.0], 'Barbara')

# reversing a tuple
>>> my_tuple2[::-1]
('Barbara', [3.0, 6.0], 'Bob', 1)

Iteration

We can use a for-loop to iterate over the elements of my_tuple2.

>>> for elem in my_tuple2 :
...     print (elem)
... 
1
Bob
[3.0, 5.0]
Barbara

Immutability

Tuple cannot be modified i.e. elements cannot be modified or deleted. However, it is important to note that a mutable element of a tuple can be changed.

# updation not supported
>>> my_tuple2[1] = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

# deletion not supported
>>> del my_tuple2[2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion
# updation of the mutable list element is allowed.
>>> my_tuple2
(1, 'Bob', [3.0, 5.0], 'Barbara')
>>> my_tuple2[2][1] = 6.0
>>> my_tuple2
(1, 'Bob', [3.0, 6.0], 'Barbara')

# deleting the whole tuple is allowed
>>> del my_tuple2
>>> my_tuple2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'my_tuple2' is not defined

Tuple Unpacking

The elements of a tuple can be unpacked into variables.

# unpacking
>>> a,b,c, d = (1.0, 3, [6, 7], 'Simon')

>>> a
1.0

>>> b
3

>>> c
[6, 7]

>>> d
'Simon'

sphere

Combining / Repeating Tuples

Tuples can be combined using the + operator. They can also be repeated n times using the (tuple)*n syntax.

# concatenation
>>> [1,2,3] + [4,5,6]
[1, 2, 3, 4, 5, 6]

# repetition
>>> (1,2,3)*3
(1, 2, 3, 1, 2, 3, 1, 2, 3)

Use as key in dictionary (Hashing)

Python dictionaries need keys that are immutable. So a data structure such as a list cannot be a dictionary key. But tuples can be keys of a Python dictionary.

>>> d = {'name' : 'John Doe', 'age': 45, 'city':'Cupertino', 'zip code': 94087}

>>> t = (1,2,3)
>>> d[t] = 'Address 1 Address 2 Address 3'
>>> d
{'name': 'John Doe', 'age': 45, 'city': 'Cupertino', 'zip code': 94087, (1, 2, 3): 'Address 1 Address 2 Address 3'}

Element Count, Position

We can find the number of times an element occurs in a tuple as well as the position(s) of an element in a tuple.

>>> t = (1, 2, 3, 2, 2, 5, 6, 7, 8, 1)

# first index of element in tuple
>>> t.index(2)
1

# all indices of an element in tuple
>>> [index for index, value in enumerate(t) if value == 2]
[1, 3, 4]

# count of element in tuple
>>> t.count(2)
3

Useful Functions

The following functions are useful utility functions to examine the elements of a tuple.

>>> t = (1, 1, 3, 2, 5, 6, 7, 8, 9)

>>> len(t)
9
>>> max(t)
9
>>> min(t)
1

Tuple Membership

The standard Python in operator can be used to check if an element is a member of a tuple. The expression returns True if the element is a member of the tuple and False if it is not.

>>> t = (1, 1, 3, 2, 5, 6, 7, 8, 9)

>>> 5 in t
True

>>> 11 in t
False

Person holding a sticky note that says Python

Additional Reading/References

Want to explore a bit more about creating a Python tuple – or Python Programming in general? Check out the links below!

Conclusion

And that concludes our brief tutorial on the Python tuple. Let’s review some key points:

  • Python tuples are very similar to lists. However, they cannot be modified once created.
  • Their immutability makes them usable as dictionary keys.
  • They can be combined using the + operator and replicated using the * operator.
  • Elements can be packed into a tuple and a tuple can also be unpacked into a set of variables for easy access.
  • They can be indexed into and sliced similar to lists.
  • Elements can be repeated in a tuple.
  • The position of an element(s) and its number of occurrences can be easily ascertained using methods available on the tuple or with a simple list comprehension.

What can we take away from this? Well, you should generally (caveat in the article) use tuples where you need a read-only data structure similar to a list (or any data type that can store multiple items). This ensures that your data is protected, but you can still use that information for a lot of things throughout your program.

Whatever the case may be, understanding this foundational element of the Python programming language is essential and will give you more tools to use as you program with Python. We also encourage you to explore other tuple related subjected like nested tuples, making an empty tuple, tuple packing, and more.

So, we wish you the best of luck out there with your Python projects and hope you find the Python tuple useful!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Free Course – Create GUIs for Python Apps with Tkinter https://gamedevacademy.org/python-tkinter-tutorial/ Wed, 30 Jun 2021 01:00:59 +0000 https://coding.degree/?p=1118 Read more]]>

Create desktop GUIs applications with ease by learning Python Tkinter which provides tools like widgets, event handlers, frames, etc. You can also learn more about all Python Tkinter has to offer by exploring the full course below!

Python GUIs with Tkinter for Beginners

About

This Tkinter tutorial, taught by developer Nimish Narang, will help you get started with using Tkinter, Python’s standard toolkit for developing user interfaces. You’ll learn the quickest and easiest way to create GUIs for any Python-based application – no third-party library downloads required – focusing on customizable widgets and event handlers, you’ll explore various ways to size, place, and add interactive UI elements. Regardless of the Python project you wish to build, these foundations will help you enrich and add aesthetics to your Python projects!

]]>
Free Course – Master Python Programming https://gamedevacademy.org/python-complete-course/ Wed, 10 Feb 2021 01:00:44 +0000 https://coding.degree/?p=926 Read more]]>

Learn the popular Python programming language from the ground up and discover core coding fundamentals needed for any Python project! You can also download the project files used for the course below.

Download the project files

About

Following the teachings of instructor Nimish Narang, you’ll explore all the foundations you’ll need to get started programming with the popular Python language – one of the most in-demand languages in the industry. Focusing on the coding fundamentals, you’ll master techniques for storing and manipulating bits of data, controlling the flow of your program, evaluating data, and more. You will also discover how these fundamentals apply in a real-life programming situation.

Whether you want to build games, develop websites, become a master of data science, make the next machine learning program, or something else, learning Python’s fundamentals will set you on the path to becoming a super-powered developer.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Free Course – How to Use Objects and Classes in Python https://gamedevacademy.org/python-classes-objects-tutorials/ Wed, 06 Jan 2021 01:00:53 +0000 https://coding.degree/?p=804 Read more]]>

Explore object-oriented programming foundations for Python by learning to code objects and classes! You can also download the project files used for the course below.

Download the project files

About

In this course taught by Nimish Narang, you will explore some of the core fundamentals of Python programming by learning to use objects and classes. Not only will this allow you to take your first steps into the world of object-oriented programming, but teach you common methods seen throughout the industry for structuring your data and programs. These skills will not only prove essential to your developer skillset, but prepare you to create a number of Python programs for automation, games, and more!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>