Python Basics For Beginners

python basics for beginners

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 on earth. 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 complete 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. To get started, we can add a directory to hold all of our Python scripts. In our case that can be found in the /c/python/pythonforbeginners directory as we see here.

directory to hold python scripts

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

pycharm ide by jetbrains

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

pycharm open projectOk, 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

In order 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 a helloworld.py to our project. Here we go.

hello world in pycharm

In that file, you may add the following code:

Running Your Python Program

We try to run the program from our hyper terminal, 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 of its glory!

python hello world powershell

We can also run the program right in PyCharm. There are actually 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’ like so.

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 output of the script. 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 wonderful 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.


Variables And Expressions In Python

In order to do anything of much use in your Python programs, you will need to use variables. Just like in other programming languages, a variable is a memory location you can store values in. Depending on the type of the variable, 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 out.

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 simply type a variable name of my_variable and use the assignment operator (=) to place a number value of 77 in the variable. By using the build in print() function, we can see the output of whatever is stored inside of my_variable.

PS C:\python\pythonforbeginners> 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 simply assign a new value to the named variable, and this will replace 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, but you do need to respect what data type is 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 like we see above. We can turn the number 7 into it’s 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 own 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, which 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.

We can now call this function by simply typing my_function(). We should see the string Funk soul brother output to the screen.
global vs local python variables

What happens if we try to access local_variable 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 demonstrates clearly that the local_variable outside of the function and the local_variable inside of the function are two different variables.

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:

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 of print(local_variable), 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. In reality, the local_variable inside and outside of the function are 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 variable that was previously declared. 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.

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, the my_function() call works fine, but then the last call to print(local_variable) fails. It fails because inside of the function, we added the del local_variable line. This removes that local_variable right after it outputs local_variable.


Functions In Python

No matter what programming language an application is written in, the logic is broken up into smaller, reusable chunks of code known as functions. This concept holds true 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.

This is a function

The function above doesn’t take any arguments but there are a few interesting things to consider. If you program in C, C#, PHP, Java, or JavaScript, you’ll notice that in Python we don’t have any curly braces. 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 provide the ability to pass 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.

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.

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

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, then the function will assign the default value of 2. So if you call power(2), then it is returned 2 to the power of 2. On the other hand, if you call power(2, 10), then that returns 2 to the power of 10.

4

1024

Variable number of arguments

Another thing you can have in Python is a function which 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.

4

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

1096

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

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

Python if

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

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

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 is output to the terminal.

Python if else

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

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 is greater than bar

Python elif

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

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 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.

500

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


Tackling Repetitive Tasks With Loops

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

While Loop

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

0
1
2
3
4

For Loop

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

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.

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

4
5
6
7

continue

The opposite of this is the continue statement which basically means to skip the rest of the execution of a loop.

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 like 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.

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 also easy to build upon. This is where Python gets really fun. Learning how to leverage code reuse in Python will have you building all kinds of useful programs.

Defining A Python Class

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

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 interesting 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 of the methods of a class is the self argument and the self argument refers to the object itself.

Adding Methods To Classes

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

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 make use of the format() function to simply insert the variable data inside of 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 quite easy and uses this simple syntax.

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

<__main__.Car object at 0x00BD1DC0>

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

Subaru
Outback
Blue

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

This is a Blue Subaru Outback

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

This is a White Tesla Model 3

Python Dates and Times

Working with dates and times is a common 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 datetime module provides classes for manipulating dates and times.

To get today’s date we can use the simple today() method from the date class.

Today's date is  2019-12-17

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

Date Components:  Day:17 Month:12 Year:2019

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

Today's Weekday number is:  1
In other words, today is  Tuesday

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

The current date and time is  2019-12-17 13:28:46.764101

To get the current time you can use the .now() method like so.

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 has the ability to format dates and times so they are much more user-friendly. Here are a few examples.

Full year with century

The current year is: 2019

Abbreviated day, num, full month, abbreviated year

Tue, 17 December, 19

Locale’s date and time

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

Current time: 01:36:56 PM
24-hour time: 13:36

Working With Calendar Data

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

Create a calendar as a textual table. Cool!

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

You can create an HTML version of the same calendar with this simple code.

January 2020
Sun Mon Tue Wed Thu Fri Sat
      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  

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

January
February
March
April
May
June
July
August
September
October
November
December

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 a meeting happens on the first Tuesday of every month, you could use this Python script to determine the date for each meeting.

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 differences in dates as well as for date manipulations in Python. Let’s see a few examples.

Create a simple timedelta and print it

365 days, 3:01:00

Print out today’s date

Today is: 2019-12-17 14:12:26.606124

Print today’s date one year from now

One year from now it will be: 2020-12-16 14:12:26.606124

Create a timedelta that uses more than one argument

In a week and 3 days it will be: 2019-12-27 14:12:26.606124

Calculate the date 1 week ago, formatted as a string

Use a timedelta to calculate the number of 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 some examples of how to read and write files in Python.

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

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.

Sure enough, if we look in the directory where the Python script ran, there is a new mytextfile.txt file. We can open it up and see the contents.
python file write example beginner

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 out the contents to the screen. Here is the updated file.
python read and readline

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

We can run the Python script in Pycharm, and the results are indeed what we expect in the debug output.
pycharm read file to output

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

The os module

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

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

nt (windows)
posix (linux)

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

Item exists: True
Item is a file: True
Item is a directory: False

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

Item's path: C:\python\pythonforbeginners\mytextfile.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

Tue Dec 17 14:52:35 2019
It has been 0:20:33.005550 since the file was modified

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

Get the path to a file in the current directory

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

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

Rename the original file

Put directory contents into a ZIP archive


Web Scraping, JSON, and XML

The final topics we’ll look at in this introduction to Python tutorial focuses 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 take a look at a few simple examples.

Make A Request To A Web Server

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.

On each run of the script, we see 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 in that XML document and parse the results. To do that, we can use a script like this.

#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.

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’re going to need more resources to learn as much as you can! Check out some great ones listed below.


Python Basics For Beginners Summary

If you make it all the way 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, basic 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 for digging deeper into Python.