Archive for the ‘Scripts’ Category

This class will accept 2 input parametrers:

one of type string and second of type integer, and we need to make sure second parameter needs to be integer

# function which tests for type:

def ensure_type(value, types):
    if isinstance(value, types):
        return value
    else:
        raise TypeError('Value {value} is {value_type}, but should be {types}!'.format(
            value=value, value_type=type(value), types=types))


class Account():
    def __init__(self, name, amount):
        self.name = name
        self.amount = amount

    def __str__(self):
        return "Account owner:" + self.name + '\nAmmount$: ' + str(self.amount)    
        
    def add(self, num):
        self.amount = self.amount + num
        return self.amount
    @property
    def name(self):
        return self.__dict__['name']

    @name.setter
    def name(self, value):
        self.__dict__['name'] = ensure_type(value, str)

    @property
    def amount(self):
        return self.__dict__['amount']

    @amount.setter
    def amount(self, value):
        self.__dict__['amount'] = ensure_type(value, int)

   


acc = Account('jose', 100)
 
print(acc)

print(acc.add(10))
Advertisements

Related posts:

 

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-i-basic-data-types/

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-ii-file-manipulation/

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-iii-booleanfor-loops-and-while/

https://geekdudes.wordpress.com/2019/09/25/python-fundamentals-part-iv-scope-resolution-legb-rule/

https://geekdudes.wordpress.com/2019/09/26/python-fundamentals-part-v-importing-modules/

Object Oriented Programming (OOP) allows programmers to create their own objects that have methods and attributes. For much larger scripts of python code,functions by themselved aren’t enough for organization and repeatability.

Commonly repeated tasks and objects can be defined with OOP to create code that is more usable.

Name of the class uses Camel case convention

CamelCase is a naming convention in which the first letter of each word in a name is capitalized. (StarCraft,FireHouse)

self” is the instance object automatically passed to the class instance’s method when called, to identify the instance that called it. “self” is used to access other attributes or methods of the object from inside the method. (methods are basically just functions that belong to a class)

Class syntax:

class NameOfClass():


    def__init__(self,param1,param2):
	   
	   self.param1 = param1
       self.param2 = param2	   

    
     # self is used to connect method to the class
     
    def some_method(self):
    
        # perform some action
        
        print(self.param1)

__init__ is special method (function) which creates instance of class object

param1 param2 input parameters to class

self.param1 self.param2 atributes of the class


Dog class accepts breed parameter and assigns it to breed attribute

class Dog():

    def __init__(self,breed):
    
        # assign breed atrubute  to self.breed
         
        self.breed = breed   


# create instance of class Dog

mydog = Dog("dalmatian")

# breed is attribute of class instance mydog

mydog.breed

'dalmatian'

Class object attributes

is attribute that belongs to any instance of class hence it’s globally visible.

class Dog():

    # class object attribute
    # same for any instance of the class
    # that's why self keyword is not used
    species  = 'mammal'
    def __init__(self,breed):

        self.breed = breed
        self.name = name

Create instance of Dog class

mydog = Dog("dalmatian")

Get class atributes

mydog.breed ‘dalmatian’

mydog.species ‘mammal’

Methods

are functions which takes class input parameters through self keyword

We added another class parameter – name

and added method bark() which returns name of the dog.

class Dog():

    # class object attribute
    # same for any instance of the class
    # that's why self keyword is not used
    species  = 'mammal'
    def __init__(self,breed, name):

        self.breed = breed
        self.name = name
       
    # method
    
    def bark(self):
        print(f'{self.name} barks')


mydog = Dog("dalmatian", "Pluton")

mydog.breed
'dalmatian'

mydog.species
'mammal'

# call method

mydog.bark()
Pluton barks

Methods can take arguments not specified in class inputs

In bark method we added number input, note that in print function it specified without self because this paramter is

“outside” of class, ie, it’s not specified during class definition.

class Dog():

    # class object attribute
    # same for any instance of the class
    # that's why self keyword is not used
    species  = 'mammal'
    def __init__(self,breed, name):

        self.breed = breed
        self.name = name
         
    def bark(self, number):
        print(f'{self.name} barks and number is {number}')


mydog = Dog("dalmatian", "Pluton")
mydog.breed

