Python

Python Logo.

Python

Python has become one of the most common programming languages. Hopefully, you have taken ICS 110P as this has given you a great foundation for learning Python. 


During this section we will cover:


To continue to improve on your Python skills pythonbasics.org is a great site. 

Variables

Variables are a core component of learning any scripting language. A variable allows developers to store data in memory using a descriptive name and then using it later. Variables can store all types of data from integers, decimal numbers, binary values, dates, time and strings! 


Python is amazing as it allows you to declare a variable and it will automatically choose the correct data type. No special characters are needed to define a variable.


# Variable declaration

my_variable = 281


# Print the value of the variable

print(my_variable)


In this example, my_variable is declared and assigned the value of 281. The print() function is then used to display the value of the variable, which will output 281 to the console. Lines of code that start with # are a comment. This will not impact the code or be printed out. We like to use comments to document the code and provide insights on how it should work. 

Arrays

An array is a data structure that stores items of the same data type. It provides a method to organize and access multiple values using a single variable. 


# Array declaration

my_array = [1, 2, 3, 4, 5]


# Print the array

print(my_array)


In this example, my_array is declared as a list containing the elements 1, 2, 3, 4, and 5. The print() function is then used to display the array, which will output [1, 2, 3, 4, 5] to the console

You can access individual elements of the array by using the index. For example, to access the second element of the array, you can use my_array[1] since indexing starts from 0.

Python Comparison Operators

When writing code you might need to determine if two variables are the same or if a value is greater than or less than another value. We can do this using comparison operators.  Python has 6 comparison operators and they either return True or False based on the result of the comparison.

See examples below:


1. Equal to (`==`): Checks if two values are equal.

x = 5

y = 7

print(x == y)  # False

2. Not equal to (`!=`): Checks if two values are not equal.

x = 5

y = 7

print(x != y)  # True

3. Greater than (`>`): Checks if the left operand is greater than the right operand.

x = 5

y = 7

print(x > y)  # False

4. Less than (`<`): Checks if the left operand is less than the right operand.

x = 5

y = 7

print(x < y)  # True

5. Greater than or equal to (`>=`): Checks if the left operand is greater than or equal to the right operand.

x = 5

y = 7

print(x >= y)  # False

6. Less than or equal to (`<=`): Checks if the left operand is less than or equal to the right operand.

x = 5

y = 7

print(x <= y)  # True

String Operators

Python has a lot of String operations! To understand and even test out these operations use the w3schools Python String Method site.


A common String operation is concatenation. This combines two strings into one. See the example below:


first_name = "Pete"

last_name = "Gross"


full_name = first_name + " " + last_name

print(full_name)  # Output: Pete Gross


Conditionals

A conditional statement allows you to perform different actions and control the flow of code based on a condition. These are very simple to write, but can be very powerful when used within code.  Below is a simple example showing a sime if-else conditional statement.  


# Example of a Python conditional statement

x = 10


if x > 5:

    print("x is greater than 5")

else:

    print("x is less than or equal to 5")

This sets the variable x to a value of 10. The 'if' statement checks to see if x is greater than 5. If this is true (which it is) it executes the indented code block (the print statement). If the condition is false it would execute the indented code block under the else statement. 


Python also provides if-elif-else conditional statements. 

# Example of a Python conditional statement with if-elif-else.


x = 10


if x > 10:

    print("x is greater than 10")

elif x < 10:

    print("x is less than 10")

else:

    print("x is equal to 10")


This is the same idea as the previous example, except we are also checking to see if the value is less than 10 (this is the elif statement). You can use multiple elif statements in a single conditional block.


Basic Looping

The most common loops you will find in Python are a for and a while loop. 


for item in sequence:

    # Code block to be executed

while condition:

    # Code block to be executed

Error Handling

At times our code might throw an error and we might wish to handle this graceful instead of just having our program crash. In python this is a try-except block.  Just imaging if you asked a user for two integer values and then gave you 100 and 0. In your code you then tried to do 100/0. This would throw an error as you cannot divide by 0.  We might wish to handle this cleanly. 


The try block would contain the code that might wish to raise an exception. If an exception occurs the execution of the code is transferred to the except block. 

See an example of the scenario below:


try:

    numerator = int(input("Enter an integer: "))

    denominator = int(input("Enter an integer: "))

    result = numerator / denominator

    print("Result:", result)

except ZeroDivisionError:

    print("Error: Cannot divide by zero")


System Calls

There are two ways to do system calls in Python. 


The first one uses the 'os' module. See the example and explanation of the code below:


import os


# Execute a shell command

os.system('ls -l')


The first line of code imports the os module that allows you to use the os.system() function. This example would execute the ls -l command. This would not provide you with the output. If you wish to get the output you would need to use file redirection to create a file. You would then need to open the file and parse the data from the file.


The second method uses the subprocess module. This method provides more functionality then using the os module. 


import subprocess


# Execute a shell command

result = subprocess.run(['ls', '-l'], capture_output=True, text=True)


# Print the output

print(result.stdout)


The first line of code imports the subprocess module and this allows you to use the subprocess.run() function. This can take several arguments. I have only provide details about the ones used in the above example.


Install Packages

Python provides an easy way to install other Python packages. To do this you would use the pip (python2) or pip3 (python3) command.  


pip install package_name


At times you might find that Python code you downloaded has various Python packages that are required. A majority of the time you can find these listed in a requirements.txt file. You can easily use this file with pip!


pip install -r requirements.txt


It seems that in the near future that pip and pip3 will be gone and you will need to use APT to install Python packages. This blog post provides details about this change.