Python Primer

Python Primer


Python web


Python was invented in the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica in the Netherlands. 

It is an interpreted language, meaning the code is not compiled into a machine run language but read one line at a time for execution. 

Has built in data structure and dynamic typing.

Great for fast rapid development. 

Code is easy to read and easy to learn. 

Extensive module and package library available to python developers provides both power and flexibility.

Runs on all major platforms and operating systems. 


Most popular and widely used programming language in the world.


This is reflected in its name—a tribute to the British comedy group Monty 


Named after the British comedy troupe “Monte Python” known for their absurd and chaotic sketches.


Dead Parrot





Why use Python?

  • Readable and Maintainable Code

  • Multiple Programming Paradigms

  • Compatible with Major Platforms and Systems

  • Robust Standard Library

  • Many Open Source Frameworks and Tools

  • Simplify Complex Software Development

  • Adopt Test Driven Development


Python Download

Welcome to the Python installation manager configuration helper.


********************************************************************************


Windows is not configured to allow paths longer than 260 characters.


Python and some other apps can exceed this limit, but it requires changing a system-wide setting, which may need an administrator to approve, and will require a reboot. Some packages may fail to install without long path support enabled.

Update setting now? [y/N] y

The setting has been successfully updated, and will take effect after the next reboot.


********************************************************************************

The legacy 'py' command is still installed.


This may interfere with launching the new 'py' command, and may be resolved by uninstalling 'Python launcher'.

Open Installed apps now? [y/N] y


********************************************************************************


The global shortcuts directory is not configured.


Configuring this enables commands like python3.15.exe to run from your

terminal, but is not needed for the python or py commands (for example, py

-V:3.15).


We can add the directory (C:\Users\john\AppData\Local\Python\bin) to PATH now, but you will need to restart your terminal to use it. The entry will be removed if you run py uninstall --purge, or else you can remove it manually when uninstalling Python.

Add commands directory to your PATH now? [y/N] y

PATH has been updated, and will take effect after opening a new terminal.


********************************************************************************


You do not have the latest Python runtime.


Install the current latest version of CPython? If not, you can use 'py install

default' later to install.


Install CPython now? [Y/n] y

Python install manager was successfully updated to 26.4.


Please see https://github.com/python/pymanager/releases/tag/26.4 for all changes.


********************************************************************************

The signature for https://www.python.org/ftp/python/index-windows.json was successfully verified.

Installing Python 3.15.0.

Extracting: ...................................................................✅

To see all available commands, run 'py help'

********************************************************************************


********************************************************************************


Configuration checks completed.


To run these checks again, launch Python install manager from your Start menu, or py install --configure from the terminal.


********************************************************************************


Usage:

py <regular Python options> Launch the default runtime with specified options. This is the equivalent of the python command.


py -V:<TAG> Launch runtime identified by <TAG>, which should 

include the company name if not PythonCore. Regular Python options may follow this option.


py -3<VERSION>  Equivalent to -V:PythonCore\3<VERSION>. The version

must begin with the digit 3, platform overrides are permitted, and regular Python options may follow. py -3 is the equivalent of the python3 command.


py exec <any of the above> Equivalent to any of the above launch options, and the requested runtime will be installed if needed.


py help [<CMD>]  Show help for Python installation manager commands


py install <TAG>  Download new Python runtimes, or pass --update to

update existing installs.


py list [<FILTER>]   Show installed Python runtimes, optionally filtering by

<FILTER>.


py uninstall <TAG>   Remove one or more runtimes from your machine. Pass  --cleanup to remove cached and unrecognized files while

preserving recognized runtimes, or --purge to remove all.


Find additional information at https://docs.python.org/using/windows.


View online help? [y/N]


We have 2 ways to execute python code.

First, is directly in the interpreter and the second is in a file.

To execute the interpreter just click on your python application.

print ("Hello, world!")

