\[ \begin{align}\begin{aligned}\newcommand\blank{~\underline{\hspace{1.2cm}}~}\\% Bold symbols (vectors) \newcommand\bs[1]{\mathbf{#1}}\\% Poor man's siunitx \newcommand\unit[1]{\mathrm{#1}} \newcommand\num[1]{#1} \newcommand\qty[2]{#1~\unit{#2}}\\\newcommand\per{/} \newcommand\squared{{}^2} \newcommand\cubed{{}^3} % % Scale \newcommand\milli{\unit{m}} \newcommand\centi{\unit{c}} \newcommand\kilo{\unit{k}} \newcommand\mega{\unit{M}} % % Percent \newcommand\percent{\unit{\%}} % % Angle \newcommand\radian{\unit{rad}} \newcommand\degree{\unit{{}^\circ}} % % Time \newcommand\second{\unit{s}} \newcommand\s{\second} \newcommand\minute{\unit{min}} \newcommand\hour{\unit{h}} % % Distance \newcommand\meter{\unit{m}} \newcommand\m{\meter} \newcommand\inch{\unit{in}} \newcommand\foot{\unit{ft}} % % Force \newcommand\newton{\unit{N}} \newcommand\kip{\unit{kip}} % kilopound in "freedom" units - edit made by Sri % % Mass \newcommand\gram{\unit{g}} \newcommand\g{\gram} \newcommand\kilogram{\unit{kg}} \newcommand\kg{\kilogram} \newcommand\grain{\unit{grain}} \newcommand\ounce{\unit{oz}} % % Temperature \newcommand\kelvin{\unit{K}} \newcommand\K{\kelvin} \newcommand\celsius{\unit{{}^\circ C}} \newcommand\C{\celsius} \newcommand\fahrenheit{\unit{{}^\circ F}} \newcommand\F{\fahrenheit} % % Area \newcommand\sqft{\unit{sq\,\foot}} % square foot % % Volume \newcommand\liter{\unit{L}} \newcommand\gallon{\unit{gal}} % % Frequency \newcommand\hertz{\unit{Hz}} \newcommand\rpm{\unit{rpm}} % % Voltage \newcommand\volt{\unit{V}} \newcommand\V{\volt} \newcommand\millivolt{\milli\volt} \newcommand\mV{\milli\volt} \newcommand\kilovolt{\kilo\volt} \newcommand\kV{\kilo\volt} % % Current \newcommand\ampere{\unit{A}} \newcommand\A{\ampere} \newcommand\milliampereA{\milli\ampere} \newcommand\mA{\milli\ampere} \newcommand\kiloampereA{\kilo\ampere} \newcommand\kA{\kilo\ampere} % % Resistance \newcommand\ohm{\Omega} \newcommand\milliohm{\milli\ohm} \newcommand\kiloohm{\kilo\ohm} % correct SI spelling \newcommand\kilohm{\kilo\ohm} % "American" spelling used in siunitx \newcommand\megaohm{\mega\ohm} % correct SI spelling \newcommand\megohm{\mega\ohm} % "American" spelling used in siunitx % % Inductance \newcommand\henry{\unit{H}} \newcommand\H{\henry} \newcommand\millihenry{\milli\henry} \newcommand\mH{\milli\henry} % % Power \newcommand\watt{\unit{W}} \newcommand\W{\watt} \newcommand\milliwatt{\milli\watt} \newcommand\mW{\milli\watt} \newcommand\kilowatt{\kilo\watt} \newcommand\kW{\kilo\watt} % % Energy \newcommand\joule{\unit{J}} \newcommand\J{\joule} % % Composite units % % Torque \newcommand\ozin{\unit{\ounce}\,\unit{in}} \newcommand\newtonmeter{\unit{\newton\,\meter}} % % Pressure \newcommand\psf{\unit{psf}} % pounds per square foot \newcommand\pcf{\unit{pcf}} % pounds per cubic foot \newcommand\pascal{\unit{Pa}} \newcommand\Pa{\pascal} \newcommand\ksi{\unit{ksi}} % kilopound per square inch \newcommand\bar{\unit{bar}} \end{aligned}\end{align} \]

Oct 24, 2024 | 1555 words | 16 min read

5.1.1. Materials#

Here is the link to the Python Official Documentation

HELLO WORLD#

00_hello_world.py

OPERATORS#

01_operators.py

Math Operators#

used to perform basic operations

  • Addition +: returns the sum of two numbers

  • Subtraction -: returns the difference of two numbers

  • Multiplication *: returns the product of two numbers

  • Division /: returns the quotient of two numbers

  • Modulus %: returns the remainder of the division

  • Exponentiation **: raises the first number to the power of the second number

  • Floor division //: returns the integer part of the division result

Operands - Operands are the values that the operator acts on.

Order of operations is determined by precedence:

  1. Parentheses ()

  2. Exponents **

  3. Multiplication and Division *, /, %, //

  4. Addition and Subtraction +, -

If two operators have the same precedence, they are applied from left to right

Boolean Operators#

used to combine conditional statements

  • not : returns True if the statement is false and vice versa

  • and : returns True if both statements are true

  • or : returns True if one of the statements is true

Comparison Operators#

used to compare two values, returns a boolean value.

  • greater than > : returns True if the left operand is greater than the right operand

  • less than < : returns True if the left operand is less than the right operand

  • greater than or equal to >= : returns True if the left operand is greater than or equal to the right operand

  • less than or equal to <= : returns True if the left operand is less than or equal to the right operand

  • equal to == : returns True if the operands are equal

  • not equal to != : returns True if the operands are not equal

Assignment Operators#

= is used to assign values to variables.

See Variables

Bitwise Operators#

used to perform bitwise operations

  • & : Bitwise AND

  • | : Bitwise OR

  • ^ : Bitwise XOR

  • ~ : Bitwise NOT

  • << : Bitwise left shift

  • >> : Bitwise right shift

Identity Operators#

used to compare the memory location of two objects

  • is : returns True if both variables are the same object

  • is not : returns True if both variables are not the same object

Membership Operators#

used to test if a sequence is present in an object

  • in : returns True if a sequence is present in the object

  • not in : returns True if a sequence is not present in the object

VARIABLES#

02_variables.py

A variable is a name that refers to a value. Variables are used to store data that can be referenced and manipulated in a program.

Assignment operator#

= is used to assign a value to a variable

  • The value on the right side of the assignment operator is assigned to the variable on the left side.

  • Variable names can contain letters, numbers, and underscores.

  • They must start with a letter or an underscore.

  • Variable names are case-sensitive.

  • Variables can be reassigned to new values at any time.

  • Variables can point to any data type.

Expressions are anything that can be evaluated to a value. For example: 1+2

Literals are fixed values that are written directly into the code. For example: 1 or "Hello World!"

Assignment statements#

used to create variables and assign values to them.

Syntax: variable = expression or literal

a = 1+2
b = "Hello World!"

Compound Assignment Operators#

  • a+=3 equates to a = a + 3 (Add and assign)

  • a-=3 equates to a = a - 3 (Subtract and assign)

  • a*=3 equates to a = a * 3 (Multiply and assign)

  • a/=3 equates to a = a / 3 (Divide and assign)

  • a%=3 equates to a = a % 3 (Modulus and assign)

  • a**=3 equates to a = a ** 3 (Exponentiate and assign)

  • a//=3 equates to a = a // 3 (Floor divide and assign)

Python does not have increment ++ and decrement -- operators.

DATA TYPES#

03_data_types.py

You can use the type() function to get the datatype of a variable or a literal.

Basic Data Types#

  • Integer int - whole numbers

  • Float float - numbers with decimal points

  • String str - sequence of characters

  • Boolean bool - True or False

  • None NoneType - represents the absence of a value

Sequence Data Types#

  • List - comma separated values enclosed in square brackets, [1, 2, 3], list()

  • Tuple - comma separated values enclosed in parentheses, (1, 2, 3), tuple()

  • Set - comma separated values enclosed in curly braces, {1, 2, 3}, set()

  • Dictionary - key-value pairs enclosed in curly braces, {"name": "John", "age": 20}, dict()

  • Range - range() returns a sequence of numbers

    Syntax: range(start, stop, step)

    • start - optional, an integer number specifying at which position to start.

    • stop - required, an integer number specifying at which position to stop (not included)

    • step - optional, an integer number specifying the incrementation.

    • Default values: start=0, stop - no default values as it is required, step=1

Basic indexing and slicing#

  • Indexing - accessing a single element of a sequence

  • Slicing - accessing multiple elements of a sequence

  • Indexing starts from 0

  • Negative indexing starts from -1 (last element)

  • Slicing syntax: [start:stop:step]

    • start - starting index

    • stop - stopping index

    • step - incrementation

    • Default values: start=0, stop=len(sequence), step=1

Table 5.2 Sequence Differences#

Sequence

Mutability

Order

Unique Elements

Editablity

List

Mutable

Ordered

allows duplicates

replaced or changed or added or removed

Tuple

Immutable

Ordered

allows duplicates

cannot be replaced or changed or added or removed

Set

Mutable

Unordered

no duplicates

cannot be replaced or changed, only added or removed

Dictionary

Mutable

Unordered

no duplicate keys

replaced or changed or added or removed

Mixed Type Operations#

  • Adding two integers results in an integer: int + int = int

  • Adding an integer and a float results in a float: int + float = float

  • Adding a string and a number, results in an error: str + int = TypeError

  • Adding two strings concatenates them and results in a string: str + str = str

  • Multiplying a string by an integer repeats the string and results in a string: str * int = str

  • Division always results in a float: int / int = float

  • Floor division always results in an integer: float // float = int

Data Type Conversion#

  • int() - converts a value to an integer

  • float() - converts a value to a float

  • str() - converts a value to a string

  • bool() - converts a value to a boolean

  • list() - converts a value to a list

  • tuple() - converts a value to a tuple

  • dict() - converts a value to a dictionary

  • set() - converts a value to a set

Strings#

Single quotes ', double quotes ", or triple quotes ''' or """ can be used to define strings You can add backward-slash \ before the quote to escape it.

Example:

print('Pete')                 # Output: Pete
print("Pete's hammer")        # Output: Pete's
print("""Pete's "hammer" """) # Output: Pete's "hammer"

print('Pete\'s "hammer"')     # Output: Pete's "hammer"

INPUT FUNCTION - input()#

04_input_function.py

Example:

user_name = input("Enter your name: ")

Converting user input

age = input("Enter your age: ")
age = int(age)

Nested functions in Python

age = int(input("Enter your age: "))
age = float(input("Enter your age: "))

For the purpose of this course, you will not worry about validating and sanitizing user input. If you are interested in learning more about it, you can check out exception handling in Python.

OUTPUTS#

05_outputs.py

format() function#

format() function - accepts a number and a format specifier and returns as a string

Syntax: format(number, format_specifier)

format_specifier syntax - "[width][grouping_option][.precision][type]"

  • width - minimum number of characters to be printed (default is 0)

  • grouping_option - comma (,) to use comma as a thousand separator

  • precision - number of decimal places to be printed

  • type - d for integer, f for float, s for string

Examples:

format(123.4567, ".2f")       # Output is "123.46"
format(1234.56789, "10,.2f")  # Output is "  1,234.57"
format(1234, "10_d")          # Output is "     1_234"
format(0.2, "0.0%")           # Output is "20.0%"
format(12345.6789, "e")       # Output is "1.234568e+04" which is 1.234568 x 10^4
format(12345.6789, "E")       # Output is "1.234568E+04" which is 1.234568 x 10^4
format(12345.6789, ".2e")     # Output is "1.23e+04" which is 1.23 x 10^4
format(0.00000012345, ".4E")  # Output is "1.2345E-07" which is 1.2345 x 10^-7

Formatted print statements (f-print)#

Here is the Python Official Documentation link to formatted string literals

Syntax: f"string {variable}"

Example:

item = "apple"
cost = 1234.56789
f"{item} costs ${cost}"             # Output is "apple costs $1234.56789"
print(f"{item} costs ${cost:,.2f}") # Output is "apple costs $1,234.57"

MATH MODULE#

06_math_module.py

Syntax:

import math

math.<function name>()
  • Python has a built-in module called math that contains a collection of mathematical functions

  • To use the math module, you must import it using the import keyword

  • To access functions in the math module, you must use the module name followed by a period (.) and then the function name

Examples:

math.sqrt()       # square root of a number
math.ceil()       # ceiling of a number (round up to the next integer)
math.floor()      # floor of a number (round down to the previous integer)
math.factorial()  # factorial of a number

More details on the math module can be found in the official documentation.

IMPORT METHODS#

07_import_methods.py

There are several ways to import a module or a function from a module

import a module#

import math

print(math.sqrt(25))  # Output: 5.0

import a module using an alias#

import math as m

print(20 * m.cos(m.pi))  # Output: -20.0 , (cos(pi) = -1)

import specific functions from a module#

from math import cos, pi

print(20 * cos(pi))  # Output: -20.0

import specific functions from a module using an alias#

from math import sqrt as s

print(s(25))  # Output: 5.0

import all functions from a module using the * operator#

from math import *

print(sqrt(25))  # Output: 5.0

Warning

To import all functions (using the * method) from a module is NOT recommended.

This is because it can overwrite functions that already exist in the program and/or It can be difficult to determine where a function came from.

RANDOM MODULE#

08_random_module.py

The random module provides a number of functions that can be used to generate random numbers. Random numbers are used in various applications such as games, simulations, cryptography, and statistical analysis.

True Random Number Generator (TRNG)

  • Generates random numbers based on physical processes such as atmospheric noise, radioactive decay, or thermal noise.

  • The random numbers generated by a TRNG are truly random.

  • They are completely unpredictable and uniformly distributed.

  • They are slow and expensive to implement.

Pseudo-Random Number Generator (PRNG)

  • Generates random numbers using a deterministic algorithm.

  • The random numbers generated by a PRNG are not truly random.

  • They are predictable and reproducible.

  • They can be initialized with a seed value, which determines the sequence of random numbers generated.

  • They are fast and efficient.

Some commonly used functions in the random module are:

random()    # generates a random float number between 0 and 1.
randint()   # generates a random integer number between two specified integers.
uniform()   # generates a random float number within a specified range.
seed()      # initializes the random number generator.
randrange() # generates a random integer number within a specified range with a step.
            # Syntax: random.randrange(start, stop, step)
choice()    # returns a random element from a sequence.
choices()   # returns a random sample of elements from a sequence with replacement.
sample()    # returns a random sample of elements from a sequence without replacement.
shuffle()   # shuffles the elements of a sequence.

Example:

# import the random module
import random

# generate a random float number between 0 and 1
print(random.random())  # Output: 0.6394267984578837

# generate a random integer number between 1 and 10
print(random.randint(1, 10))  # Output: 7

# generate a random float number between 1 and 10
print(random.uniform(1, 10))  # Output: 5.123456789012345

# initialize the random number generator with a seed value
random.seed(10)

# generate a random integer number between 1 and 10
print(random.randint(1, 10))  # Output: 10

# generate a random integer number between 1 and 10 with a step of 2
print(random.randrange(1, 10, 2))  # Output: 7

# generate a random element from a sequence
print(random.choice([1, 2, 3, 4, 5]))  # Output: 3

# generate a random sample of elements from a sequence with replacement
print(random.choices([1, 2, 3, 4, 5], k=3))  # Output: [3, 1, 5]

# generate a random sample of elements from a sequence without replacement
print(random.sample([1, 2, 3, 4, 5], k=3))  # Output: [3, 1, 5]

# shuffle the elements of a sequence
arr = [1, 2, 3, 4, 5]
random.shuffle(arr)
print(arr)  # Output: [3, 1, 5, 2, 4]

Help function#

To access the help function, follow these steps:

  1. Enter the python interpreter by typing python3 in the terminal.

  2. Type help() in the python interpreter.

  3. For example, type help(random) to get help on the random module. This will display the help information for the random module.

  4. To quit the help function, type quit().

  5. To quit the python interpreter, type exit() or quit().

PYTHON LIBRARIES#

09_python_libraries.py

Python libraries are collections of functions and methods that allow you to perform many actions without writing your code.

Python modules are files that contain Python code. They can define functions, classes, and variables.

Python has a vast collection of libraries and modules that can be used to perform various tasks.

Installing a library#

  • To install a library, you can use the pip command (Python package manager)

  • For example, to install the numpy library, you can use the following command in the terminal:

    python3 -m pip install numpy
    
  • To install pip, you can use the following command in the terminal:

      python3 -m pip --version              # Check if pip is installed
      python3 -m ensurepip --user           # Install pip
      python3 -m pip install --upgrade pip  # Upgrade pip
    
    

math#

Provides mathematical functions.

# import the math module
import math

print(math.sqrt(16))  # Output: 4.0

numpy#

Provides support for large, multidimensional arrays and matrices.

python3 -m pip install numpy
# import the numpy module
import numpy as np

# Create a simple array
arr = np.array([1, 2, 3, 4, 5])

# Multiply each element by 2
result = arr * 2

# Print the result
print(result)  # Output: [ 2  4  6  8 10]

matplotlib#

Provides plotting functions.

# import the matplotlib module
import matplotlib.pyplot as plt

# Create a simple plot
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]

plt.plot(x, y)
plt.title("Simple Plot")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()

pandas#

Provides data structures and data analysis tools.

import pandas as pd

# Create a simple DataFrame
data = {
    "Name": ["John", "Anna", "Peter", "Linda"],
    "Age": [25, 36, 29, 42],
    "City": ["New York", "Paris", "Berlin", "London"],
}

df = pd.DataFrame(data)

# Display the DataFrame
print(
    df
)  # Output:     Name  Age  City 0  John  25  New York 1  Anna  36  Paris 2  Peter  29  Berlin 3  Linda  42  London

# Accessing a specific column
ages = df["Age"]  # Access the 'Age' column
print(ages)  # Output: 0    25, 1    36, 2    29, 3    42, Name: Age, dtype: int64

KEYWORDS#

10_keywords.py

Reserved words#

  • Keywords are reserved words in Python that have special meaning and cannot be used as variable names.

  • Keywords are case-sensitive.

  • Python has 35 keywords.

  • You can get a list of keywords using the keyword module.

  • You can check if a word is a keyword using the iskeyword() function.

  • You can get a list of built-in functions and variables using the builtins module.

  • You can check if a word is a built-in function or variable using the dir() function.

  • You can check if a word is a built-in function or variable using the is identity operator.

Example:

# import the keyword module
import keyword

print(keyword.kwlist)  # List of reserved words
print(keyword.iskeyword("break"))  # Output: True

# import the builtins module
import builtins

print(dir(builtins))  # List of built-in functions and variables

print(ArithmeticError is builtins.ArithmeticError)  # Output: True

ENGR 13300 Python Template#

ENGR133_Python_Template.py