'dalmatian'

mydog.species
'mammal'


# supply number argument

mydog.bark(1)

Pluton barks and number is 1

Priniting class objects

If we want to print input parameters, we need to use

__str__ – convert objects to string


__len__ – convert objects to integers

Dog class now has 3 input paraneters:

strings (name and breed)

integers (number)

class Dog():

    # class object attribute
    # same for any instance of the class
    # that's why self keyword is not used
    species  = 'mammal'
    def __init__(self,breed, name, num):

        self.breed = breed
        self.name = name
        self.num = num
    
    # return string atribute
    
    def __str__(self):

        return 'Name: ' + self.name + 'Breed: ' + self.breed    
    
    # return integer attribute
    
    def __len__(self):
        return self.num


    def bark(self, number):
        print(f'{self.name} barks and number is {number}')   

my_dog = Dog('husky','pluton', 1) 

len(my_dog)
1

str(my_dog)
'Name: pluton Breed: husky'

Inheritence

is creating new class from existing one. Derived class have all properties of base class (attributes and methods)

Base class:

class Animal():
    def __init__(self):
        print("Animal created")

    def who_am_i(self):
        print("I am an animal")

    def eat(self):
        print("I am eating")
        
        
        

my_animal = Animal()

Animal created

my_animal.eat()

I am eating

my_animal.who_am_i()

I am an animal

Creating Dog class from Animal class.

Dog class “inherits” all methods from Animal class.

class Dog(Animal):
    def __init__(self):
        Animal.__init__(self)
        print ("Dog created")



my_dog = Dog()

Animal created
Dog created

my_dog.eat()

I am eating

my_dog.who_am_i()
I am an animal

Methods from base class can be overriden in “child” (derived) class. It’s called Polymorphism.

Polymorphism

allows us to define methods in the child class with the same name as defined in their parent class.

Overriding eat() method.

In Dog class create same method as in base class and change it’s ouptut.

class Dog(Animal):
    def __init__(self):
        Animal.__init__(self)
        print ("Dog created")

    def eat(self):
        print("I'm a dog eating")


my_dog.eat()

I'm a dog eating

Abstract class

cannot be instantiated (objects cannot be created from it)

To create abstract class we need to import following namespace:

from abc import ABC,abstractmethod

ABC stands for abstract class and we need to add @abstractmethod above each method we do not want to instantiate.

from abc import ABC,abstractmethod
 class Animal(ABC):
     
  @abstractmethod
  def __init__(self, name):
      self.name = name
      print(f'Animal Created {self.name}')

f we now try to create instance from Animal class we’ll face expected error

TypeError: Can't instantiate abstract class Animal with abstract methods __init__

Let’s add another method to Animal class and derive Dog class from Animal.

from abc import ABC,abstractmethod
class Animal(ABC):
     
  @abstractmethod
  def __init__(self, name):
      self.name = name
      print(f'Animal Created {self.name}')
  # @abstractmethod 
  def eat(self):
    print(f'{self.name} eating')
 
 
class Dog(Animal):
  def __init__(self, name):
    self.name = name      
    # Animal.__init__(self)
    print(f'Animal Created {self.name}')    
 
# output
 
my_dog = Dog('tom')
'Animal Created tom'
my_dog.eat()
'tom eating'

Calling module from same folder

In Documents folder we have 2 files:

mymodule.py with simple function in it:

def my_func():
  print("My function")

myprogram.py from which we’ll call function in mymodule.py

To call function from another file we’ll use import keyword followed by file name, then we’ll simple call function from moymodule.py file (my_func)

from mymodule import my_func

my_func()

My Function

Calling modules from subfolders

Documents
        |
        |
        |
        MainPackage 
                   |
                   |                                      
                   |                                       
                   |                                       
                   __init__.py   some_main_script.py     SubPackage                                    
                                                                  |
                                                                  |
                                                                  |
                                                                  
                                                __init__.py   mysubscript.py                                                                 

Both __init__.py files are empty.The primary use of __init__.py is to initialize Python packages

Documents/MainPackage/some_main_script.py:

def report_main():
    print("Hey I'm in some_main_script in main package")

Documents/MainPackage/SubPackage/mysubscript.py:

def sub_report():
    print("Hey i'm function inside my subscript")

