Python Basics For Beginners

Sharing is caring 🙂

This introduction to Python is for beginning-level students of the Python language. Python is skyrocketing in popularity as it is very beginner-friendly yet can also be leveraged for the most intense programming challenges. You might recall the news of Python being used to take a picture of a black hole. It sounds like some heavy-duty science to me! In this regard, you can start as a beginner and progress as far as you want – it’s entirely up to you. In this tutorial, we’ll learn all about the basics of the Python programming language and how to get started writing some super simple programs.


Writing Python Code

In this tutorial, we will write some Python Code on Windows. We can add a directory to hold all of our Python scripts to get started. In our case, that can be found in the /c/python/pythonforbeginners directory, as we see here.

directory to hold python scripts

You can use many tools to write Python code, ranging from a simple notepad application to a full-blown Integrated Development Environment such as PyCharm by JetBrains. We will use PyCharm since our aspirations are high even though we are just beginners!

pycharm ide by jetbrains

You’ll need to have Python installed on your machine. Getting it installed with one of the provided installer packages at Python.org is straightforward. Pro tip if you have not already done so: When installing using the installer, choose “Add Python To Path”! This will allow you to simply enter a Python shell from any directory location on your machine.

pycharm open project

Ok, time to write a Python program. Indeed it will be hello world. The first thing to do is to open our directory, which will hold our Python code as a project in PyCharm.


Python Files Have A .py Extension To write some code, we need a file to contain that source code. Python files have a .py extension, and if we want to write a hello world program, maybe we can add it helloworld.py to our project. Here we go.

hello world in pycharm

In that file, you may add the following code:

print('hello world')

Running Your Python Program

We try to run the program from our hyper terminal, but we get a problem.

pythonforbeginners $helloworld.py
bash: helloworld.py: command not found

Instead, we will change to Powershell for our command-line program and run the program there. To run our fancy hello world program, we can just type python helloworld.py at the command line and watch the output in all its glory!

python hello world powershell

We can also run the program right in PyCharm. There are a few ways to do this, but one easy one is to simply right-click on the Python file you wish to run and choose Run ‘helloworld’.

pycharm run helloworld

If everything goes according to plan, an integrated Python console will open in the lower area of the PyCharm window and show you the script’s output. In our case, that is simply ‘hello world.’

pycharm debug output window

Ok! You may laugh, but this could be the beginning of a beautiful journey to excellent programs you will write in Python to do automation tasks, create websites, collect data from the internet, or any other task you can think of. You may also be interested in Django For Beginners for web development with Python.


Variables And Expressions In Python

You will need to use variables to do anything of much use in your Python programs. Like in other programming languages, a variable in Python is a memory location you can store values in. Depending on the variable type, the Python interpreter will allocate memory and allow a variable of a given type to be stored. These may be integers, floats, or strings.


Declaring A Variable

With that knowledge, we can add a variables.py file to our PyCharm project and test some concepts of variables.

python variable

Using the above code, we can try it out in the Python REPL, which comes with any Python installation. At a Powershell command prompt, we can type Python to enter the REPL. Then, we type a variable name my_variable and use the assignment operator (=) to place a number value of 77 in the variable. By using the built-in print() function, we can see the output of whatever is stored inside of my_variable.

PS C:pythonpythonforbeginners> python
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> my_variable = 77
>>> print(my_variable)
77

Re-declare / Overwrite A variable

In Python, you can assign a new value to the named variable, replacing the original value with the new one. The new value can also be of a new type. Here we overwrite the initial integer with a string.

>>> my_variable = "Put a string in the variable"
>>> print(my_variable)
Put a string in the variable

Respecting Data Types

Python is what’s called a strongly typed language. You don’t need to declare the type when creating a variable. Still, you need to respect the data type contained in a variable, as Python has no Type Coercion (the process of converting a value from one type to another). Let’s see that in action.

Adding two variables of the same type is perfectly fine.

