UCONN

UCONN
UCONN

Python Primer

Python Primer


Python web


https://www.python.org/



The salary for a Python developer can vary depending on experience level, location, and skill set. Here are some salary ranges for Python developers: 

Entry-level: Starting salaries for entry-level Python developers are around $118,400 annually. 

Mid-level: Mid-level Python developers make around $140,728 annually. 

Senior-level: Senior-level Python developers can make up to $163,200 annually. 


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


Python's developers aim for it to be fun to use. 


Spam and Eggs


This is reflected in its name—a tribute to the British comedy group Monty Python —and in occasionally playful approaches to tutorials and reference materials, such as the use of the terms "spam" and "eggs" (a reference to a Monty Python sketch) in examples, instead of the often-used "foo" and "bar".


What is Python?



Python is a programming language that lets you work more quickly and integrate your systems more effectively.


Interpreted, object-oriented, high-level programming language.


High-level built in data structures, dynamic typing and dynamic binding. 


Rapid Application Development, a scripting or glue language.


Connect existing components together. 


Python's simple, easy to learn syntax emphasizes readability.


Supports modules and packages, program modularity and code reuse.


Python interpreter and the extensive standard library are available in

source or binary form without charge for all major platforms, and can be

freely distributed.


Python is meant to be an easily readable language. 

Its formatting is visually uncluttered and often uses English keywords where other languages use punctuation. 










Why use Python?

  • Readable and Maintainable Code.

  • Multiple Programming Paradigms (object oriented and structured

programming fully) dynamic type system.

  • 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 has the following data types built-in by default, in these categories:


Name

Type

Description

Integers

int

numbers eg 3

Floating point

float

numbers with decimals 3.14

Strings

str

"University of Connecticut"

Lists

list

collection of items (1,2,3)

Dictionaries

dict

name/value pairs (name : John)

Booleans

bool

True or False









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 #################

# List is a collection which is ordered and changeable. Allows duplicate members.

my_list = [1,2,3]

for it_name in my_list:

    print (it_name)


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


#Dictionary is a collection which is unordered, changeable and indexed.

#No duplicate members.

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

print (my_dict['name'])

print(type(my_dict))


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

### BOOLEAN ###

#Booleans represent 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 (uconn-engr)$ python3 dt.py

<class 'int'>

5

<class 'float'>

20.5

1

2

3

John

<class 'dict'>

True

<class 'bool'>











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 (uconn-engr)$ 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 (uconn-engr)$ 




Python Assignment Operators

python program ao.py

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

#!/usr/bin/python3

#!/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 (uconn-engr)$ 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 (uconn-engr)$ 




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)

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

john_iacovacci1@cloudshell:~/py-exam (uconn-engr)$ 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


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 (uconn-engr)$ 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


String format()

The format() method allows you to format selected parts of a string.

Sometimes there are parts of a text that you do not control, maybe they come from a database, or user input?

To control such values, add placeholders (curly brackets {}) in the text, and run the values through the format() method:


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))

quantity = 3

itemno = 567

price = 49

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

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



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

Results

john_iacovacci1@cloudshell:~/py-exam (uconn-engr)$ 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.

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



admin_@cloudshell:~/py-exam (python-inv)$ 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.

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 which is ordered and changeable. Allows duplicate members.

  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

  • Set is a collection which is unordered and unindexed. No duplicate members.

  • Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.


python program lt.py

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

#!/usr/bin/python3

### List Example ###

print('loop thru list')

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

for it_name in my_list:

    print (it_name)

### RANGE ###

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

print(my_list[2:4])

#Remember that the first item is position 0,

#and note that the item in position 4 is NOT included

### 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)

### TUPLE ###

print('loop thru tuple')

my_list = ('d','e','f','a','b')

for it_name in my_list:

    print (it_name)

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

print('dictionary example')

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

print (x['name'])

print(type(x))



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

Results

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

loop thru list

d

e

f

a

b

range starting at position 2 upto but not including position 4

['f', 'a']

replace position 1 with z

['d', 'z', 'f', 'a', 'b']

length of list

5

sort the list

['a', 'b', 'd', 'f', 'z']

loop thru tuple

d

e

f

a

b

dictionary example

John

<class 'dict'>

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


Python Control Flow

The if statement, which conditionally executes a block of code, along with else and elif (a contraction of else-if)

The for statement, which iterates over an iterable object, capturing each element to a local variable for use by the attached block


The while statement, which executes a block of code as long as its condition is true


The break statement, which exits a loop


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 (uconn-engr)$ python3 ui.py

What is your name?:John Iacovacci

My name is: John Iacovacci

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







Python Functions


A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Allows developers to build blocks of repeatable code.

starts with def

In Python a function is defined using the def keyword:

def name_of_function(name):

      Block of code

Arguments

Information can be passed into functions as arguments.

Return Values

Return allows variables to be set and return values within functions.

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

Arbitrary Arguments, *args

If you do not know how many arguments that will be passed into your function, add a

* before the parameter name in the function definition.

Keyword Arguments

You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.


Python Functions

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 (uconn-engr)$ python3 functions.py

Hello World

My name is John Iacovacci

15

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


Python Classes and Objects


Python is an object oriented programming language.


Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class


To create a class, use the keyword class:

OOP Object oriented programming allows developers to create their own objects that have methods and attributes.


Call methods using .methond_name() syntax

Methods act as functions that use information about the object, as well as the object itself to return results, or change the current object.


OOP allows us to create code that is repeatable and organized

class NameOfClass():


      def __init__(self,param1,param2):

            self.param1 = param1

            self.param2 = param2

       def some_method(self):

            # perform some action

            print(self.param1)


python program class.py

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

#!/usr/bin/python3

### Class Examples ###


class Sample():

    pass


my_sample = Sample()


print(type(my_sample))

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

Results

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


<class '__main__.Sample'>




__init__ method

"__init__" is a reserved method in python classes. 


It is called a constructor in object oriented terminology.

This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.


What is the __ main __ in Python?

'__main__' is the name of the scope in which top-level code executes.

Basically you have two ways of using a Python module:

 Run it directly as a script, or import it. 


When a module is run as a script, its __name__ is set to __main__

Python self

Featured snippet from the web

self in Python class. self represents the instance of the class.

By using the “self” keyword we can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason you need to use self.



python program class_dog.py

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

#!/usr/bin/python3

### Class Examples ###

class Dog():

    def __init__(self,breed):

        self.breed = breed


my_dog = Dog(breed='Lab')

print(type(my_dog))

print(my_dog.breed)


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

Results

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

<class '__main__.Dog'>

Lab


python program class_doggy.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("WOOF!")


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

print(type(my_dog))

print(my_dog.breed)

print(my_dog.name)

my_dog.bark()

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

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

<class '__main__.Dog'>

Lab

Bear Bear

WOOF!

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





https://wiki.python.org/moin/BeginnersGuide/Programmers


No comments:

Post a Comment

Disable Billing

Search for Billing Manage billing accounts Go to MYPROJECTS CLICK ON THE 3 BUTTON Actions Then hit disable