From Documents/myprogram.py parent folder we’ll call functions in Documents/MainPackage/some_main_script.py and Documents/MainPackage/SubPackage/mysubscript.py files

Documents/myprogram.py:

from keywords is followed by folder name and import is followed by file name located in that folder.

MainPackage/SubPackage corresponds to MainPackage.SubPackage, dot characters is used to express subfolders.

from MainPackage import some_main_script

from MainPackage.SubPackage import mysubscript

some_main_scrip.report_main()

Hey I'm in some_main_script in main package

mysubscript.sub_report()

Hey i'm function inside my subscript

Related articles:

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-i-basic-data-types/

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-ii-file-manipulation/

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-iii-booleanfor-loops-and-while/

https://geekdudes.wordpress.com/2019/09/26/python-fundamentals-part-v-importing-modules/

https://geekdudes.wordpress.com/2019/09/27/pyhon-fundamentals-part-vi-oop-concepts/

LEGB is acronim of:

L:Local – Names assigned in any way within a function (def or lambda) and not declared global in that function.

E:Enclosing function locals – Names in the local scope of any and all enclosing functions (def or lambda), from inner to outer.

G:Global (module) – Names assigned at the top-level of a module file. or declared global in a def within the file.

B:Built-in (Python) – Names preassigned in the built-in names module:open,range,SyntaxError.

Local scope refers to variables defined in current function.Always, a function will first look up for a variable name in its local scope. Only if it does not find it there, the outer scopes are checked.

name = 'This is a global string'

   def myfunc():
      name = "Hello World"
      print(name)

myfunc()
Hello World

In above example we have 2 variables with same name and when function is executed, it’s looking into it’s own namespace (name=’Hello World’), in case there is no variable name inside “enclosing function” – myfunc(), then global name string would be applied, below example illustrates this:

name = 'This is a global string'

   def myfunc():
       print(name)

myfunc()
This is a global string

Let’s look at next example:

x =  50

def func(x):
     print(f'X is {x}')
     
     # Local reassignment
     x = 200
     print(f'I just changed X to {x} locally')

func(x)

X is 50
I just changed X to 200 locally

print(x)
50

So we get 50 for X although we changed it’s value to 200, it’s because assignment happens only inside local namespace (inside this function), it’not going to affect any variable outside function itself (higher scope).


If we need to “override” global variable we can do it in following way:

we declared global x variable global x, so function will tell python: go to namespace, jump to the global level and get x value, then assign new value to that global variable locallyx = 'new value' and apply changes on global level.

x =  50

def func():
     global x

     print(f'X is {x}')
     
     # Local reassignment on a global variable 
     x = 'new value'
     print(f'I just locally changed global X to {x}')

func()
X is 50
I just locally changed global X to new value
print(x)
new value

Above approach is potentially dangerous because we change global variable value so safer solution would be to assign output of function to global variable, without changing it:

x =  50

def func(x):
     print(f'X is {x}')
     
     # Local reassignment 
     x = 'new value'
     print(f'I just locally changed global X to {x}')
     return x


x = func(x)
X is 50
I just locally changed global X to new value
print(x)
new value

Related posts:

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-i-basic-data-types/

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-ii-file-manipulation/

https://geekdudes.wordpress.com/2019/09/25/python-fundamentals-part-iv-scope-resolution-legb-rule/

https://geekdudes.wordpress.com/2019/09/26/python-fundamentals-part-v-importing-modules/

https://geekdudes.wordpress.com/2019/09/27/pyhon-fundamentals-part-vi-oop-concepts/

Booleans are operators used to express True or False statements, used for performing comparations.Needs to be capitalized True is not equal to true and False is not equal to false.None used to define null value or no value at all.

If elif and else statements

if some_condition: 

   # execute some code 

elif some_other_condition: 

   # execute_some_other_code 

else: 

   # do something else


############################################################## 

# print response based on input code

code = 'CA' 

if code == 'CA': 

  print("CA is California") 

elif code == 'CO': 

  print("CO is Colorado") 

elif code == 'CT': 

  print("CT is Connecticut") 

else: 

  print("Invalid. Please enter a valid state code that starts with letter C") 

For Loops