>>> print(7 + 7)
14
>>> print('string one ' + 'string two')
string one string two

Contrast this with trying to add a string to an integer.

>>> print('Seven' + 7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

You can’t do it. You will get a type error, as we see above. We can turn the number 7 into its string representation, and the Python interpreter will no longer complain.

>>> print('Seven' + str(7))
Seven7

How do functions affect variables?

Functions in Python have their local copy of whatever variables you declare inside the function. The examples above have been using what is known as global variables. That means they can be accessed from anywhere. Let’s see an example of a variable inside a function that is not global but local. We can define a function, populate a variable, and print it out. This entire logic is contained in the function itself.

def my_function():
    local_variable = "Funk soul brother"
    print(local_variable)
global vs local python variables

We can now call this function by simply typing my_function(). We should see the string Funk soul brother output on the screen.

What happens if we try to access local_variable it directly, though, by using something like print(local_variable) *outside* of the function? Well, we get an error.

Traceback (most recent call last):
File “C:/python/pythonforbeginners/variables.py”, line 6, in <module>
print(local_variable)
NameError: name ‘local_variable’ is not defined

python function variable not available outside

Consider this code which clearly demonstrates that the local_variable outside of the function and the local_variable inside the function are two different variables.

local_variable = "I'm actually global"


def my_function():
    local_variable = "Funk soul brother"
    print(local_variable)


my_function()
print(local_variable)

The output of running this function is:

Funk soul brother
I'm actually global

The Python global keyword

Now let’s add the Python global keyword like so:

local_variable = "I'm actually global"


def my_function():
    global local_variable
    local_variable = "Funk soul brother"
    print(local_variable)


print(local_variable)
my_function()
print(local_variable)

What do you think the output of the above code will be?

I'm actually global
Funk soul brother
Funk soul brother

On the first call, the output of I’m actually global appears. Then we run the function my_function(), and the output of Funk soul brother appears. Now in this step, since we used the global keyword, the variable outside the function is affected. The local_variable inside and outside of the function is now the same variable. Making the last call to print(local_variable) shows this as Funk soul brother is the output.

The Python del keyword

The del keyword is used to delete the definition of a previously declared variable. This allows the programmer to undefine variables in real time by using the del keyword. This stack overflow thread has some ideas of when to use the del keyword. Let’s see an example of putting del to work here.

local_variable = "I'm actually global"


def my_function():
    global local_variable
    local_variable = "Funk soul brother"
    print(local_variable)
    del local_variable


print(local_variable)
my_function()
print(local_variable)

The above code outputs as such:

I'm actually global
Funk soul brother

Traceback (most recent call last):
  File "C:/python/pythonforbeginners/variables.py", line 13, in 
    print(local_variable)
NameError: name 'local_variable' is not defined

The first print(local_variable) works fine, and the my_function() call works fine, but then the last call to print(local_variable) fails. It fails because, inside the function, we added the del local_variable line. This removes that local_variable right after it outputs the local_variable.


Functions In Python

No matter what programming language an application is written in, the logic is broken into smaller, reusable chunks of code known as functions. This concept holds with Python as well. Let’s learn a little more about how to use functions in Python.


Defining A Function In Python

To declare a function in Python, you use the def keyword.

def pyfunc():
    print("This is a function")


pyfunc()
This is a function

The function above doesn’t take any arguments, but there are a few exciting things to consider. If you program in C, C#, PHP, Java, or JavaScript, you’ll notice that we don’t have any curly braces in Python. In Python, those curly braces are replaced with the colon : and indentations to denote function scope. That’s the key takeaway of defining a function in Python. You use the def keyword, a colon, and indentation.


Arguments To A Function

Arguments to a function allow passing information into a function at runtime. The function can then use that information as it does the work it was designed to do. Here is a simple greeter function that takes two arguments.

def greeter(name, message):
    print('Hi ' + name + ', ' + message)


greeter('John', 'How are you today?')
Hi John, How are you today?

Returning A Value

Functions can return a value. Here is a function that takes a number, doubles it, and returns it.

def doubler(number):
    return number * 2


doubler(128)

Running the above function will produce no output. To use a returned value, you can store it in a variable and then output it like so.

def doubler(number):
    return number * 2


result = doubler(128)
print(result)
256

Default Argument Values

To demonstrate default argument values, we can look at this function which returns a number to a specific power. Now, if you don’t supply the second argument, the function will assign the default value of 2. So if you call power(2), it returns 2 to the power of 2. On the other hand, if you call power(2, 10), that produces 2 to the power of 10.

def power(num, x=2):
    result = 1
    for i in range(x):
        result = result * num
    return result


result = power(2)
print(result)
4
def power(num, x=2):
    result = 1
    for i in range(x):
        result = result * num
    return result


result = power(2, 10)
print(result)
1024

Variable number of arguments

Another thing you can have in Python is a function that has a variable number of arguments. Using the approach, we can create a function that will add up all of the numbers you provide to it. Here is the code for that.

def variableargs(*args):
    result = 0
    for x in args:
        result = result + x
    return result


print(variableargs(2, 2))
4

If you call the function with a different number of arguments, then there is no problem!

print(variableargs(2, 2, 5, 12, 77, 123, 875))
1096

Conditional logic With if, else, elif, and Ternary Operator

Programs need to make decisions to be helpful. A program often must compare values and execute code based on logical outcomes. This is what conditional logic is used for. In Python, conditionals are handled by the if, else, elif, and Ternary Operator.

Python if

python if syntax

The Python if is used to check a condition. If the condition is true, the indented code will be executed immediately following the if condition test.

Here is a simple example of an if test in Python.

foo = 50
bar = 100

if foo < bar:
    string = "foo is less than bar"

print(string)

In the example above, the foo variable holds 50 while the bar variable holds 100. Therefore, when we check to see if foo is less than bar, the condition is true, so foo is less than bar and is output to the terminal.

Python if else

python if else syntax

The if condition can have an else clause as well. This is useful when the if condition is false, yet you want some other behavior to happen.

Here we add an else clause to our original if example. We also change the value of foo to 500 so that our else clause will trigger.

foo = 500
bar = 100

if foo < bar:
    string = "foo is less than bar"
else:
    string = "foo is greater than bar"

print(string)
foo is greater than bar

Python elif

python elif syntax

The elif in Python works like else if in other programming languages.

What if the foo and bar variables are equal? In that case, we need to add another check for that condition and handle it correctly. For that, we can make use of elif.

foo = 500
bar = 500

if foo < bar:
    string = "foo is less than bar"
elif foo == bar:
    string = "foo and bar are equal"
else:
    string = "foo is greater than bar"

print(string)
foo and bar are equal

Python ternary

The last flow control (conditional) operator we will look at is the ternary operator. It is like shorthand for an if elif condition.

foo = 500
bar = 1000

value = foo if foo < bar else bar

print(value)
500

The ternary in Python is not all that readable, so it might be best to stick with if, else, and elif for flow control.


Tackling Repetitive Tasks With Loops

Part of the power of programming is to repeat simple tasks very quickly and easily. Python provides a couple of looping constructs like other programming languages to handle this.

While Loop

The while loop is used to run a code block while a particular condition is true. Some languages provide all kinds of ways of making loops. Python likes to simplify things and offers two methods of making loops, while and for. Here is an example of the Python while loop, we’ll get to the for loop in a minute. First, let’s check out a simple while loop.

counter = 0

while (counter < 5):
    print(counter)
    counter = counter + 1
0
1
2
3
4

For Loop

The for loop is often used with the Python range function like so.

for counter in range(3, 7):
    print(counter)
3
4
5
6

For Loop On A Collection

for loops operate over sets of things, not just numbers. In this example, we are iterating over a list of colors.

colors = ["Red", "Green", "Blue", "Yellow", "Orange", "Purple", "White"]
for color in colors:
    print(color)
Red
Green
Blue
Yellow
Orange
Purple
White

Break and Continue

The break statement is used to break the execution of a loop if a condition is met.

break

for counter in range(4, 11):
    if (counter == 8): break
    print(counter)
4
5
6
7

continue

The opposite of this is the continue statement, which means skipping the rest of a loop’s execution.

for counter in range(4, 11):
    if (counter % 2 == 0): continue
    print(counter)
5
7
9

Enumerate For Index Usage

To get the index of a list item, you can use the Python enumerate function. It will iterate over a collection as a loop does, but in addition to returning the value of the item being looked at, it also returns the value of the index for the item in question.

colors = ["Red", "Green", "Blue", "Yellow", "Orange", "Purple", "White"]
for index, color in enumerate(colors):
    print(index, color)
0 Red
1 Green
2 Blue
3 Yellow
4 Orange
5 Purple
6 White

Object Oriented Python

Python has Classes that are used to logically group data and functions in a way that is easy to reuse and build upon. This is where Python gets fun. Learning how to leverage code reuse in Python will have you making all kinds of valuable programs.

Defining A Python Class

Just like in all programming languages, a Class is similar to a Blueprint to create objects from which you can use in your program. The easiest way to understand this is to create a Python class like so simply.

class Car:

    def __init__(self, make, model, color):
        self.make = make
        self.model = model
        self.color = color

The code above defines a Car class. We know a car can have a color, a make, and a model. That is why we added those variables to represent those characteristics. You’ll notice a couple of exciting things in the Car definition. First is that you can see the definition of the __init__ method. __init__ is a reserved method in Python classes. It is also known as the Constructor for the class and is used to initialize any variables for the class. The other interesting thing we see is the self keyword. The self is similar to this in other languages. Usually, the first argument to any class method is the self argument, which refers to the object itself.

Adding Methods To Classes

Classes need to have methods to do fun and practical tasks. What are methods? They are just functions that exist inside of a class. So let’s go ahead and add a method that outputs all the information about our Car.

class Car:

    def __init__(self, make, model, color):
        self.make = make
        self.model = model
        self.color = color

    def makemodel(self):
        return 'This is a {} {} {}'.format(self.color, self.make, self.model)

We see that new makemodel() method, which accepts an instance of the object via the self keyword. Then, we can access the variables (attributes) of the class using things like self.color, self.make, and self.model. In the return statement, we simply use the format() function to insert the variable data inside the returned string. It’s like a form of interpolation.

Creating An Object From A Class

We have the blueprint. Let’s now create an instance of the class. This is relatively easy and uses this simple syntax.

car1 = Car('Subaru', 'Outback', 'Blue')

We can now use something like print(car1) to see what this new variable is.

<__main__.Car object at 0x00BD1DC0>

Accessing any of the variables of that instance can be done like so.

print(car1.make)
print(car1.model)
print(car1.color)
Subaru
Outback
Blue

Alternatively, we can call that one method to see all the information.

print(car1.makemodel())
This is a Blue Subaru Outback

With one class, we can create multiple objects. Let’s create another Car object and test that out.

car2 = Car('Tesla', 'Model 3', 'White')

print(car2.makemodel())
This is a White Tesla Model 3

Python Dates and Times

Working with dates and times is a standard programming task. Python gives you several modules to handle these scenarios like date, time, datetime, calendar, and timedelta.

Dates and Times Basics

To start working with dates and times, we can add these two lines to the top of a new python file. The python datetime module provides classes for manipulating dates and times.

from datetime import date
from datetime import datetime

We can use the simple today() method from the date class to get today’s date.

today = date.today()
print("Today's date is ", today)
Today's date is  2019-12-17

Here is how to print out the individual components of a date.

print("Date Components: ", "Day:" + str(today.day), "Month:" + str(today.month), "Year:" + str(today.year))
Date Components:  Day:17 Month:12 Year:2019

Each weekday has a number (0=Monday, 6=Sunday) which you can use in your program.

print("Today's Weekday number is: ", today.weekday())
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print("In other words, today is  " + days[today.weekday()])
Today's Weekday number is:  1
In other words, today is  Tuesday

Example of getting today’s date from the datetime class.

today = datetime.now()
print("The current date and time is ", today)
The current date and time is  2019-12-17 13:28:46.764101

You can use the .now() method to get the current time.

t = datetime.time(datetime.now())
print("The current time is ", t)
The current time is  13:29:46.171494

Formatting Dates and Times

The examples above could benefit from some better formatting of the output. Python can format dates and times, so they are much more user-friendly. Here are a few examples.

Full-year with a century

now = datetime.now()
print(now.strftime("The current year is: %Y"))
The current year is: 2019

Abbreviated day, num, full month, abbreviated year

now = datetime.now()
print(now.strftime("%a, %d %B, %y")) 
Tue, 17 December, 19

Locale’s date and time

now = datetime.now()
print(now.strftime("Locale date and time: %c"))
print(now.strftime("Locale date: %x"))
print(now.strftime("Locale time: %X"))
Locale date and time: Tue Dec 17 13:36:56 2019
Locale date: 12/17/19
Locale time: 13:36:56

Two types of time formats

now = datetime.now()
print(now.strftime("Current time: %I:%M:%S %p"))  
print(now.strftime("24-hour time: %H:%M")) 
Current time: 01:36:56 PM
24-hour time: 13:36

Working With Calendar Data

Python has a neat calendar module with which you can do some impressive things.

Create a calendar as a textual table. Cool!

c = calendar.TextCalendar(calendar.SUNDAY)
str = c.formatmonth(2020, 1, 0, 0)
print(str)
Su Mo Tu We Th Fr Sa
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

This simple code allows you to create an HTML version of the same calendar.

htmlcalendar = calendar.HTMLCalendar(calendar.SUNDAY)
str = htmlcalendar.formatmonth(2020, 1)
print(str)
January 2020
SunMonTueWedThuFriSat
   1234
567891011
12131415161718
19202122232425
262728293031 

The Calendar module gives us valuable utilities for the given locale, like the names of days and months in both full and abbreviated forms.

for name in calendar.month_name:
    print(name)
January
February
March
April
May
June
July
August
September
October
November
December
for day in calendar.day_name:
    print(day)
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Using the calendar module, you could figure out the dates of a particular meeting. For example, if you know that an engagement happens on the first Tuesday of every month, you could use this Python script to determine the date for each meeting.

print("The meetings fall on these dates:")
for m in range(1, 13):
    # returns an array of weeks that represent the month
    cal = calendar.monthcalendar(2020, m)
    # The first Tuesday has to be within the first two weeks
    weekone = cal[0]
    weektwo = cal[1]

    if weekone[calendar.TUESDAY] != 0:
        meetday = weekone[calendar.TUESDAY]
    else:
        # if the first tuesday isn't in the first week, it must be in the second
        meetday = weektwo[calendar.TUESDAY]

    print("%10s %2d" % (calendar.month_name[m], meetday))
The meetings fall on these dates:
   January  7
  February  4
     March  3
     April  7
       May  5
      June  2
      July  7
    August  4
 September  1
   October  6
  November  3
  December  1

Timedelta In Python

The timedelta() method can be used for calculating date differences and for date manipulations in Python. Let’s see a few examples.

Create a simple timedelta and print it

print(timedelta(days=365, hours=3, minutes=1))
365 days, 3:01:00

Print out today’s date

now = datetime.now()
print("Today is: " + str(now))
Today is: 2019-12-17 14:12:26.606124

Print today’s date one year from now

print("One year from now it will be: " + str(now + timedelta(days=365)))
One year from now it will be: 2020-12-16 14:12:26.606124

Create a timedelta that uses more than one argument

print("In a week and 3 days it will be: " + str(now + timedelta(weeks=1, days=3)))
In a week and 3 days it will be: 2019-12-27 14:12:26.606124

Calculate the date one week ago, formatted as a string

t = datetime.now() - timedelta(weeks=1)
s = t.strftime("%A %B %d, %Y")
print("One week ago it was " + s)
One week ago it was Tuesday December 10, 2019

Use a timedelta to calculate the number of days until next Christmas.

today = date.today()
christmas = date(today.year, 12, 25)

if christmas < today:
    print("Christmas already went by %d days ago" % ((today - christmas).days))
    christmas = christmas.replace(year=today.year + 1)

time_to_christmas = christmas - today
print("It's just", time_to_christmas.days, "days until next Christmas!")
It's just 8 days until next Christmas!

Working With Files In Python

They say that in Linux, everything is a file. That said, files are super important no matter what OS you are working on. Python makes it easy to work with the filesystem, whether Linux or Windows. Let’s see examples of how to read and write files in Python.

To open a file for writing, you can use the following code.

file = open("mytextfile.txt", "w+")

With your file now open, you can write to it using the .write() method. You’ll want to close the file using .close() once complete.

for i in range(7):
    file.write("This is line %drn" % (i + 1))
file.close()
python file write example beginner

Sure enough, if we look in the Python script’s directory, there is a new mytextfile.txt file. We can open it up and see the contents.

python read and readline

We can use Python to open files and read their contents. To show this, let’s modify the text in our file manually. We’ll just put some random content in there, and then we will use Python to read the contents to the screen. Here is the updated file.

Now we will use the .read() method to read all of the file’s contents in one shot.

file = open("mytextfile.txt", "r")
if file.mode == 'r':  # check to make sure that the file was opened
    contents = file.read()
    print(contents)
pycharm read file to output

We can run the Python script in Pycharm, and the results are what we expect in the debug output.

We can also read the file line by line with this code.

file = open("mytextfile.txt", "r")
if file.mode == 'r':
    filelines = file.readlines()
    for line in filelines:
        print(line)

The os module

When working with files, we can import the python os module to get more information about the operating system and files we are working on.

To see the operating system’s name, you can use this code.

print(os.name)
nt (windows)
posix (linux)

You can use the .exists(), .isfile(), and .isdir() methods for the existence of files or directories.

print("Item exists: " + str(path.exists("mytextfile.txt")))
print("Item is a file: " + str(path.isfile("mytextfile.txt")))
print("Item is a directory: " + str(path.isdir("mytextfile.txt")))
Item exists: True
Item is a file: True
Item is a directory: False

Working with the path for files can be done using .realpath().

print("Item's path: " + str(path.realpath("mytextfile.txt")))
print("Item's path and name: " + str(path.split(path.realpath("mytextfile.txt"))))
Item's path: C:pythonpythonforbeginnersmytextfile.txt
Item's path and name: ('C:\python\pythonforbeginners', 'mytextfile.txt')

Check the modification time on the file and how long ago it was modified

t = time.ctime(path.getmtime("mytextfile.txt"))
print(t)

td = datetime.datetime.now() - datetime.datetime.fromtimestamp(path.getmtime("mytextfile.txt"))
print("It has been " + str(td) + " since the file was modified")
Tue Dec 17 14:52:35 2019
It has been 0:20:33.005550 since the file was modified

Here is a collection of different things you can do with the os module, directories, and files.

Get the path to a file in the current directory

src = path.realpath("mytextfile.txt")

Make a backup copy by appending “bak” to the name

dst = src + ".bak"
# # now use the shell to make a copy of the file
shutil.copy(src, dst)

Copy permissions, modification times, and other info to the new file

shutil.copystat(src, dst)

Rename the original file

os.rename("mytextfile.txt", "newfile.txt")

Put directory contents into a ZIP archive

root_dir, tail = path.split(src)
shutil.make_archive("archive", "zip", root_dir)

Web Scraping, JSON, and XML

The final topics we’ll look at in this introduction to Python tutorial focus on fetching data from the internet, working with JSON formatted data, and parsing XML structured data. Python has all kinds of built-in tools to complete these tasks, so let’s look at a few simple examples.

Make A Request To A Web Server

import urllib.request  # import urllib.request

# open a connection to a URL using urllib
webUrl = urllib.request.urlopen("https://www.bing.com")

# print out the http status code
print("result code: " + str(webUrl.getcode()))

# read the data from the URL and print it
data = webUrl.read()
print(data)
python webscraping example

Now that we know how to fetch data from a given URL, we will use our skills to read a public JSON API. For this example, we will use https://random.dog/woof.json. This great JSON API returns the URL for a random dog picture on each request. Visiting this URL in the browser shows the nature of the structured JSON response.

json api to parse with python

Here is our Python script to fetch the JSON data from this public API.

import urllib.request
import json

urlData = "https://random.dog/woof.json"

webUrl = urllib.request.urlopen(urlData)

print("result code: " + str(webUrl.getcode()))

if (webUrl.getcode() == 200):
    data = webUrl.read()
    theJSON = json.loads(data)
    print(theJSON['fileSizeBytes'])
    print(theJSON['url'])
else:
    print("Received an error from server, cannot retrieve results " + str(webUrl.getcode()))

On each script run, we see an output like this in Pycharm.

json response to parse with python

Look at all the cute Doggos this API provided us with!

randomdog json api results

Parsing XML Data

Consider we have this simple XML document shown here.

<?xml version="1.0" encoding="UTF-8" ?>
<car>
    <make>Tesla</make>
    <model>Model S</model>
    <color>Red</color>
    <option name="Autopilot"/>
    <option name="Extended Range"/>
    <option name="Clear Coat"/>
</car>

Now we want to be able to use Python to read that XML document and parse the results. To do that, we can use a script like this.

import xml.dom.minidom

# use the parse() function to load and parse an XML file
doc = xml.dom.minidom.parse("samplexml.xml")

# print out the document node and the name of the first child tag
print(doc.nodeName)
print(doc.firstChild.tagName)

# get a list of XML tags from the document and print each one
options = doc.getElementsByTagName("option")
print("%d options:" % options.length)
for option in options:
    print(option.getAttribute("name"))
#document
car
3 options:
Autopilot
Extended Range
Clear Coat

Cool! We can also use Python to modify or add elements to an XML structure. This code here adds a new option tag to the current XML Document.

import xml.dom.minidom

# use the parse() function to load and parse an XML file
doc = xml.dom.minidom.parse("samplexml.xml")

# create a new XML tag and add it into the document
newOption = doc.createElement("option")
newOption.setAttribute("name", "Race Tires")
doc.firstChild.appendChild(newOption)

# read the new XML document
options = doc.getElementsByTagName("option")
print("%d options:" % options.length)
for option in options:
    print(option.getAttribute("name"))
4 options:
Autopilot
Extended Range
Clear Coat
Race Tires

Learn More About Beginning Python

This has been a great introduction to the Python programming language, but you will need more resources to learn as much as possible! Check out some great ones listed below.


Python Basics For Beginners Summary

If you made it through this tutorial, congratulations! We covered a lot of ground here, especially if you are new to Python. We covered a lot, including the Pycharm IDE, creating our first hello world script, variables, and expressions, essential python functions, conditional statements and loops, classes, dates, time, formatting time, calendars, working with files, fetching data from the web, parsing JSON data, and manipulating XML data. This beginner-level tutorial has prepared you to dig deeper into Python.

Sharing is caring 🙂