Python Primer
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.
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
Run a Python Script Under Mac, Linux, BSD, Unix, etc
On platforms like Mac, BSD or Linux (Unix) you can put a "shebang" line as the first line. (#!/usr/bin/python3)
Indicates the location of the Python interpreter on the hard drive.
It's in the following format:
Simple Hello World python script to start
Go to linux cloud shell and make a directory py-exam
Welcome to Cloud Shell! Type "help" to get started.
Your Cloud Platform project in this session is set to python-inv.
Use “gcloud config set project [PROJECT_ID]” to change to a different project.
john_iacovacci1@cloudshell:~ (uconn-engr)$ mkdir py-exam
Open Editor
Highlight the py-exam directory and right click to select new file
Type the name hw.py
Put the code for Hello World in the editor screen
#!/usr/bin/python3
# Say hello, world.
print ("Hello, world!")
Go back into Terminal
Change into py-exam directory
john_iacovacci1@cloudshell:~ (uconn-engr)$ cd py-exam
Now execute the hw.py script
john_iacovacci1@cloudshell:~ (uconn-engr)$python3 hw.py
Hello, world!
admin_@cloudshell:~/py-exam (python-inv)$
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
=======================================================
#!/usr/bin/python3
# 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))
=========================================================
Results
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$ python3 dt.py
<class 'int'>
5
<class 'float'>
20.5
a
b
c
John
<class 'dict'>
True
<class 'bool'>
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$
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
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$ python3 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
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$
Python Assignment Operators
python program ao.py
===========================================================
#!/usr/bin/python3
### 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
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$ python3 ao.py
= sign x = 3
3
+= sign x += 3
9
-= sign x-= 3
3
*= sign x*= 3
18
/= sign x/= 3
2.0
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$
Python Comparison Operators
python program co.py
=========================================================#!/usr/bin/python3
### Comparison Operators ###
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
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$ python3 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
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$
Python Logical Operators
python program lo.py
===========================================================
#!/usr/bin/python3
### Logical Operators ###
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
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$ python3 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
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$
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
=========================================================
#!/usr/bin/python3
### FORMAT ###
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
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$ python3 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.
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$
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
========================================================
#!/usr/bin/python3
### List Example ###
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
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$ python3 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'>
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$
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
=======================================================
#!/usr/bin/python3
### CONTROL FLOW ###
### if test ###
a = 3
b = 5
print('if a = 3 and b = 5')
if b > a:
print("b is greater than a")
### if elif test ###
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
i += 1
=======================================================
Results
john_iacovacci1@cloudshell:~/py-exam (uconn-engr)$ python3 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
john_iacovacci1@cloudshell:~/py-exam (uconn-engr)$
Python User Input
python program ui.py
=====================================================
#!/usr/bin/python3
### USER INPUT ###
my_name = input("What is your name?:")
print("My name is: " + my_name)
=====================================================
Results
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$ python3 ui.py
What is your name?:John Iacovacci
My name is: John Iacovacci
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$
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
========================================================
#!/usr/bin/python3
### SIMPLE FUNCTION ###
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
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$ python3 functions.py
Hello World
My name is John Iacovacci
15
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$
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
====================================================
#!/usr/bin/python3
### 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
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$ python3 dog_class.py
<class '__main__.Dog'>
mixed
Bear Bear
BARK!
john_iacovacci1@cloudshell:~/py-exam (cloud-project-examples)$
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!"
No comments:
Post a Comment