Python Tutorial


sudo apt update
sudo apt install python3 python3-dev python3-venv

wget https://bootstrap.pypa.io/get-pip.py
sudo python get-pip.py
mkdir project
cd project
python3 -m venv venv
source venv/bin/activate


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 first line of the program which indicates the location of the Python interpreter on the hard drive. It's in the following format:

Hello World

!/usr/bin/python3# Say hello, world.print ("Hello, world!")

Python has the following data types built-in by default, in these categories:


python program dt.py

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

my_list = [1,2,3]
for it_name in my_list:
    print (it_name)
print(type(my_list)

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

my_dict = {"name" : "John""email" : "john.iacovacci1@gmail.com"}
print (my_dict['name'])
print(type(my_dict))

########### BOOL ###########
### BOOLEAN ###

x = True

#display x:
print(x)

#display the data type of x:
print(type(x)) 

Python Arithmetic Operators


python program ao.py

#!/usr/bin/python3

# DATA OPERATOR EXAMPLES ##########

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

### MODULUS ###
print('MODULUS x = 5 % 2')
x = 5 % 2
print(x)

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

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)

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)

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

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


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


Python Control Flow


python program cf.py

#!/usr/bin/python3

### CONTROL FLOW ###

### if test ###

a = 3
b = 5
print('if a = 3 and x = 5')
if b > a:
  print("b is greater than a")

### if elif test ###

a = 6
b = 5
print('elsif a = 6 and x = 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 x = 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('fomatting 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


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)


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

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.

Arbitrary Keyword Arguments, **kwargs

If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition.
This way the function will receive a dictionary of arguments, and can access the items accordingly:
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))

### FUNCTION WITH X ARGS ###
def my_function(*kids):
  print("The youngest child is " + kids[1])

my_function("Jonathan","Michael")

### FUNCTION WITH KEY WORD ARGUMENTS ###

def my_function(child2child1):
  print("The youngest child is " + child2)

my_function(child1 = "Jonathan"child2 = "Michael")

### ARBITARY KEY WORD ARGUMENTS ###

def my_function(**kid):
  print("His last name is " + kid["lname"])

my_function(fname = "Jonathan"lname = "Iacovacci")

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))
__init__ method
"__init__" is a reseved method in python classes. It is called as 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)
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()






No comments:

Post a Comment

Office hours tomorrow(Tuesday) 5:00pm-6:00pm, 4/26/2021, 5:13 PM, English, 4/26/2021, 5:13 PM

Your assigned language is: English Classroom blog: googleclouduconn.blogspot.com 4/26/2021, 5:13 PM Office hours tomorrow(Tuesday) 5...