We can iterate over every element in many objects in Ptyhon. Executing block of code for every iteration is possible using for loops.Bellow code will print list value (1,2,3).Item_name is arbitrary variable, it represents values in my_iterable list.For every value (item_name) in my_iterable list, print that value.

 

my_iterable = [1,2,3] 

for item_name in my_iterable: 

  print(item_name) 
1
2
3

Getting dictionary key pairs

d = {'k1':1,'k2':2,'k3':3} 

for item in d.items(): 

    print(item) 

 ('k1', 1) 

('k2', 2) 

('k3', 3) 

  

  

# getting values 
for item in d.values(): 

    print(item) 

1 
2 
3 

  

# another way  

  
for key,value in d.items(): 
    print(value) 

while loops executes a block of code while some conditions remains True.

while some_boolean_condition: 

   #do something 

While will execute until x is less than 5, otherwise, it will print “X is not less than 5”

x = 0 

while x < 5:
    print(f'The current value of x is {x}') 
    x = x + 1 
else: 
    print("X is not less than 5")    

The current value of x is 0 
The current value of x is 1 
The current value of x is 2 
The current value of x is 3 
The current value of x is 4 
X is not less than 5 

break,continue and pass statements.

break: Breaks out of the current loops

continue: goes to the top of cuttent loops

pass: does noting at all (prevents errors)

Bellow is example for pass

x = [1,2,3] 

    for item in x: 
    # nothing 
    print('end')  
  IndentationError: expected an indented block 

# adding pass will prevent syntax error and won't do anything else

x = [1,2,3] 
  for item in x: 
     # nothing 
  pass 
  print('end') 

end 

continue

In below examplw,when for loop finds ‘e’ character, it will simply go back at the begging of the loop, it won’t process ‘e’ character.

string = 'Hello' 
for letter in string: 
   if letter == 'e': 
      continue 
   print(letter)    
H 
l 
l 
o    

Break will simple stop executing code when it faces ‘e’ character.

string = 'Hello' 
for letter in string: 
   if letter == 'e': 
       break 
   print(letter)  
H    

Range function prints number in specified range except last number (10 in this case)

a = list(range(1,10))
print (a)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

range function includes another parameter:step.

The step is a difference between each number in the result.

for num in range(3,11,2):
    print(num)
3
5
7
9

List comprehension is an other way how to iterate through list instead of for loop

# for loop
my_string = 'hello'
my_list = []
for letter in my_string:
    if 'l' in letter:
        print(True)
    else:
        print(False)

# output
False
False
True
True
False

# List comprehension

['True' if 'l' in letter else 'False' for letter in my_string] 

Enumerate function creates index of items in for loop iteration for every location in variable

word = "abcde" 

for item in enumerate(word): 
   print(item) 
(0, 'a') 

(1, 'b') 

(2, 'c') 

(3, 'd') 

(4, 'e') 

zip function zips 2 or more lists returns list of tuples
(pairs up one element in one list with element in other list at same index )

mylist1 = [1,2,3] 
mylist2 = ['a','b','c']

for item in zip(mylist1,mylist2):
    print(item)

