Python

Syntax

Essentially, syntax in programming refers to the grammatical rules for a specific programming language. Different programming languages use different syntaxes. Python is known as one of the simpler ones to use. As computers cannot make inferences, any code that is not written correctly will result in some type of error. While there are many types of errors, syntax errors are very common. Each section below will explore the syntax for that section. Python is case-sensitive, so capitalization matters, as does the placement of other characters in the code. Get ready to put your detective skills to work!

Comments

Comments can be used to explain code. They make code more readable. They can even be used to temporarily block code from being run when testing a program or debugging. Python starts comments with an octothorpe (#). You may hear it referred to more commonly as a hashtag. Python will ignore lines that begin with an octothorpe.

In Python, there is no separate syntax for a multiline comment. Most other programming languages include this. In Python, an octothorpe is added to each line in the multiline comment. There is an unintentional way to do this, though, without using the octothorpe on every line. That is to use the syntax for a multiline string (triple quotes).

Variables

To begin, think of a variable as a container. You can put different things in it, but the container still looks the same. You may have used variables in math class for equations like 5 = x – 3, where you must solve for x. In programming, variables simply store a value. This value may be a number or text. It can even be a collection of values.

Other popular languages, like Java and C++, require you to specify what type of variable you are going to create, which is referred to as declaring your variable. Python does not require this and will ‘throw’ an error if you try. Python will decide what type it is based on what is in it.

Python does have syntax rules that must be followed when naming variables:

  • A variable name must start with a letter or the underscore character

  • A variable name cannot start with a number

  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

  • Variable names are case-sensitive (age, Age, and AGE are three different variables)

It is common practice to use snake-case to name Python variables. There are a variety of different ‘cases’, and again, languages like Java and C++ use a different case, camelCase. This is merely an industry standard and will not impact the functionality of the program. Snake-case is all lowercase, with underscores (_) in place of spaces. See the examples on the next page.

Camel Case

Each word, except the first, starts with a capital letter:

Pascal Case

Each word starts with a capital letter:

Snake Case

Each word is separated by an underscore character:

Keywords

Python includes 35 keywords (Python 3.10.6) that cannot be used as variable names. The number of keywords can vary depending on the version of Python.

Functions

A function is a block of code that only runs when called. Data known as parameters can be passed into a function. Functions can return data as a result.

Built-in Functions

Python has many built-in functions that are used frequently in code. It would take too much space to list them all here, so ones you are more likely to use will be examined.

Custom Functions

While there are plenty of built-in functions, it is often helpful to create your own to make tasks easier. Below are some of the basics to help you create your own functions. They are frequently used to perform tasks that need to be performed repeatedly. This eliminates the need for writing the same code multiple times.

Creating a Function

In Python, a function is defined using the def keyword:

Calling a Function

When you want to use your function, you use a process known as calling. This is simply a specific syntax used to access your function. One important thing to point out is functions should be added before the main code in your program. Programming languages start at the top of the code and work through it in order. If you call a function before you have defined it, you will get an error message. To call a function, use the function name followed by parentheses.

Arguments

Sometimes you want to send information into the function so it can be used. To do this, we pass arguments into the function. You can add as many arguments as you wish, just separate them with a comma. In the example below, the argument x is sent to the function. The function will print the value produced by multiplying x times three.

Parameters

Arguments and parameters can be used interchangeably but technically, a parameter is the variable listed inside the parentheses in the function definition and an argument is the value sent to the function when it is called. So, in the example above, the parameter would be x and the arguments would be 3 and 12.

Strings

A string is a value that is treated as normal text. It can contain letters, numbers, or special characters, it does not matter. A string cannot be used for calculations. Strings can be used with some arithmetic operators, which will be covered later. Strings must be surrounded by either single or double quotation marks. ’hello’ is the same as ”hello”. Strings can be shown using the print() function.

Multiline Strings

There are also multiline strings. They use three quotes. Again, it can be single or double quotes.

Program output:

String Format

The format() method can be extremely useful when printing strings containing variables. You will see in the Casting section that strings and numbers cannot be combined without first casting any numbers to strings. The format() method can be used to bypass this. When this method is used, information to be added will be replaced in the string with a set of curly braces {} as placeholders.

Program output:

This can also be used with multiple placeholders. There are a few ways to do this, but we will examine one. Other options can be found online. One particularly good source is W3Schools if you are interested in learning more. In the example below, the variables are listed in their desired order in the format function.

Program output:

Escape Character

An escape character \ is used to insert characters that would be considered illegal, in other words, that would otherwise cause errors. A simple example would be trying to use quotes inside of a string that already has quotes around it because it is a string. Python sees this as one string, some illegal characters, and another string. See the example below.

Python views this as a first string: “John said, “. Then the illegal characters: I would like eggs, please. since the text is not enclosed in quotes. And finally, the final string: “ as he walked into the diner.” The proper way to enter this can be seen below, using the escape character before the extra quotation marks. The backslash will not appear in the output.

The output if printed would be as follows:

Other escape characters that you may find useful are shown in the table below. Others exist but are beyond the scope of this document.

String Methods

In Python, a method looks like a function but cannot be called by its name alone. Without getting too deep into technical jargon here, just know that a method must be called by using the variable name along with the method like you saw using the format() method. For example, if we had a variable named ‘text’ and we wanted to use a method with it, we would call the method using the following syntax: text.method() Where ‘method’ is replaced with the name of the desired method. Some examples that you may find useful can be found below. Again, there are others, but they are beyond the scope of this document.

Numbers

Python recognizes three types of numbers: integers, floating point numbers, and complex numbers. It comes as no surprise that numbers are used frequently in programming. They may be used to perform calculations, in lists, as well as many other reasons. Below, integers and floating-point values will be examined. At this level, we will skip complex numbers, but these would be numbers involving imaginary numbers, like i in calculus, which represents the square root of -1 (√-1).

Int

An int, or integer, is a whole number. It can be negative or positive and can have unlimited length.

Program output:

Float

An float, or floating point number, is a number containing one or more decimal places. It can be positive or negative.

Program output:

Casting

When programming in Python, you will often find reasons you would want to change a variable’s type. This is called casting. A few examples include converting user input to numbers so calculations can be performed or changing numbers to strings so a numeric value may be concatenated with a string value. Concatenation is the process of chaining different values together, like a greeting with a name, where the name is a variable.

Strings to Numbers

To change a string to a number, we use either the int() function or the float() function – remembering that we are ignoring complex numbers at this point. See the example below.

Program output:

Numbers to Strings

To change a number into a string, we use the str() function. An example of where this is helpful can be seen below. If you try the same code without casting ‘age’ to a string, you will receive an error message. You can, however, use string format to accomplish this task without the need for casting.

Program output:

Booleans

A Boolean is a logical data type that represents either True or False. There are often cases in programming when it is helpful to find out if an expression is true or false. A common example would be checking a password the user enters. If it is correct or True, the information or program can be accessed. If it is wrong or False, the user will not gain access.

A statement’s Boolean value can be checked using the bool() function. If the value is empty, 0, None, or False, the function will return False. If the value is not empty or one of the values mentioned, it will return True. It is important to note when checking if a value is true or false, you must capitalize the first letter, or an error will be thrown.

Program output:

Operators

Operators are used in performing operations on variables and values. There are a variety of types of operators, including arithmetic, assignment, comparison, logical, identity, membership, and bitwise. We will look at many of these, but not all of them.

Arithmetic Operators

Arithmetic operators are used with numeric values to perform mathematical operations. The example below shows addition. Below that is a table with all the arithmetic operators and their functions. To note, Python automatically follows the order of operations.

Program output:

Assignment Operators

Assignment operators are used for assigning values to variables. Bitwise operators are left out of the table below as they are beyond the scope of this document.

Comparison Operators

Comparison operators are used to compare two values. They will result in either being True or False.

Logical Operators

Logical operators are used to combine conditional statements. They will result in either being True or False.

Storing Collections of Data

Python has four built-in data types used to store collections of data: lists, tuples, sets, and dictionaries. They are similar to one another, but each has unique qualities and usage.

Lists

Lists are ordered, changeable, and allow duplicate values. They are created using square brackets []. Items in a list are indexed starting at zero, so the first item has an index of [0], the second item has an index of [1], and so on.

Creating Lists

A list is created by assigning it to a variable. See the example below.

Accessing List Items

List items can be accessed in several ways, including by index value and by a range of values. See the examples below. The first shows how to access a single item. The second shows how to access a range of items.

Program output:

Program output:

Notice that the range stops before the second index value. If you wanted all the remaining items, use grocery_list[2:5] or you could use grocery_list[2:], which would start at index [2] and go through the rest of the list. Similarly, using grocery_list[:3] would print the first three items in the list:[“apples”, “bananas”, “cherries”], keeping in mind that index [3] is the fourth item in the list.

Changing List Items

Lists can be changed. This process is like accessing items in a list, as, you can change a single item or a range of items. See the examples below.

Adding List Items

Items can be added to a list, or one list can be added to another. In the example below, you see two methods to add an item to a list. The first example adds an item to the end of a list using append(). The second allows you to insert an item at the desired location using insert(). Keep in mind that a method must be attached to a variable.

Removing List Items

Items can be removed from a list, the entire list can be cleared, or the entire list can be deleted. Below are examples of how individual items can be removed from a list using the remove() method or the pop() method. There is an additional method, clear(), and the keyword del(), that will not be explored in this document.

This example removes “apples” from the list:

This example removes “bananas” from the list:

This example removes the last item from the list:

List Iteration

You can iterate or loop through a list using for or while loops. These differ from simply using the print() function because they will list each item on a separate line, whereas printing the list prints all items on a single line inside square brackets with quotes around each item.

For Loop

The example below iterates through the list using a for loop. “Item” can be anything, I chose this because it is a logical name to use. It could be “x” or “thing” or whatever.

Program output:

While Loop

The example below iterates through the list using a while loop. To use a while loop, you will need to create a counter and use the len() function, so the program knows how many items to iterate through. This is preferred over adding a number, in case the length of the list is changed. Also, at the end of the loop, the counter must be incremented by 1.

Program output:

List Methods

This document is not meant to be an exhaustive list of everything that can be done in Python, however, it is quite comprehensive for our purposes. Below are some of the methods that can be used with lists. Additional methods can be accessed online, using resources such as W3Schools.

Tuples

Tuples are similar to lists in they are ordered and allow duplicate values, however, they are unchangeable, or immutable as it is called. They are created using parentheses (). Items in a tuple are indexed starting at zero, so the first item has an index of [0], the second item has an index of [1], and so on.

Tuples can be accessed in the same way as lists. For more information, look at ‘Accessing List Items’. Again, this document is not intended to be comprehensive. It is intended to cover what is likely to be useful in class.

Tuples can be iterated through in the same way as lists, too. Again, for more information, refer to the Lists section of this document.

There are only two built-in methods for tuples, which can be found below.

Sets

Sets are also a collection of data, but they are unordered, unchangeable, and unindexed. However, items can be added and removed. A set is created using curly braces {}. Sets can be iterated though like a list or tuple and can be searched for a specific item. See an example of a set and set methods that may be pertinent below.

Dictionaries

Dictionaries store data in key:value pairs. They are ordered (as of Python version 3.7), changeable, and do not allow duplicates. The key:value pairs make dictionaries distinctly different from lists, tuples, and sets. While we will not do a lot with dictionaries in class, there are a lot of things that can be done with dictionaries. An example of how to make a dictionary can be found below. The first value on each line is the key. The second is the value.

There are a lot of methods that can be used to access, change, and remove items from a dictionary, as well as iterate through dictionaries. Some selected methods are listed below.

Logic

Python supports logical conditions that are used in mathematics (see comparison operators). These conditions can be used in several ways. The most common are in if statements and loops.

If

An if statement is written using the if keyword. One key difference in Python’s if statements compared to other programming languages is there is no need for curly braces. Instead, Python relies on indentation – with a preferred indent of four spaces for any code contained in the statement. The example below tests if two variables are equal.

In this example, a is not equal to b , so nothing will be printed. If the two variables were the same, the argument in the print function would be printed.

Elif

The elif keyword is short for “else if”, which other programming languages use. If the condition in the if statement was not true, the program will try this one. An elif statement will always be proceeded by an if statement. An infinite amount of elif statements can be added afterward. The example below expands on the previous example, by checking if a is greater than b is the two are not equal.

Once again, neither of the conditions in this example are true, so nothing will be printed.

Else

The else keyword catches anything that was not caught by the preceding conditions. Once again expanding on the last two examples, the if and elif conditions were not true. The else statement will print the only other possible option.

And

The and keyword is a logical operator used to combine conditional statements. Notice both possible conditions are complete, often people want to write if a < b and < c, which will throw an error.

Or

The or keyword is a logical operator used to combine conditional statements.

Nested If

A nested if statement is an if statement that contains another if statement. If the first condition is true, then the program will go on to check the second condition.

Program output:

Pass

An if statement cannot be empty. If you are working on your code and not ready to finish your statement yet or had no content in it yet for some reason, you could put in a pass statement to prevent an error from being thrown.

Loops

A loop is a sequence of instructions that is continually repeated until a specified condition has been met. They generally require some sort of counter. Python has two primitive types of loops: for and while.

For Loops

In Python, a for loop is used to iterate over a sequence, such as a dictionary, list, set, string, or tuple. It can easily execute a set of statements, once for each item in a list, set, tuple, and the like. Unlike a while loop, a for loop does not require an indexing variable (counter) to be set beforehand.

The example below shows how to iterate through a list.

Program output:

A for loop can also iterate through a string. See the example below.

Program output:

Break

The break statement allows us to stop a loop before it has iterated through all its items.

Program output:

Continue

The continue statement allows us to stop the current iteration of the loop and continue with the next.

Program output:

Range

The range() function allows us to iterate through a set of code a specified number of times. This function returns a sequence of numbers, starting from 0 and incrementing by 1, and finally ending at the specified number. The starting value can be changed, as can the value the loop increments by. Also, the loop ends at the specified range value, so it is not included in the range (so range(5) would start at 0 and end at 4, not 5).

Program output:

To change the starting point, add that value before the ending value, separated by a comma. For instance, range(2, 5). This would start at 2 and iterate through 4. To change the value the loop increments by the starting value must be added, the ending value, and then the increment value, each separated by a comma. This may look like: range(0, 25, 5). This function would list the following values: 0, 5, 10, 15, 20. If ‘25’ were changed to ‘26’, 25 would be included in the list. The example below starts at 1 and increments by 5, stopping when it reaches 25.

Program output:

Else

The else keyword in a for loop specifies a block of code to be ran once the loop has finished.

Program output:

Pass

A for loop cannot be empty. If for some reason you have a for loop with no content, you can put in a pass statement to prevent an error from being thrown.

While Loops

A while loop executes a set of statements until a condition is no longer true. If written improperly, a while loop will continue forever. In the example below, if you forget to increment i, you will be stuck in a forever loop. Also, the counter variable, i, must be set or initialized before the loop.

Break

The break statement allows us to stop a loop even when the condition is still true.

Program output:

Continue

The continue statement allows us to stop the current iteration of the loop and continue with the next. In the example below, while the counter (i) is less than 8, it will increment the number first, then check if the value is 4 and if not, it will print the value. As a result, there is no 4 in the output.

Program output:

Else

The else keyword in a while loop specifies a block of code to be run once the condition is no longer true. In the example below, the program will print i starting at 1 and continuing through 5. Once i is greater than 5, it will print, i is greater than 5.

Program output:

Modules & Libraries

At our level, the intricacies between modules and libraries are not important. To keep things simple, let us just say they are collections of code that can be easily added to a Python program. Some that we may use in class are described below. These modules and libraries can be imported into our code using the import keyword followed by the module or library you wish to import. They contain extra code that can be used to extend the capabilities of the programming language.

Random

The random module contains a set of methods that can be accessed by importing the random module into a Python program. The module adds methods that perform a variety of tasks that require random values. These include seeding, random numbers, shuffling, sampling, as well as other methods. The example below shows how to import the module and an example of how it could be used. This example would choose a random integer from 1 to 6 (these two values are included and could be chosen). To use the methods in the random module, you must use the syntax: random.method_name(), where ‘method_name’ is the actual name of a method.

Program output:

Turtle

Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzeig, Seymour Papert, and Cynthia Solomon in 1967. The turtle module contains a set of methods that can be accessed by importing the turtle module into a Python program. The module adds methods that perform a variety of drawing tasks. These include drawing lines, changing colors, filling shapes, and writing text. The example below shows how to import the module and an example of how it could be used. This example names the turtle sam, sets sam’s speed, draws a navy-blue square, and writes some text. Many methods in the turtle module use the turtle’s name. In this case, sam.method_name(), where ‘method_name’ is the actual name of a method.

Program output:

Math

The math module contains a set of methods and constants that can be accessed by importing the math module into a Python program. The module adds methods that perform a wide range of mathematical tasks. These include everything from Pi and powers to logarithms, sines, and cosines. The example below shows how to import the module and an example of how it could be used. To use the methods in the math module, you must use the syntax: math.method_name(), where ‘method_name’ is the actual name of a method.

Program output:

Tkinter

Tkinter is a Python module that is used to create Graphical User Interfaces or GUI for short. A GUI allows the user to interact with a program using icons, windows, menus, buttons, etc. It is easier than using a Command Line Interface. The Turtle library is built on Tkinter. Tkinter uses widgets, which are elements in a GUI application, such as buttons, labels, menu bars, and the like. The example below shows how to import the module, create a screen, create a label, create a button, and create an entry field. Comments were left in for a bit more explanation.

Program output: