Elena' s AI Blog

Python Programming Language

28 Oct 2021 / 6 minutes to read

Elena Daehnhardt


Midjourney AI-generated art


Introduction

Python is relatively easy to learn and beginner-friendly. I like Python because you can program any kind of project with it. It is open-source and free for anyone to use. Python has well-tested machine learning libraries and a very supportive community. I will overview herein a basic syntax of the Python programming language. This will be useful for beginners or people who move quickly from another programming language to Python.

Why Python?

Python is a general-purpose, object-oriented programming language. It was created by Guido Van Rossum initially thought of as a hobby project in 1989 during Xmas vacation. Python is relatively easy to learn and beginner-friendly. I like Python because you can program any kind of project with it. It is open-source and free for anyone to use. Python has well-tested machine learning libraries and a very supportive community. I will overview herein a basic syntax of the Python programming language. This will be useful for beginners or people who move quickly from another programming language to Python.

Basic Syntax

In Python, we do not need to declare types of variables as we do in Java programs. We can declare variables in any ode place. The variables and the data types they store can also be changed dynamically, thus during the code executions. This is why Python is called “dynamically typed programmed language.”

# This is a comment, starting with #
# Below we declare a variable named "birds", assigned an integer value
birds = 5
# We can print here a number of birds, and use %d to place the birds value into the string
print("We have %d birds in stock!"%birds)
    We have 5 birds in stock!
# Type of the variable "birds"
type(birds)
    int
# Next, we can change the "birds" variable into a list with bird names
birds = ["Eagle", "Chicken", "Stork", "Swan"]
# Type of the variable "birds" changed "on the fly"!
type(birds)
    list
# The Python len() method is a built-in function calculating the length of any iterable object, 
# such as our list of birds.
# We also use here "if-elif-else" statement to test how many birds are in list
if len(birds)<5:
    print("We have too few birds at the moment.")
elif len(birds)==5:
    print("It is all right, 5 birds in stock!")
else:
    print("Too many birds need food!")
    We have too few birds at the moment.

Dictionary data structure contains keys and variables. For instance, we can keep wing spans of birds in the dictionary “wing_spans.”

# an empty dictionary
wing_spans={}
# create a list of wing spans in sentimeters for each bird in the "birds" list:
# and store it in a temporary variable temp
temp=[200, 50, 110, 240]

Alternatively, we could just define the dictionary by hand, for each bird:

wing_spans=dict(zip(birds, temp))
wing_spans
    {'Eagle': 200, 'Chicken': 50, 'Stork': 110, 'Swan': 240}
wing_spans = {'Eagle': 200, 'Chicken': 500, 'Stork': 110, 'Swan': 240}
for key, value in wing_spans.items():
    print("%ss' wing span is about %d santimeters."%(key, value))
    Eagles' wing span is about 200 santimeters.
    Chickens' wing span is about 500 santimeters.
    Storks' wing span is about 110 santimeters.
    Swans' wing span is about 240 santimeters.

It seems that chicken’s wing span is the largest among our birds! This cannot be. Let’s fix it and correct 500 centimeters of wing span for chickens:

wing_spans['Chicken'] = 50
wing_spans
    {'Eagle': 200, 'Chicken': 50, 'Stork': 110, 'Swan': 240}

Build-in max and min functions to get minimum and maximum of their argument values are as follows:

max(wing_spans.values()) # values() gets all the integer values from the dictionary wing_spans!
    240
min(wing_spans.values()) 
    50

List Comprehensions

List comprehensions are my favorite feature in Python. We can create new lists based on another list, tuple, range, or string. It has a concise syntax:

# squares of numbers from range
squares = [ x**2 for x in range(11)]
print(squares)
    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# string operations
[x.upper() for x in "hello!"]
    ['H', 'E', 'L', 'L', 'O', '!']

Here we open a log text file and find lines with the string “FAIL” in it.

# for lines in file
f=open("log.txt","r")
result=[x for x in f if "FAIL" in x]
result
    ['3/12/2019\tMaintanance\tFAIL\n']
# using functions
from math import sin
[sin(x) for x in [1,2,4]]
    [0.8414709848078965, 0.9092974268256817, -0.7568024953079282]

Tools and IDE

Wherein can we write Python programs? We can use any text editor that is suitable for writing programming code. However, when the code has a complex structure and grows a lot, it is better to use an Integrated Development Environment (IDE), a software application providing functionality for more comfortable coding. At the moment, I use PyCharm, which is integrated with Git for version control. This way, the code is stored locally and online and accessible from anywhere on the Internet. Another advantage of GIT is that we keep track of all code changes and can always roll back when something goes wrong.

Did you like this post? Please let me know if you have any comments or suggestions.

Python posts that might be interesting for you



Conclusion

In this post, I described basic data structures on Python such as lists, dictionaries, and tuples, shown some examples of code flow statements and the usage of list comprehensions. I am going to continue on Python coding in the following days. You can get the code in progress in the Colab file. Thanks for reading!

desktop bg dark

About Elena

Elena, a PhD in Computer Science, simplifies AI concepts and helps you use machine learning.

Citation
Elena Daehnhardt. (2021) 'Python Programming Language', daehnhardt.com, 28 October 2021. Available at: https://daehnhardt.com/blog/2021/10/28/edaehn-python/
All Posts