Python 3.15.0 (tags/v3.15.0:d220409, Oct  9 2026, 11:55:56) [MSC v.1951 64 bit (AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> print ("Hello, world!")

Hello, world!

>>>


The second is via file execution

Need an editor like notepad or notepad++



Type CMD in search window


Created a directory for my python programs.


In notepad input the python commands

Then save the file to the directory


Type the name hw.py 

dir  command will allow you to see if the program is present.

C:\Users\john\python>dir

 Volume in drive C is Windows

 Volume Serial Number is 0EBA-E6F2


 Directory of C:\Users\john\python


10/11/2026  12:58 PM    <DIR>          .

10/11/2026  12:58 PM    <DIR>          ..

10/11/2026  12:58 PM                29 hw.py

               1 File(s)             29 bytes

               2 Dir(s)  167,399,931,904 bytes free


C:\Users\john\python>


Now I can execute the code using the python program.


C:\Users\john\python>python hw.py

Hello, world!


Data Types

Python uses the following data types:

int - Integers (numbers without decimals)

float - Floating point numbers (numbers with decimals)

str - Strings (text and number)

list - Lists (collection of items)

dict - Dictionary (name/value pairs)

bool - Booleans (true or false values)

python program dt.py


Note the type command display the type of the variable

=======================================================

# DATA TYPE Examples

########## INTEGER #######################

my_int = 5

print(type(my_int))

print(my_int)


########### FLOAT ########################

my_float = 20.5

print(type(my_float))

print(my_float)


########## LISTS #################

# collection of items that is ordered, changeable and allows duplicates

my_list = ['a', 'b', 'c']

for l_name in my_list:

    print(l_name)


########## DICTIONARY #################

#collection which is unordered, changeable, indexed no duplicates

my_dict = {"name" : "John", "email" : "john.iacovacci1@gmail.com"}

print (my_dict['name'])

print(type(my_dict))


########### BOOL ###########

# one of two values: True or False.

x = True

#display x:

print(x)

#display the data type of x:

print(type(x))    




=========================================================

Note: Must change to Save as Type to All files when saving

Results

C:\Users\john\python>python dt.py

<class 'int'>

5

<class 'float'>

20.5

a

b

c

John

<class 'dict'>

True

<class 'bool'>


C:\Users\john\python>


Python Arithmetic Operators

python program am.py

=========================================================

#!/usr/bin/python3

### Arithmetic Operators Examples ###

### ADD ###

x = 2 + 3

print('ADD x = 2 + 3')

print(x)

### SUBTRACT ###

print('SUBTRACT x = 3 - 2')

x = 3 - 2

print(x)

### MULTIPLY ###

print('MULTIPLY x = 3 * 2')

x = 3 * 2

print(x)

### DIVISION ###

print('DIVIDE x = 3 / 2')

x = 3 / 2

print(x)

### MODULUS ###

print('MODULUS x = 5 % 2')

x = 5 % 2

print(x)

### EXPONENTIAL ###

print('EXPONENTIAL x = 3**2')

x = 3**2

print(x)



==================================================

Results

C:\Users\john\python>python am.py

ADD x = 2 + 3

5

SUBTRACT x = 3 - 2

1

MULTIPLY x = 3 * 2

6

DIVIDE x = 3 / 2

1.5

MODULUS x = 5 % 2

1

EXPONENTIAL x = 3**2

9


Python Assignment Operators

python program ao.py

===========================================================

### Assignment Operators ###

print('= sign  x = 3')

x = 3

print(x)

print('+= sign  x += 3')

x = 6

x += 3

print(x)

print('-= sign  x-= 3')

x = 6

x -= 3

print(x)

print('*= sign  x*= 3')

x = 6

x *= 3

print(x)

print('/= sign  x/= 3')

x = 6

x /= 3

print(x)


===========================================================

Results


C:\Users\john\python>python ao.py

= sign  x = 3

3

+= sign  x += 3

9

-= sign  x-= 3

3

*= sign  x*= 3

18

/= sign  x/= 3

2.0



Python Comparison Operators

python program co.py

==================================================

print('== sign, x = 3, y = 5,  is x == y')

x = 3

y = 5

print(x == y)

print('!= sign, x = 3, y = 5,  is x != y')

x = 3

y = 5

print(x != y)

print('> sign, x = 3, y = 5,  is x > y')

x = 3

y = 5

print(x > y)

print('< sign, x = 3, y = 5,  is x < y')

x = 3

y = 5

print(x < y)

print('>= sign, x = 3, y = 5,  is x >= y')

x = 3

y = 5

print(x > y)

print('<= sign, x = 3, y = 5,  is x <= y')

x = 3

y = 5

print(x <= y)




==================================================

Results


C:\Users\john\python>python co.py

== sign, x = 3, y = 5,  is x == y

False

!= sign, x = 3, y = 5,  is x != y

True

> sign, x = 3, y = 5,  is x > y

False

< sign, x = 3, y = 5,  is x < y

True

>= sign, x = 3, y = 5,  is x >= y

False

<= sign, x = 3, y = 5,  is x <= y

True



Python Logical Operators

python program lo.py

===========================================================

print('and operator , x = 5, x > 3 and x < 10')

x = 5

print(x > 3 and x < 10)

print('or operator , x = 5, x > 3 or x < 4')

x = 5

print(x > 3 or x < 4)

print('not operator , x = 5, not(x > 3 or x < 10)')

x = 5

print(not(x > 3 and x < 10))

===========================================================

Results

C:\Users\john\python>python lo.py

and operator , x = 5, x > 3 and x < 10

True

or operator , x = 5, x > 3 or x < 4

True

not operator , x = 5, not(x > 3 or x < 10)

False


String format()

The format() method allows you to format a string to fit the needs of the application. 

The use of curly brackets {} in the text acts as a placeholder and allows variables to be placed into the formatted string.


Formatting

python program pf.py

=========================================================

print('This is a String {}'.format('INSERTED'))

price = 49

txt = "The price is {:.2f} dollars"

print(txt.format(price))

quantity = 3

itemno = 567

price = 49

myorder = "I want {} pieces of item number {} for {:.2f} dollars."

print(myorder.format(quantity, itemno, price))


=========================================================

Results

C:\Users\john\python>python pf.py

This is a String INSERTED

The price is 49.00 dollars

I want 3 pieces of item number 567 for 49.00 dollars.

Python Lists

Python Collections (Arrays)

There are four collection data types in the Python programming language:

List is a collection ordered, changeable and allows duplicates


Dictionary is a collection which is unordered, changeable, indexed with no duplicate allowed


python program lt.py

========================================================

print('loop thru list')

my_list = ['y','d','e','a','f']

for lt_name in my_list:

    print (lt_name)

### RANGE ###

print('range starting at position 2 up to but not including position 4')

print(my_list[3:2])

#First item is position 0

### REPLACE ITEM ###

print('replace position 1 with z')

my_list[1] = 'z'

print(my_list)

### LENGTH ###

print('length of list')

print(len(my_list))

### SORT METHOD ###

print('sort the list')

my_list.sort()

print(my_list)

########## DICTIONARY #################

print('dictionary example')

x = {"name" : "John", "email" : "john.iacovacci1@gmail.com"}

print (x['name'])

print(type(x))



======================================================

Results

C:\Users\john\python>python lt.py

loop thru list

y

d

e

a

f

range starting at position 2 up to but not including position 4

[]

replace position 1 with z

['y', 'z', 'e', 'a', 'f']

length of list

5

sort the list

['a', 'e', 'f', 'y', 'z']

dictionary example

John

<class 'dict'>



Python Control Flow

The if statement executes a block of code if the statement is true. An elif statement is tested if the first condition fails.

The for statement, loops executes the code until the condition set is met.


The while statement executes code while a condition is true.


The break statement allows exiting the while loop before condition is met., 


The continue statement, which skips the rest of the current iteration and continues with the next.



python program cf.py

=======================================================


a = 6

b = 5

print('elsif a = 6 and b = 5')

if b > a:

   print("b is greater than a")

elif a > b:

    print("a is greater than b")

### if elif else test ###

a = 5

b = 5

print('else a = 5 and b = 5')

if b > a:

   print("b is greater than a")

elif a > b:

   print("a is greater than b")

else:

       print("a is equal to b")

### FOR NEXT ###

print('for next loop')

my_list = ['a','b','c','d','e']

for it_name in my_list:

    print (it_name)

### looping thru a string ###

print('looping thru string')

for x in "orange":

    print(x)

    print('formatting loop thru string')

    index_count = 0

for letter in 'orange':

  print('At index {} the letter is {}'.format(index_count,letter))

  index_count += 1

### while loops ###

print('while loop')

i = 1

while i < 5:

  print(i)

  i += 1



### while loop break ###

print('while loop break')

i = 1

while i < 5:

  print(i)

  if i == 3:

    break


=======================================================

Results


C:\Users\john\python>python cf.py

if a = 3 and b = 5

b is greater than a

elsif a = 6 and b = 5

a is greater than b

else a = 5 and b = 5

a is equal to b

for next loop

a

b

c

d

e

looping thru string

o

formatting loop thru string

r

formatting loop thru string

a

formatting loop thru string

n

formatting loop thru string

g

formatting loop thru string

e

formatting loop thru string

At index 0 the letter is o

At index 1 the letter is r

At index 2 the letter is a

At index 3 the letter is n

At index 4 the letter is g

At index 5 the letter is e

while loop

1

2

3

4

while loop break

1

2

3


Python User Input

python program ui.py


=====================================================

my_name = input("What is your name?:")

print("My name is: " + my_name)





=====================================================

Results

C:\Users\john\python>python ui.py

What is your name?:John Iacovacci

My name is: John Iacovacci





Python Functions


A function is a block of code that runs when called.

Pass data to function using parameters/

Functions can return results.

starts with def

In Python a function is defined using the def keyword:

def name_of_function(name):

      Block of code


The return statement, used to return a value from a function


python program functions.py

=========================================================

def my_function():

  print("Hello World")

my_function()

### FUNCTION WITH AN ARGUMENT ###

def name_function(name):

    print("My name is " +name)

name_function("John Iacovacci")


### RETURN VALUE FROM FUNCTION ###

def my_function(x,y):

  return  x * y

print(my_function(3,5))



=================================================

Results

C:\Users\john\python>python functions.py

Hello World

My name is John Iacovacci

15



Python Classes and Objects


Python is a multi-paradigm programming language that supports  object-oriented, functional, procedural, and imperative language concepts.


Python uses classes to allow you to group attributes and methods.


The following examples focus on Python’s Object-Oriented concepts.

The keyword class is used to create an object class.


Developers create objects and those objects have methods and attributes.


Methods are like functions and use information about the object, as well as the object itself to return results or modify the object.



python program dog_class.py

====================================================


### Class Examples Methods ###



class Dog():

    species = "mammal"

    def __init__(self,breed,name):

        #assign using self.attribute_name

        self.breed = breed

        self.name = name



    #methods ...actions

    def bark(self):

        print("BARK!")



my_dog = Dog(breed='mixed',name="Bear Bear")

print(type(my_dog))

print(my_dog.breed)

print(my_dog.name)

my_dog.bark()


====================================================

Results

C:\Users\john\python>python dog_class.py

<class '__main__.Dog'>

mixed

Bear Bear

BARK!




class Dog() - Defining a new object type called Dog. 

Attributes (The Data) 

species = "mammal": Class Object Attribute same for every single instance of a dog.

def __init__(self, breed, name) -  Constructor runs when a new dog is created.

self: Specific instance of the dog you are creating. 

self.breed & self.name: These are Instance Attributes. 

def bark(self) - Method functions actions an object can perform.

Creates an instance of the Dog class.

print(type(my_dog))

Confirms that my_dog is an object of the __main__.Dog class.

print(my_dog.breed)

Accesses the attribute and prints "mixed"

my_dog.bark()

Executes the action, printing "BARK!"



Python was designed to be highly extensible via modules. 

This compact modularity has made it particularly popular as a means of adding programmable interfaces to existing applications. 


PIP

pip is a package-management system written in Python and is used to install and manage software packages. The Python Software Foundation recommends using pip for installing Python applications and its dependencies during deployment.

Install numpy:

$ pip3 install numpy

Note: It may already be installed by default

NumPy

NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.

Python lists are excellent, general-purpose containers. They can be “heterogeneous”, meaning that they can contain elements of a variety of types, and they are quite fast when used to perform individual operations on a handful of elements.

NumPy aims to provide an array object that is up to 50x faster than traditional Python lists.

Useful for Data Science and Machine learning.

Numpy can do everything python lists can do and much more.

Some applications include mathematics, plotting and machine learning.

Works well with other libraries like Pandas and Tensorflow.


Allowing for efficient data manipulation as well but its main use case involves multi-dimensional arrays and vectorized operations, which are faster and more efficient than using standard Python loops.


The import and from statements, used to import modules whose functions or variables can be used in the current program


Python program num.py

=====================================================

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

print(type(arr))

===================================================

john_iacovacci1@cloudshell:~/py-exam (uconn-engr)$ python3 num.py

[1 2 3 4 5]

<class 'numpy.ndarray'>

john_iacovacci1@cloudshell:~/py-exam (uconn-engr)$ 


Python program numpy_example.py

===================================================

import numpy as np

#customer details

name = input("Name: ")

address = input("Address: ")

#data in numpy (np) arrays

items = np.array(['Plates', 'Cups'])

prices = np.array([2, 4])

#quantities

num_plates = int(input("How many plates? "))

num_cups = int(input("How many cups? "))

#store quantities in a numpy array

quantities = np.array([num_plates, num_cups])

#calculate total for each item and overall total

totals = prices * quantities

total_cost = np.sum(totals)

#results

print("\nCustomer Information:")

print(f"Name: {name}")

print(f"Address: {address}")

print("\nInvoice:")

for i, item in enumerate(items): #iterate through numpy array to print result

    print(f"{item}: Quantity = {quantities[i]}, Unit Price = ${prices[i]}, Total = ${totals[i]}")

print(f"\nTotal Amount Due: ${total_cost}")


===================================================

Results


$ python3 numpy_example.py

Name: John Iacovacci

Address: 55 Daffodil Road

How many plates? 2

How many cups? 2


Customer Information:

Name: John Iacovacci

Address: 55 Daffodil Road


Invoice:

Plates: Quantity = 2, Unit Price = $2, Total = $4

Cups: Quantity = 2, Unit Price = $4, Total = $8


Total Amount Due: $12

john_iacovacci1@cloudshell:~/py-exam (uconn-engr)$ 



Pandas


Pandas is a software library written for the Python programming language for data manipulation and analysis. In particular, it offers data structures and operations for manipulating numerical tables and time series.


Python library used for working with data sets.

It has functions for analyzing, cleaning, exploring, and manipulating data.

The name "Pandas" has a reference to both "Panel Data", and "Python Data Analysis" and was created by Wes McKinney in 2008.

Provides fast, flexible, and expressive data structures designed to make working with "relational" or "labeled" data both easy and intuitive. It aims to be the fundamental high-level building block for doing practical, real world data analysis in Python. Additionally, it has the broader goal of becoming the most powerful and flexible open source data analysis / manipulation tool available in any language. 

Pandas provides adaptable data structures with powerful instruments for data indexing, selecting, and manipulating which sidesteps the need for complex programming methods. You can easily convert CSV, Excel, SPSS (Statistical Package for the Social Sciences) files and SQL databases into DataFrames.

Install pandas

john_iacovacci1@cloudshell:~/py-exam (uconn-engr)$ pip3 install pandas

Successfully installed pandas-2.2.3 pytz-2024.2 tzdata-2024.1

Python program pan.py

==================================================


import pandas as pd

mydataset = {

  'cars': ["BMW", "Volvo", "Ford"],

  'passings': [3, 7, 2]

}

myvar = pd.DataFrame(mydataset)

print(myvar)

====================================================

Results

python3 pan.py

    cars  passings

0    BMW         3

1  Volvo         7

2   Ford         2

Python program pandas_example.py

===================================================


#import pandas library

import pandas as pd

#customer details

name = input("Name: ")

address = input("Address: ")

#item data, name and price

data = {

    'Item': ['Plates', 'Cups'],

    'Price': [2, 4]

}

df = pd.DataFrame(data) #dataframe

#quantities

num_plates = int(input("How many plates? "))

num_cups = int(input("How many cups? "))

#add quantities to the DataFrame

df['Quantity'] = [num_plates, num_cups]

#calculate total for each item and overall total

df['Total'] = df['Price'] * df['Quantity']

total_cost = df['Total'].sum()

#results

print(f"\n{name}\n{address}")

print(df[['Item', 'Quantity', 'Total']])

print(f"Amount Due = ${total_cost}")

====================================================

Results

$ python3 pandas_example.py

Name: John Iacovacci

Address: 55 Daffodil Road

How many plates? 4

How many cups? 4

John Iacovacci

55 Daffodil Road

     Item  Quantity  Total

0  Plates         4      8

1    Cups         4     16

Amount Due = $24

john_iacovacci1@cloudshell:~/py-exam (uconn-engr)$ 

Matplotlib

Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK.

Popular data visualization library in Python. It's often used for creating static, interactive, and animated visualizations in Python. Matplotlib allows you to generate plots, histograms, bar charts, scatter plots, etc., with just a few lines of code.

Matplotlib is a low level graph plotting library in python that serves as a visualization utility. Created by John D. Hunter,  open source and can be used freely. Mostly written in python, a few segments are written in C, Objective-C and Javascript for Platform compatibility.

matplotlib.pyplot is a collection of functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.

Python program mat.py

====================================================

import matplotlib.pyplot as plt  

import numpy as np  

# Data for plotting

t = np.arange(0.0, 2.0, 0.01)  # Create an array of values t from 0 to 2 , with a step size of 0.01

s = 1 + np.sin(2 * np.pi * t)  # Calculate the s values (sin(2*pi*t)) and add 1 to shift the curve vertically

fig, ax = plt.subplots()  # Create a figure and a set of subplots (returns a figure and axis object)

ax.plot(t, s)  # Plot the time values 't' on the x-axis and the sine values 's' on the y-axis

# Set axis labels and title

ax.set(xlabel='x-axis', ylabel='y-axis', title='Simple Plot Example')  # Label the x-axis, y-axis, and set a title for the plot

ax.grid()  # Add a grid to the plot for better visual reference

fig.savefig("test.png")  # Save the figure to a file named "test.png"

plt.show()  # Display the plot window to the user

====================================================


No comments:

Post a Comment

3D Printing

  I wanted to let you know that the lab's 3D printers, the Prusas and the Flashforge are now available for printing. Please keep in mind...