Pythin Learnings
Pythin Learnings
import random
a=4
b,c,d=5,"neha",12.04
flag =True # boolean datatype
if(flag==True):
print(flag)
"""Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the
values into variables.
This is called unpacking.
"""
#Unpack a list:
print(x, y, z)
print(x+y+z)
"""
Python has the following data types built-in by default, in these categories:
"""
# to get type of a var
print(type(x))
print(random.randrange(1,3))
for x in "neha":
print(x)
#defining a function
def cal(x) :
print("x is ",x)
cal(10)
if "free" in txt:
print("yes it contains")
#slicing in string
b = "Hello, World!"
print(b[2:5]) # starting index and ending index Note: The search will start at index 2
(included) and end at index 5 (not included).
# Remember that the first item has index 0.
#Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
#The strip() method removes any whitespace from the beginning or the end:
a = "Hello"
b = "World"
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age)) #My name is John, and I am 36
print(txt,age) #My name is John, and I am {} 36
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
x = txt.splitlines()
print(x)
#The partition() method searches for a specified string, and splits the string into a tuple
containing three elements.
#Search for the word "bananas", and return a tuple with three elements:
"""
1 - everything before the "match"
2 - the "match"
3 - everything after the "match"
"""
print("trying partitioning ")
txt = "I could eat bananas all day"
x = txt.partition("bananas")
print(x)
#Use a mapping table to replace many characters:
a = "MyFolder"
b = "Demo002"
c = "2bring"
d = "my demo"
print(a.isidentifier()) #True
print(b.isidentifier()) #True
print(c.isidentifier()) #False
print(d.isidentifier()) #False
if a.strip("MyFolder"):
print("valid identifier ")
elif c.strip("2bring"):
print("not valid identifier ")
else:
print("nothing")
"""
> Greater than x > y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
"""
myList=["apple","mango","banana"]
print(myList)
#list constructor
myList=list(("apple","mango","banana"))
print(myList)
print(myList[1])
print(myList[-2]) # refering second last item
print(myList[0:3]) # retruns RANGE of Indexes
"""
Python Collections (Arrays) --- collections are heterogeneous in nature like
[1,"banana",True, 12.4]
There are four collection data types in the Python programming language:
Tuple is a collection which is ordered and unchangeable(can't insert values once tuple is
created). Allows duplicate members.
#("apple", "cherry","grapes") Tuples are written with round brackets.
o cd yes
#Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred
to by index or key.
#Once a set is created, you cannot change its items, but you can remove items and add
new items.
When we say that dictionaries are ordered, it means that the items have a defined order,
and that order will not change.
Unordered means that the items does not have a defined order, you cannot refer to an
item by using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
"""
print(thislist)
print(thislist)
age = 12
txt = "My name is John, and I am"
print(txt,age)
# Use the format() method to insert numbers into strings: Formats specified values in a
string
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered."""
mylist = ["apple","mango","banana","kiwi"]
for x in mylist:
print(x)
mylist_new = ["apple","mango","banana","kiwi"]
i=0
while i < len(mylist_new):
print(mylist_new[i])
i=i+1
print("printing on string")
my="paaye"
print(len(my)) # returns 5
#print(range(my)) # string object cannot be interpreted as an integer
print(range(len(my))) # retruns 5
for x in fruits:
if "an" in x:
newlist.append(x)
print(newlist)
# negative indexing
myStr = "myStr"
print("mystr",myStr[-5:-1]) # prints tSym ... last char doesnt get printed
#This example returns the items from index -4 (included) to index -1 (excluded)
"""
Reverse the string "Hello World" using slicing
"""
txt = "Hello World"[::-1] # [::-1] is used to reverse a string
print("txt is ",txt)
print(fruits[0][::-1][0:2])
a=10
b=20
if(a>b):
print("a is greater")
elif(b>a):
print("b is greater")
else:
print("they are equal")
c=12.3
a=c
print("a is ",a)
"""
Operator
Description
Syntax
=
Add and Assign: Add right side operand with left side operand and then assign to left
operand a += b
-=
Subtract AND: Subtract right operand from left operand and then assign to left operand:
True if both operands are equal a -= b
*=
Multiply AND: Multiply right operand with left operand and then assign to left operand
a *= b
/=
Divide AND: Divide left operand with right operand and then assign to left operand
a /= b
%=
Modulus AND: Takes modulus using left and right operands and assign result to left
operand a %= b
//=
Divide(floor) AND: Divide left operand with right operand and then assign the
value(floor) to left operand a //= b
**=
Exponent AND: Calculate exponent(raise power) value using operands and assign value
to left operand a **= b
&=
Performs Bitwise AND on operands and assign value to left operand a &= b
|=
Performs Bitwise right shift on operands and assign value to left operand a >>= b
<<=
Performs Bitwise left shift on operands and assign value to left operand a <<= b
"""
a=3
b=5
# a = a ** b
a=3
b=5
# a = a ** b
a **= b
print(a)
"""
Operator Example Meaning
& a & b Bitwise AND #1-1 then 1 ##advocates 1
| a | b Bitwise OR # 1-0 or 0-1 then 1 , only 1 is enough to set 1 ## highly
advocates 1
^ a ^ b Bitwise XOR (exclusive OR) ##if both are 1 or both are 0) it is set to 0
#same same puppy shame # treats equally
~ ~a Bitwise NOT ## inverts all the bits
<< a << n Bitwise left shift
>> a >> n Bitwise right shift
The & operator compares each bit and set it to 1 if both are 1, otherwise it is set to 0:
6 = 0000000000000110
3 = 0000000000000011
--------------------
2 = 0000000000000010
====================
The | operator compares each bit and set it to 1 if one or both is 1, otherwise it is set to 0:
6 = 0000000000000110
3 = 0000000000000011
--------------------
7 = 0000000000000111
====================
"""
w=10001
w<<w
print(w)
"""
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Operator Description
+ Unary plus operator; indicates positive value (numbers are positive without this,
however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical complement operator; inverts the value of a boolean
The following program, UnaryDemo, tests the unary operators:
class UnaryDemo {
result--;
// result is now 0
System.out.println(result);
result++;
// result is now 1
System.out.println(result);
result = -result;
// result is now -1
System.out.println(result);
"""
"""
Python Logical Operators
Logical operators are used to combine conditional statements: --must read
The And operator is used to verify where both conditions associated with it are True
Simultaneously.
print(x)
Create a new tuple with the value "orange", and add that tuple:
print(thistuple)
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
Packing a tuple:
Unpacking a tuple:
"""
Loop Through the Index Numbers
You can also loop through the tuple items by referring to their index number.
Example
Print all items by referring to their index number:
or
print(mytuple)
"""
"""------set {}----------"
A set is a collection which is unordered, unchangeable*, and unindexed.
* Note: Set items are unchangeable, but you can remove items and add new items.
print(thisset)
"""
""""
print(thisset)
Add Sets
To add items from another set into the current set, use the update() method.
Example
Add elements from tropical into thisset:
thisset.update(tropical)
print(thisset)
The union() method returns a new set with all items from both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
set1.update(set2)
print(set1)
note: Both union() and update() will exclude any duplicate items. --union is best because
sometimes upon run update() is producing None
Example
Keep the items that exist in both set x, and set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
The intersection() method will return a new set, that only contains the items that are
present in both sets.
Example
Return a set that contains the items that exist in both set x, and set y:
z = x.intersection(y)
Example
Remove the items that are present in both sets, AND insert the items that is not present in
both sets:
x.symmetric_difference_update(y)
The symmetric_difference() method will return a new set, that contains only the elements
that are NOT present in both sets.
Example
Return a set that contains all items from both sets, except items that are present in both:
z = x.symmetric_difference(y)
"""
Dictionary
Dictionaries are used to store data values in key:value pairs.
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
Dictionaries are written with curly brackets, and have keys and values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict) ## {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
"""The keys() method will return a list of all the keys in the dictionary.
Example
Get a list of the keys:"""
x = thisdict.keys()
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.keys()
Example
Add a new item to the original dictionary, and see that the keys list gets updated as well:
"""
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
car["color"] = "white"
"""Get Values
The values() method will return a list of all the values in the dictionary.
Example
Get a list of the values:"""
x = thisdict.values()
"""
The items() method will return each item in a dictionary, as tuples in a list.
Example
Get a list of the key:value pairs"""
x = thisdict.items()
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.items()
print(x) ## dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
"""Escape Characters
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded by
double quotes:
ExampleGet your own Python Server
You will get an error if you use double quotes inside a string that is surrounded by double
quotes:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
car["color"] = "red"
Example
Check if "model" is present in the dictionary:"""
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
"""Removing Items
There are several methods to remove items from a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
"""
Example
The popitem() method removes the last inserted item (in versions before 3.7, a random
item is removed instead):
"""
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
"""Example
The del keyword removes the item with the specified key name:"""
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"] # or del thisdict
print(thisdict)
"""Example
The clear() method empties the dictionary:"""
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict) # prints {}
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.values():
print(x,"_values")
for x in thisdict:
print(end='\n')
print(thisdict[x]) #prints value
print(thisdict.get(x)) #prints value
'''
dict syntax is dictname = {k1:v1,k2:v2,k3:v3}
nested dict syntax is dictname ={k1:{a1:b1,a2:b2},k2:{c1:d1,c2:d2},k3:{e1:f1,e2:f2}}
'''
Neha1 = {
"personal":"Good", #key1:value1
"professional":"Balanced", #key2=value2
"family":"Yes" #ket3=value3
}
print(Neha1, end='\n')
Neha = {
"personal":{"age":32, "color":"fair","height":"157","weight":80}, #key1:value1
"professional":{"occupation":"data_engineering","job_type":"white_collar"},
#key2=value2
"family":{"parents":True,"Brothers":True,"Sisters":False} #ket3=value3
}
print(Neha,end='\n')
Example
Create three dictionaries, then create one dictionary that will contain the other three
dictionaries:
"""
Neha = {
"personal":personal,
"professional":professional,
"family": family
}
i=0
while i < 8:
i += 1
if i == 3:
continue # continue means special treatment if u see this condition means this
condition needs to be skipped .. execution rules halt ..
print("3 not found alas") #jump directly to the next iteration.
if i== 7:
break # breaks on that condition and terminates execution going forward ...
print(i)
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.
"""
The range() Function
To loop through a set of code a specified number of times, we can use the range()
function,
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
"""
for x in range(10):
print(x)
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
Print each adjective for every fruit:"""
for x in adj:
for y in fruits:
print(x, y)
""" prints
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry"""
"""
The range() function defaults to increment the sequence by 1, however it is possible to
specify the increment value by adding a third parameter: range(2, 30, 3):
Example
Increment the sequence with 3 (default is 1):"""
for x in range(2, 30, 3):
print(x)
"""Calling a Function
To call a function, use the function name followed by parenthesis:
Example"""
def my_function():
print("Hello from a function")
my_function()
A parameter is the variable listed inside the parentheses in the function definition.
This way the function will receive a tuple of arguments, and can access the items
accordingly:
If the number of arguments is unknown, add a * before the parameter name: """
def my_function(*kids):
print("The youngest child is " + kids[2])
def neha_cal(*listargs):
for x in listargs:
print(x)
listofnames=["she","he","her","him","himself"]
neha_cal(listofnames)
"""prints
The youngest child is Linus
['she', 'he', 'her', 'him', 'himself']
"""
"""Keyword Arguments
You can also send arguments with the key = value syntax.
Example"""
Example"""
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
Example"""
def my_function(food):
for x in food:
print(x)
my_function(fruits)
"""prints
apple
banana
cherry
"""
Example"""
def myfunction():
pass
A lambda function can take any number of arguments, but can only have one expression.
"""
"""
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous function
inside another function.
Say you have a function definition that takes one argument, and that argument will be
multiplied with an unknown number:
"""
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
# ----------Python Arrays
"""Note: Python does not have built-in support for Arrays, but Python Lists can be used
instead.
Arrays
Note: This page shows you how to use LISTS as ARRAYS, however, to work with
arrays in Python you will have to import a library, like the NumPy library.
"""
#------------Python Classes/Objects----------
Create Object
"""
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
"""To understand the meaning of classes we have to understand the built-in __init__()
function.
All classes have a function called __init__(), which is always executed when the class is
being initiated.
Use the __init__() function to assign values to object properties, or other operations that
are necessary to do when the object is being created:
Example
Create a class named Person, use the __init__() function to assign values for name and
age:
"""
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
# Note: The __init__() function is called automatically every time the class is being used
to create a new object. --as good as constructor in java
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
"""Example
The string representation of an object WITH the __str__() function:"""
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
"""
Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the
object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
"""Note: The self parameter is a reference to the current instance of the class, and is used
to access variables that belong to the class."""
"""
The self Parameter
The self parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class.
"""
"""
Traceback (most recent call last):
The sequence of function calls that led to the error, starting with the outermost function
and going deeper into the call stack.
"""
A lambda function can take any number of arguments, but can only have one expression.
Syntax
lambda arguments : expression
The expression is executed and the result is returned:
"""---------Python Arrays-------------------
Note: Python does not have built-in support for Arrays, but Python Lists can be used
instead.
Python Arrays
Note: Python does not have built-in support for Arrays, but Python Lists can be used
instead.
Arrays
Note: This page shows you how to use LISTS as ARRAYS, however, to work with
arrays in Python you will have to import a library, like the NumPy library.
NumPy Tutorial
[+:
NumPy is a Python library.
import numpy as np
print(arr)
print('shape of array :', arr.shape)
"""output
[[[1 2 3 4]]]
shape of array : (1, 1, 4)
"""
Example
Convert the array into a 1D array:""""
import numpy as np
newarr = arr.reshape(-1)
print(newarr)
import numpy as np
for x in arr:
print(x)
"""
Iterate on the elements of the following 2-D array:"""
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
for x in arr:
print(x)
"""
If we iterate on a n-D array it will go through n-1th dimension one by one.
To return the actual values, the scalars, we have to iterate the arrays in each
dimension."""
import numpy as np
for x in arr:
for y in x:
print(x,y)
"""
output
[1 2 3] 1
[1 2 3] 2
[1 2 3] 3
[4 5 6] 4
[4 5 6] 5
[4 5 6] 6 """
"""
Iterating 3-D Arrays
In a 3-D array it will go through all the 2-D arrays.
Example
Iterate on the elements of the following 3-D array: """
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
for x in arr:
print(x)
"""
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
[[ 7 8 9]]
[[10 11 12]]]
"""
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
for x in arr:
for y in x:
for z in y:
print(z)
# best
import numpy as np
arr = np.array([[[[1, 2]]], [[[3, 4]]], [[[5, 6]]], [[[7, 8]]]]) # 4D array iteration
for x in np.nditer(arr):
print(x)
"""
1
2
3
4
5
6
7
8
"""
# ------ best to iterating through any 3-d ,4-d ,5-d array ----------#
"""Iterate through the following 3-D array:"""
import numpy as np
for x in np.nditer(arr):
print(x)
NumPy does not change the data type of the element in-place (where the element is in
array) so it needs some other space to perform this action, that extra space is called
buffer, and in order to enable it in nditer() we pass flags=['buffered'].
Example
Iterate through the array as a string:"""
"""
NumPy (Numerical Python) is one of the most commonly used packages for scientific
computing in Python.
It provides a multidimensional array object (n-dimensional array, denoted ndarray), as
well as
variations such as masks and matrices, which can be used for various mathematical
operations on
numerical datatypes (dtypes). Python numpy is compatible with, and used by many
other popular Python packages,
including pandas and matplotlib.
"""
import numpy as np
# --- bytes
""" b'1'
<class 'numpy.ndarray'>
b'2'
<class 'numpy.ndarray'>
b'3'
<class 'numpy.ndarray'>"""
import numpy as np
arr1=np.append(arr,"tree")
print(arr1)
import numpy as np
print(arr)
"""
if axis=1
[[1 2 5 6]
[3 4 7 8]]
if axis =0
[[1 2]
[3 4]
[5 6]
[7 8]]
"""
"""
We pass a sequence of arrays that we want to join to the stack() method along with the
axis.
If axis is not explicitly passed it is taken as 0.
"""
import numpy as np
arr3 =np.array([7,8,9])
print(arr_row)
print(end="\n")
print(arr_col)
""""
[[1 4 7]
[2 5 8]
[3 6 9]]
[[1 2 3]
[4 5 6]
[7 8 9]] """
import numpy as np
print(newarr)
"""
[array([1, 2]), array([3, 4]), array([5]), array([6])]
import numpy as np
newarr = np.array_split(arr, 3)
print(newarr[0])
print(newarr[1])
print(newarr[2])
"""prints
[1 2]
[3 4]
[5 6] """
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]])
newarr = np.array_split(arr, 3)
print(newarr)
import numpy as np
x = np.where(arr == 4)
print(x)
import numpy as np
x = np.where(arr%2 == 0)
print(x)
"""
Search Sorted
There is a method called searchsorted() which performs a binary search in the array, and
returns the index
where the specified value would be inserted to maintain the search order."""
import numpy as np
x = np.searchsorted(arr, 7)
print(x)
"""Example explained: The number 7 should be inserted on index 1 to remain the sort
order."""
import numpy as np
print(x)
"""The return value is an array: [1 2 3] containing the three indexes where 2, 4, 6 would
be inserted in the
original array to maintain the order."""
Example
Create a filter array that will return only values higher than 42:"""
import numpy as np
newarr = arr[filter_arr]
print(filter_arr)
print(newarr)
"""
[False, False, True, True]
[43 44]"""
import numpy as np