(1, 'a')
(2, 'b')
(3, 'c'

If 2 lists are not even, zip returns pair for shortest list

mylist1 = [1,2,3,4,5,6]
mylist2 = ['a','b','c']

for item in zip(mylist1,mylist2):
   print(item)

(1, 'a')
(2, 'b')
(3, 'c')

We can convert tuples to list using zip

list(zip(mylist1,mylist2))
[(1, 'a'), (2, 'b'), (3, 'c')]

in operator – checks if statement is true or false

# check if x is in list 

'x' in [1,2,3]
False

'x' in ['x','y','z']
True

# check if a is in string 

'a' in 'a word'
True

# check if mykey is in dictionary 

'mykey' in {'mykey':345}
True


d = {'mykey':345}
345 in d.values ()
True
345 in d.keys()
False
345 in d.items()
False

prompt user for input using string

a = input('Enter something')

# input as number

number = input("Enter a number")

int(number)

Functions allows creating block of code that can be executed multiple times without need to rewrite block of code.
Return keyword sends back function results, so we can assign this output to variable.

def function_name():
   
   return ("Hello")
   

Functions output can be assigned to variables.

output = function_name()

print(output)

Hello

Add parameter to function.

def printme( str ):
    "This prints a passed string into this function"
    return str

printme("I'm first call to user defined function!")

*args and **kwargs

def myfunc(a,b):
    return sum((a,b)) 


myfunc(8,2,1)

TypeError: myfunc() takes 2 positional arguments but 3 were given

If, in above function, we supplied more parametes than needed, then we get error.To enable function to take arbitrary number of paramters we can use *args, and specify as many parameters as we want.
Input parameters are treated as tuple (a,b,c….).

def myfunc(*args):
    return sum(args)

**kwargs creates argument of keypairs, it returns dictionary, and accepts named arguments.In next example,if user passes other argument than city, it won’t be returned but also won’t throw an error.

def myfunc(**kwargs):
    
    if 'city' in kwargs:
        return ('My favorite city is  {}'.format(kwargs['city']))
    else:
        return ("Didn't find any city")    

myfunc(city = 'Zemoon',river = 'Danube')

'My favorite city is  Zemoon'

Map function

passes every single element of list to function, so instead of running custom function multiple times for every string in list, map simple passes every string to our function in “one go”

In this example function will print “EVEN” for string whose lenght is even number, othervise, it will print first letter of non-evcen string.

def splicer(mystring):
    if len(mystring)%2 == 0:
        return 'EVEN'
    else:
        return mystring[0]

Now, we can use map to call splicer function and it’s parameter (names)

names = ['Andy','Eve','Sally']

for item in map(splicer,names):
    print(item)
EVEN
E
S

filter function returns an iterator were the items are filtered through a function to test if the item is accepted or not (True) This function accepts numbers, and if input parameter is less than 18, it returns False, othervise, returns True

def myFunc(x):
  if x < 18:
    return False
  else:
    return True

Filter function, will iterate through all elemets in ages list and will return only values which are True.

ages = [5, 12, 17, 18, 24, 32]

adults = filter(myFunc, ages)

for x in adults:
  print(x)

18
24
32

Lambda is function that’s defined without name While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Here is equivalet of above myFunc function.

ages = [5, 12, 17, 18, 24, 32]

adults = list(map(lambda x: True if (x > 18) else False,ages))

print(adults)

[False, False, False, False, True, True]

To print only values x>18, again we’l use filter function.

adults = list(filter(lambda x: True if (x > 18) else False,ages))

print(adults)

[24, 32]

return first character of string

names = ['Andy', 'Eve', 'Sally']
first_letter = list(map(lambda x:x[0], names))
print(first_letter)
['A', 'E', 'S']

Related posts:

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-i-basic-data-types/

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-iii-booleanfor-loops-and-while/

https://geekdudes.wordpress.com/2019/09/25/python-fundamentals-part-iv-scope-resolution-legb-rule/

https://geekdudes.wordpress.com/2019/09/26/python-fundamentals-part-v-importing-modules/

https://geekdudes.wordpress.com/2019/09/27/pyhon-fundamentals-part-vi-oop-concepts/

 

Get current directory path and list files in it:

import os

dirpath = os.getcwd()
files = [ f for f in os.listdir(dirpath) if os.path.isfile(os.path.join(dirpath,f)) ] 
print('Files:{f} in {d}'.format(f = files ,d = dirpath)) 

# change directory to dirpath 
os.chdir(dirpath) 

File modes:

‘r’ – read only

‘w’ – write (will overwrite file or create new)

‘a’ – append (add new lines in file)

‘r+’ – reading and writing

‘w+’ – writing and reading (overwrites exiting files or creates a new one)

# Write to file 

file1 = open("myfile.txt","w")  
file1.write("This is Delhi\nThis is Paris\nThis is London\n") 
file1.close() 

  
# read file 

file1 = open("myfile.txt","r")  
file1.readlines() 
file1.close() 

In above examples we need to manually close files using close() method.

Using “with” directives files are automatically closed after writing/reading

# read file and automatically close file  

with open('myfile.txt') as my_file: 
    content = my_file.read() 

# write to file 
 
with open('myfile.txt', 'w') as my_file: 
  my_file.write("This is Delhi\nThis is Paris\nThis is London\n") 

# append new line to file 
with open('myfile.txt', 'a') as my_file: 
  my_file.write("This is Zemoon\n") 

 

 

Related posts:

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-ii-file-manipulation/

https://geekdudes.wordpress.com/2019/09/18/python-fundamentals-part-iii-booleanfor-loops-and-while/

https://geekdudes.wordpress.com/2019/09/25/python-fundamentals-part-iv-scope-resolution-legb-rule/

https://geekdudes.wordpress.com/2019/09/26/python-fundamentals-part-v-importing-modules/

https://geekdudes.wordpress.com/2019/09/27/pyhon-fundamentals-part-vi-oop-concepts/

Numbers

Integers – whole numbers

print(10)
10
type(10)
<class 'int'&gt;

floating point – numbers with decimal

print(4.2)
4.2
type(4.2)
<class 'float'&gt;

The max() function returns the largest of the input values

max(1,3)
3

min() function returns the lowest number

min(1,3)
1

sum() function returns sum of 2 numbers

sum([1,3])
 4
 abs() returns absolute value
abs(-234)
234

String

Strings are immutable (cannot be changed)

 

name = "Test" 
# In string "Test" change first letter to "F"
name[0] = "P" 
TypeError: 'str' object does not support item assignment 

Error is thrown because strings are immutable.To change “Test” to “Fest”

# Extract "est" using slices 
# 1 - start from second character (index 0), until the end of string (:) 
name = "Test"
name = name[1:0] 
"F" + name[1:]  
'Fest' 

It’s not possible to concatenate number and string

name = "Test"
1 + name 
TypeError: unsupported operand type(s) for +: 'int' and 'str' 

‘2’+’3′ won’t give 5 because both values are treated as string (because quotes quotes)

'2' + '3' 
'23' 

Object in python usually have built-in methods (functons inside an objects) .

Some of them are upper – convert all characters to uppercase and lower (convert all characters to lowercase)

name = "Test"
name = name.upper() 
print(name) 
'TEST' 
name = name.lower() 
print(name) 
'test' 

split() creates list from string (splits based on whitespace)

name = 'Hello World' 
name = name.split() 
print(name) 
['Hello', 'World'] 

Split based on character ‘i’

x = "hi, this is a string" 
y = x.split('i') 
print (y) 
['h', ', th', 's ', 's a str', 'ng'] 

Reverse string

# print hello to olleh
s = "hello"
s[::-1] 
'olleh' 

Counter – print number of occurrences elements in list or stringHow many times does letter ‘w’ shows in string: 

from collections import Counter
s = 'twuwwjhjhjhwwhsjhssssssadff'
s.count('w')
5

Methods of Counter:

s = 'How many times does each word show up in this sentence word word shoe up up'

c = Counter(s)


sum(c.values()) # total of all counts
c.clear() # restet all counts
list(c) # list unique elements
set(c) # converts to set
dict(c) # converts to dictionary
c.items() # convert to list of (elem, cnt) pairs
Counter(dict(list_of_pairs)) #converts from a list of (elem, cnt) pairs
c.most_common()[:n-n-1:-1] #n least common elements
c += Counter() # removes zero and negative counts

String interpolation (printing variables inside strings) using .format() method

# add word INSERTED 
print('This is a string {}'.format('INSERTED')) 
'This is a string INSERTED' 

Adding multiple parameters (in order)

print('The {} {} {}'.format('fox','brown','quick')) 
'The fox brown quick' 

Change order of input string using index

fox – index 0

brown – index 1

quick – index 2

We can set paramter order as we wish using these index numbers

print('The {2} {1} {0}'.format('fox','brown','quick')) 
'The quick brown fox' 

Assigning variables to input strings

fox = a

brown = b

quick = c

print('The {a} {b} {c}'.format(a = 'fox',b = 'brown',c = 'quick')) 
The fox brown quick 

Float formatting {value:width.precision f}
value – r
width – number of positions (whitespaces) which defines distance between “The result was” and r variables
precision – number of values after “.”

result = 100/777 
0.1287001287001287 
print("The result was {r:1.3f}".format(r=result)) 
The result was 0.129 

Since Python 3.6, there is new format for printing variables inside strings

x = "Test" 
print(f'This is {x}') 
This is Test 

x = "Test" 
y = 3 
print(f'This is {x} number {y}') 
This is Test number 3

A list is a data structure in Python that is a mutable (changeable) ordered sequence of elements. Each element or value that is inside of a list is called an item. Lists are defined by having values between square brackets [ ].

my_list = ['a',1,1.2] 
# get lenght of list
len(my_list) 
3 

# get first element of list - indexing 
my_list[0] 
'a' 

# get list members since first index until the end of list - slicing 
my_list[1:] 
[1, 1.2] 

# concatanate 2 lists 
my_list = ['one',1,1.2] 
my_list1 = ['two',2,2.2] 
my_list + my_list1 
['one', 1, 1.2, 'two', 2, 2.2] 

# change 'one' to 'ONE'  

my_list = ['one',1,1.2] 
my_list[0] ='ONE' 
my_list 
['ONE', 1, 1.2] 

# Add elements to the end of list 
my_list = ['one',1,1.2] 
my_list.append('six') 
my_list 
['one', 1, 1.2, 'six'] # add elements to listx = [1,2,3]x.extend([4,5])print (x)[1, 2, 3, 4, 5]# insert element at specific indexl = [1,2,3,4]l.insert(2,'inserted')print(l)[1, 2, 'inserted', 3, 4]# removes specific elementl.remove('inserted')l = [1,2,'inserted',3,4]print(l)[1,2,3,4]

# replace hello with goodbye 
list3 = [1,2,[3,4,'hello']] 
list3[2][2] = 'goodbye' 

# editing list using pop function. 

# removing last item in list 

my_list = ['one',1,1.2] 
my_list.pop() 
1.2 
my_list 
['one', 1] 

#Remove 1st element from list 
my_list = ['one',1,1.2] 
my_list.pop(1) 
1 
my_list 
['one', 1.2] 

# sort list (ascending)  
my_list = ['a','x','z','s'] 
my_list.sort() 
sorted_list = my_list 
print(sorted_list) 
['a', 's', 'x', 'z'] 

# Descending order 
my_list = ['a','x','z','s'] 
my_list.reverse() 
reversed_list = my_list 
print(reversed_list) 
['s', 'z', 'x', 'a'] 

# Return range of values in list

s = [1, 0, 3, 0, 6, 7]
s[0:0+3]
[1, 0, 3]

# reverse
listl = [2,4,3,1,5]

l.reverse()
print(l)

[5, 1, 3, 4, 2]

# sort listl.sort()

print(l)

[1, 2, 3, 4, 5]

capitalize() method converts the first character of a string to capital (uppercase) letter. If the string has its first character as capital, then it returns the original string.

"test".capitalize()
Test


Strings are immutable (cannot be changed)

 

Dictionary is an unordered collection of data values, used to store data values like a map, which holds key:value pair.This key:value pair allow locating object without need to know index location.

Dictionary vs Lists

Dictionary: object retrieved by key name unordered and cannot be sorted.Lists: object retrieved by location.Ordered Sequence can be indexed,sorted and sliced(get substring). Getting dictionary value:

my_dict = {'key1':'value1','key2':'value2'} 
my_dict['key1'] 
'value1' 

# get value 100
d ={'k1':123,'k2':[0,1,2],'k3':{'insidekey':100}} 
d['k3']['insidekey'] 
100 

# return value from listed dictionary 
d ={'key1':['a','b','c']} 
d['key1'][2] 
'c' 

# Adding new key:pair to dictionary 
d ={'k1':100,'k2':200} 
d['k3'] = 300 
d 
{'k1': 100, 'k2': 200, 'k3': 300} 

# change value 
d ={'k1':100,'k2':200} 
d['k1'] = 'New' 
d 
{'k1': 'New', 'k2': 200} 

# getting keys 
d.keys() 
dict_keys(['k1', 'k2']) 

# getting values 
d.values() 
dict_values(['New', 200]) 

#getting "pairs" 

d.items() 
dict_items([('k1', 'New'), ('k2', 200)]) 

# get 'hello' 
d = {'k1':[{'nest_key':['this is deep',['hello']]}]} 
for a in d['k1']: 

    print(a['nest_key'][1]) 
# output
hello
# get hello 
d = {'k1':[1,2,{'k2':['this is tricky',{'tough':[1,2,['hello']]}]}]} 

for a in d['k1'][2]['k2'][1]['tough'][2]: 
    print (a)  
# output
  hello
     

 

An OrderedDict is a dictionary subclass that remembers the order that keys were first inserted. The only difference between dict() and OrderedDict() is that:

OrderedDict preserves the order in which the keys are inserted. A regular dict doesn’t track the insertion order, and iterating it gives the values in an arbitrary order. By contrast, the order the items are inserted is remembered by OrderedDict.

# standard dictionary
d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 5

 for k,v in d.items():
     print (k,v)
# output

a 1
b 2
c 3
d 5

# ordered dictionary

from collections import OrderedDict
d = OrderedDict()
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 5

for k,v in d.items():
     print (k,v)
# output

a 1
b 2
c 3
d 5



Tuples are sequences of objects, immutable (cannot be changed), element inside tuple cannot be reassigned, use parenthesis (1,2,3) .Can contain different type of objects.

t = (1,2,[1,2]) 
t = (1,"one",3.2) 
type(t) 
# output
<class 'tuple'&gt; 

# supports indexing - return index at 0 
t[0] 
# output
1 
# and slicing - return last value  
(1, 'one', 2.3) 
t[-1] 
# output
2.3 

# How many times number 2 appears in tuple 
t = (2,"one",2,2) 
t.count(2) 
# output
3 

# Return very First position of 2 in tuple 
t.index(2) 
# output
0

It’s not possible to change value types in tuple

t = (2,"one",2,2) 
t[0] = "NEW" 
# output
TypeError: 'tuple' object does not support item assignment 

Sets are unordered collections of unique elements (removes duplicate entries from list) .Sets cannot contain mutable objects like lists, dictionaries, and other sets, since items in a set must remain unique.Sets are represented with curly braces {}

my_list = [1,2,3,2,2,3] 

# get unique values from list my_list
unique = set(my_list) 
print(unique) 
# output
{1, 2, 3} 

 diference between 2 sets:

s1 = {1,2,3}
s2 = {1,4,5}
s1.difference_update(s2)
s1
# output
{2, 3}

discard element from set

s2.discard(4)
s2
# output
{1, 5}

intersection returns common elements of 2 sets

s1 = {1,2,3}

s2 = {1,4,5}

s1.intersection(s2) 
# output
1

The intersection_update() updates the set calling intersection_update() method with the intersection of sets.
The intersection of two or more sets is the set of elements which are common to all sets.

This method returns None (meaning, absence of a return value). It only updates the set calling the intersection_update() method.

A = {1, 2, 3, 4}
B = {2, 3, 4, 5}
result = A.intersection_update(B)
print('result =', result)
resut = None
print('A =', A)
# output
A = {2, 3, 4}
print('B =', B)
# output
B = {2, 3, 4, 5}

isdisjoint()
Two sets are said to be disjoint when their intersection is null. In simple words they do not have any common element in between them.

set1 = {2, 4, 5, 6}  
set2 = {7, 8, 9, 10} 
set3 = {1, 2} 
    
#checking of disjoint of two sets 
print("set1 and set2 are disjoint?", set1.isdisjoint(set2)) 
  
print("set1 and set3 are disjoint?", set1.isdisjoint(set3)) 
#Output:
set1 and set2 are disjoint? True
set1 and set3 are disjoint? False

issubset Return True if all items set x are present in set y:

x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
print(z)
# output
True

issuperset()

issuperset() method returns True if all elements of a set A occupies set B which is passed as an argument and returns false if all elements of B not present in A.
This means if A is a superset of B then it returns true; else False

A = {4, 1, 3, 5} 
B = {6, 0, 4, 1, 5, 0, 3, 5} 
  
print("A.issuperset(B) : ", A.issuperset(B)) 
  
# B is superset of A 
print("B.issuperset(A) : ", B.issuperset(A)) 

#Output:

A.issuperset(B) :  False
B.issuperset(A) :  True

symmetric_difference returns element from s2 not present in s1

s1 = {1,2}

s2 = {1,2,4}

s1.symmetric_difference(s2)
# output
{4}

union returns elements in both sets

s1 = {1,2}
s2 = {1,2,4}

s1.union(s2)
# output
{1,2,4}