0% found this document useful (0 votes)
49 views

Pythin Learnings

The document discusses Python data types, strings, lists, functions, and other core concepts. It provides examples of: 1) Defining variables of different data types like integers, floats, strings, booleans, and None. It also demonstrates unpacking values from lists. 2) Common string operations like indexing, slicing, formatting, searching, and modifying strings. 3) List operations like accessing elements, slicing, modifying, iterating and more. It also discusses the different collection data types in Python. 4) Basic functions like defining, calling and passing parameters to functions. 5) Operators, conditions and loops like for, while to iterate over items.

Uploaded by

Neha Khatri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Pythin Learnings

The document discusses Python data types, strings, lists, functions, and other core concepts. It provides examples of: 1) Defining variables of different data types like integers, floats, strings, booleans, and None. It also demonstrates unpacking values from lists. 2) Common string operations like indexing, slicing, formatting, searching, and modifying strings. 3) List operations like accessing elements, slicing, modifying, iterating and more. It also discusses the different collection data types in Python. 4) Basic functions like defining, calling and passing parameters to functions. 5) Operators, conditions and loops like for, while to iterate over items.

Uploaded by

Neha Khatri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 51

import pandas as pd

import random

a=4
b,c,d=5,"neha",12.04
flag =True # boolean datatype
if(flag==True):
print(flag)

# Declaring a None variable


var = None
"""
Interesting Facts
None is not the same as False.
None is not 0.
None is not an empty string.
Comparing None to anything will always return False except None itself.
"""

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

fruits = ["apple", "banana", "cherry"]


x, y, z = fruits
print(x)
print(y)
print(z)

print(x, y, z)
print(x+y+z)

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

Text Type: str


Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType

"""
# to get type of a var
print(type(x))

print(random.randrange(1,3))

#String Strings are Arrays of char


#strings in Python are arrays of bytes representing unicode characters.
a = "Hello, World!"
print(a[4])

# iterating through a loop


for x in a:
print(x)

for x in "neha":
print(x)

#defining a function
def cal(x) :
print("x is ",x)

cal(10)

#searching a part of string


txt = "The best things in life are free!"
print("free" in txt)

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 the start to position 5 (not included):


b = "Hello, World!"
print(b[:5])

#Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])

#Negative Indexing means starting from last end of the string

#Get the characters:


#From: "o" in "World!" (position -5)
#To, but not included: "d" in "World!" (position -2):

b = "Hello, World! you are free to take anything from here"


print("starting from end of string")
print(b[2:-3])
print(b[-5:-9]) # won't work as starting point is after end point
print(b[-9:-5]) # it will print as starting point is before end point

#The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"

a = "Hello"
b = "World"

print(a + " " + b)


#String Format
#As we learned in the Python Variables chapter, we cannot combine strings and numbers
like this:

#Use the format() method to insert numbers into strings:

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

#Split a string into a list where each line is a list item:

txt = "Thank you for the music\nWelcome to the jungle"

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:

txt = "Hi Sam!"


x = "mSa"
y = "eJo"
mytable = str.maketrans(x, y)
print(txt.translate(mytable))

w = 23 #not a valid variable/ identifier

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:

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


["apple",12,"grapes"].Lists are created using square brackets:
## because list is indexed ([0],[1] n so on ) that means it elements are ordrered since it is
changable(as we can insert values at postions like [3][10]) that means it allows
duplicates..
ocd yes

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

Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate


members.
# A set is a collection which is unordered, unchangeable*, and unindexed.

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

Dictionary is a collection which is ordered** and changeable. No duplicate members.


Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.

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.

"""

thislist = ["apple", "banana", "cherry"]

thislist[1:2] = ["blackcurrant", "watermelon","watermelon","watermelon"] # "banana" is


getting replaced by whole thislist

print(thislist)

thislist = ["apple", "banana", "cherry"]

thislist[1:5] = ["blackcurrant", "watermelon","watermelon","watermelon"] # no


exception is thrown even if index is out of bound "banana" & "cheery "ll be replaced by
whole thislist..

print(thislist)

# element finding in string -- type 1


str= "Hello world"
for x in str:
if(x=='r'):
print(" it contains")
else:
print("does not contain")

# element finding in string -- type 2


if "r" in str:
print(" yes it has ")

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

"""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, unchangeable*, and unindexed. No duplicate
members.
Dictionary is a collection which is ordered** and changeable. No duplicate members.
*Set items are unchangeable, but you can remove and/or add items whenever you like.

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

thislist = ["1apple", "2wbanana", "3qcherry"]


#for i in range(len(thislist)):
for i in range(len(thislist)):
print(thislist[i]) # prints 1apple 2wbanana 3qcherry

print(" ######### range(len()) ######### ")


thislist = ["apple", "banana", "cherry"]
#for i in range(len(thislist)):
print(len(thislist)) # retruns 3
#print(range(thislist)) # error 'list' object cannot be interpreted as an integer
print(range(len(thislist))) # returns range(0, 3)

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

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]


newlist = []

for x in fruits:
if "an" in x:
newlist.append(x)

print(newlist)

"""What is the position of the value "cherry":"""


fruits = ['apple', 'banana', 'cherry']
x = fruits.index("cherry")

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[-4:-1]) # returns ['orange', 'kiwi', 'melon'] ## prints reverse RANGE of
INDEX

# negative indexing
myStr = "myStr"
print("mystr",myStr[-5:-1]) # prints tSym ... last char doesnt get printed

print("myStr using slicing",myStr[::-1]) #right approch

fruits = ['apple', 'banana', 'cherry']


print(fruits[::-1]) #reverses the collection
fruits.reverse() #reverses the collection

#Negative indexing means startinsg from the end of the list.

#This example returns the items from index -4 (included) to index -1 (excluded)

#Remember that the last item has the index -1,

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

"""Reversing a list/string using negetive indexing """


fruits = ["apple", "banana", "cherry"]
print(fruits[-0]) # prints apple 1st element [0] and [-0] prints the same ......
print(fruits[0]) # prints apple
print(fruits[-2]) # prints banana

"""Python iter() Function


Create an iterator object, and print the items:"""

x = iter(["apple", "banana", "cherry"])


print(next(x)) #prints "apple"
print(next(x)) #prints "banana"
print(next(x)) #prints "cherry"

"""Python List sort() Method"""


def myFunc():
return 0
list.sort(reverse=True|False, key=myFunc)

cars = ['Ford', 'Mitsubishi', 'BMW','Volvo' ,'VW']

cars.sort() # sorts in alphabatical ascending order same as cars.sort(reverse=False)


['BMW', 'Ford', 'Mitsubishi', 'VW', 'Volvo']
print(cars)
cars.sort(reverse=True) # sorts in alphabatical descending order prints ['Volvo', 'VW',
'Mitsubishi', 'Ford', 'BMW']
print(cars)
cars.sort(reverse=False) #prints in aplhabactical ascending ['BMW', 'Ford', 'Mitsubishi',
'VW', 'Volvo']
print(cars)

#---- custom sorting -----


def my_func(e):
return len(e)

cars.sort(key=my_func) # prints alphabatically ascending length order ['VW', 'BMW',


'Ford', 'Volvo', 'Mitsubishi']
print(cars)
cars.sort(reverse=True,key=my_func) # prints alphabatically ascending length order
['Mitsubishi', 'Volvo', 'Ford', 'BMW', 'VW']
print(cars)

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
=

Assign value of right side of expression to left side operand x=y+z


+=

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 OR on operands and assign value to left operand a |= b


^=
Performs Bitwise xOR 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

operand is an information thing on which an operator act. Let’s take an example: +A


(where + symbol is an operator) and A.
An operator may have a couple of operands. An operand is one of the sources of info
(contentions) of an operator.
Those operators that work with just a single operand are called unary operators. Consider
the function f: A → A,
where A will be a set. The function f is a unary activity on A.

The Unary Operators --- must read


The unary operators require only one operand; they perform various operations such as
incrementing/decrementing a value by one, negating an expression, or inverting the value
of a boolean.

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 {

public static void main(String[] args) {

int result = +1;


// result is now 1
System.out.println(result);

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

boolean success = false;


// false
System.out.println(success);
// true
System.out.println(!success);
}
}

he increment/decrement operators can be applied before (prefix) or after (postfix) the


operand. The code result++; and ++result; will both end in result being incremented by
one. The only difference is that the prefix version (++result) evaluates to the incremented
value, whereas the postfix version (result++) evaluates to the original value. If you are
just performing a simple increment/decrement, it doesn't really matter which version you
choose. But if you use this operator in part of a larger expression, the one that you choose
may make a significant difference.

The following program, PrePostDemo, illustrates the prefix/postfix unary increment


operator:
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
}
}

"""

"""
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.

Operator Description Example Try it


and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
"""

""""-------------How to chnage a tuple ?----------------------


Convert the tuple into a list to be able to change it:

x = ("apple", "banana", "cherry")


y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)

Create a new tuple with the value "orange", and add that tuple:

thistuple = ("apple", "banana", "cherry")


y = ("orange",)
thistuple += y

print(thistuple)

Convert the tuple into a list, remove "apple", and convert it back into a tuple:

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)

The del keyword can delete the tuple completely:

thistuple = ("apple", "banana", "cherry")


del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists..

Packing a tuple:

fruits = ("apple", "banana", "cherry")


But, in Python, we are also allowed to extract the values back into variables. This is
called "unpacking":

Unpacking a tuple:

fruits = ("apple", "banana", "cherry","grapes","watermelon")


(green, yellow, *red,violet) = fruits # or green, yellow, red = fruits for list [green,
yellow, red] = fruits or green, yellow, red = fruits
astrick * to collect more than one items
prints
apple
bananna
['cherry', 'grapes']
watermelon

fruits = ["apple", "banana", "cherry"]


x=None
for i in fruits:
x=i
x=x+"_ch"
print(x)
"""

"""
Loop Through the Index Numbers

You can also loop through the tuple items by referring to their index number.

Use the range() and len() functions to create a suitable iterable.

Example
Print all items by referring to their index number:

thistuple = ("apple", "banana", "cherry")


for i in range(len(thistuple)):
print(thistuple[i])

or

thistuple = ("apple", "banana", "cherry")


for i in thistuple:
print(i)

Multiple tuples :--


Multiply the fruits tuple by 2:
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2

print(mytuple)

fruits = ["apple", "banana", "cherry","apple"]

print(fruits.count("apple")) # counts the no of apple 2


print(fruits.index("apple")) # searches the index of apple returns 0

"""

"""------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.

Sets are written with curly brackets.

True and 1 is considered the same value:

thisset = {"apple", "banana", "cherry", True, 1, 2}

print(thisset)
"""

""""

------- set -------------

Add an item to a set, using the add() method:

thisset = {"apple", "banana", "cherry"}


thisset.add("orange")

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 = {"apple", "banana", "cherry"}


tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)

print(thisset)

it can be any iterable object (tuples, lists, dictionaries etc.).

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)

The update() method inserts the items in set2 into set1:


set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

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

Keep ONLY the Duplicates


The intersection_update() method will keep only the items that are present in both sets.

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)

print(x) ##prints "apple"

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:

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

z = x.intersection(y)

print(z) ##prints "apple"

All, But NOT the Duplicates ## note :: symmetric_difference_update() is equalant to


intersaction()
The symmetric_difference_update() method will keep only the elements that are NOT
present in both sets.

Example
Remove the items that are present in both sets, AND insert the items that is not present in
both sets:

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

x.symmetric_difference_update(y)

print(x) ## {'microsoft', 'cherry', 'google', 'banana'}

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:

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

z = x.symmetric_difference(y)

print(z) ## {'google', 'banana', 'microsoft', 'cherry'}

"""

""" -------- Dictionary {}---------

Dictionary
Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow duplicates.

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:

Print the "brand" value of the dictionary:"""

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])

"""Duplicate values will overwrite existing values:"""

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict) ## {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

"""String, int, boolean, and list data types:


"""

thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}

"""Using the dict() method to make a dictionary:


"""

thisdict = dict(name = "John", age = 36, country = "Norway")


print(thisdict)

"""Get the value of the "model" key:"""


x = thisdict.get("brand")

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

print(x) ## dict_keys(['brand', 'model', 'year'])


"""
The list of the keys is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the keys list.
The list of the keys is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the keys list.

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

print(x) #before the change

car["color"] = "white"

print(x) #after the change

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

txt = "We are the so-called "Vikings" from the north."


txt = "We are the so-called \"Vikings\" from the north." """

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.items()

print(x) #before the change

car["color"] = "red"

print(x ,end="\n") #after the change


print("Hello", end='\n')
print("keys are ",car.keys(),end="\n")
print(car.values())

print("trying new line char",end='\n')


print("I AM \"NEHA\" buddy")
"""prints ##
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964), ('color', 'red')])
Hello
keys are dict_keys(['brand', 'model', 'year', 'color'])
dict_values(['Ford', 'Mustang', 1964, 'red'])
"""

"""trying new line char


I AM "NEHA" buddy

Check if Key Exists


To determine if a specified key is present in a dictionary use the in keyword:

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:

ExampleGet your own Python Server


The pop() method removes the item with the specified key name:"""

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
}

# ways to print all keys and values


print(thisdict.keys(),end='\n')
print(thisdict.values(), end='\n')

# option 1 to iterate through keys and values


for x in thisdict.keys():
print(x,"_keys")

for x in thisdict.values():
print(x,"_values")

# option 2 to iterate through keys and values


for x, y in thisdict.items():
print(x, y)

## option 3 to iterate through keys one by one


for x in thisdict:
print(end='\n')
print(x) # prints key

for x in thisdict:
print(end='\n')
print(thisdict[x]) #prints value
print(thisdict.get(x)) #prints value

### ----- nested dictionaries -----


#A dictionary can contain dictionaries, this is called nested dictionaries.

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

print("Nested Neha Keys",Neha.keys())


print("Nested Neha Values",Neha.values())
print("Nested Neha Items",Neha.items())
print("Nested Neha Get Professional job type ",Neha.get("professional").get("job_type"))
#accessing elements in a nested dict type 1
print("Nested Neha Get Professional job type ",Neha["professional"]["job_type"])
#accessing elements in a nested dict type 2

#---- 3 dictionaries within 1 ----


"""r, if you want to add three dictionaries into a new dictionary:

Example
Create three dictionaries, then create one dictionary that will contain the other three
dictionaries:

"""

personal = {"age":32, "color":"fair","height":"157","weight":80}


professional = {"occupation":"data_engineering","job_type":"white_collar"}
family= {"parents":True,"Brothers":True,"Sisters":False}

Neha = {
"personal":personal,
"professional":professional,
"family": family
}

print("added 3 dicts into Neha ",Neha)


## short hand description
a = 200
b = 330

if a > b: print("a is greater than b")


elif a==b: print("both are equal")
else: print("b is greater")

# the while loop


i=1
while i < 6:
print(i)
i += 1

"""Exit the loop when i is 3:"""

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)

# Note that number 3 is missing in the result and broken at 7


# Prints
#1
#2
#4
#5
#6

for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")

#If the loop breaks, the else block is not executed.


# Prints
#0
#1
#2

#####-------Python For Loops --------######


"""A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).

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.

ExampleGet your own Python Server


Print each fruit in a fruit list: """

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

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

for x in range(2, 6):


print(x) # prints 2,3,4,5
"""Nested Loops
A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example
Print each adjective for every fruit:"""

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

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

for x in [0, 1, 2]:


pass

# prints nothing at all


# having an empty for loop like this, would raise an error without the pass statement

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

"""From a function's perspective:

A parameter is the variable listed inside the parentheses in the function definition.

An argument is the value that is sent to the function when it is called."""

"""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.

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

my_function("Emil", "Tobias", "Linus")

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.

This way the order of the arguments does not matter.

Example"""

def my_function(child3, child2, child1):


print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

"""Default Parameter Value


The following example shows how to use a default parameter value.

If we call the function without argument, it uses the default value:

Example"""
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

"""Passing a List as an Argument


You can send any data types of argument to a function (string, number, list, dictionary
etc.), and it will be treated as the same data type inside the function.

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)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

"""prints
apple
banana
cherry
"""

"""The pass Statement


function definitions cannot be empty, but if you for some reason have a function
definition with no content, put in the pass statement to avoid getting an error.

Example"""
def myfunction():
pass

# lambda functions ------


"""A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one expression.

"""

x = lambda a, b, c : a + b + c # Syntax lambda arguments : expression


print(x(5, 6, 2))

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

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

#-----The __str__() Function

"""The string representation of an object WITHOUT the __str__() function:"""

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)

print(p1) # doesnt print anything

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

print(p1) # prints John(36)

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

print(p1)

"""
Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the
object.

Let us create a method in the Person class:


Example
Insert a function that prints a greeting, and execute it on the p1 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.
"""

""" ---------Python Lambda ----------------


A lambda function is a small anonymous function.

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:

ExampleGet your own Python Server


Add 10 to argument a, and return the result:"""
x = lambda a : a + 10
print(x(5))

"""---------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.

NumPy is used for working with arrays.

NumPy is short for "Numerical Python".

Create a NumPy ndarray Object


NumPy is used to work with arrays. The array object in NumPy is called ndarray.

We can create a NumPy ndarray object by using the array() function.


"""

## ------three dimentional array ------##

import numpy as np

arr = np.array([1, 2, 3, 4], ndmin=3)

print(arr)
print('shape of array :', arr.shape)

"""output
[[[1 2 3 4]]]
shape of array : (1, 1, 4)
"""

""""Flattening the arrays


Flattening array means converting a multidimensional array into a 1D array.

We can use reshape(-1) to do this.

Example
Convert the array into a 1D array:""""

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

newarr = arr.reshape(-1)

print(newarr)

"""Iterate on the elements of the following 1-D array:"""

import numpy as np

arr = np.array([1, 2, 3])

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

arr = np.array([[1, 2, 3], [4, 5, 6]])

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)

arr1 = np.array([[[1, 2, 3]], [[7, 8, 9]], [[10, 11, 12]]])


print(arr1)

"""
[[[ 1 2 3]
[ 4 5 6]]

[[ 7 8 9]
[10 11 12]]]

x represents the 2-D array:


[[1 2 3]
[4 5 6]]
x represents the 2-D array:
[[ 7 8 9]
[10 11 12]]
[[[ 1 2 3]]

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

arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

for x in np.nditer(arr):
print(x)

"""Iterating Array With Different Data Types


We can use op_dtypes argument and pass it the expected datatype to change the datatype
of elements while iterating.

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

arr = np.array([1, 2, 3])

for x in np.nditer(arr, flags=['buffered'], op_dtypes=['S']):


print(x)

# --- bytes
""" b'1'
<class 'numpy.ndarray'>
b'2'
<class 'numpy.ndarray'>
b'3'
<class 'numpy.ndarray'>"""

import numpy as np

arr=np.array(['apple', 'banana', 'cherry'])

arr1=np.append(arr,"tree")

print(arr1)

['apple' 'banana' 'cherry' 'tree']


"""Enumerated Iteration Using ndenumerate()
Enumeration means mentioning sequence number of somethings one by one.

Sometimes we require corresponding index of the element while iterating, the


ndenumerate() method can be used for those usecases.
"""
import numpy as np

arr = np.array([[[[1, 2, 3, 4]]],[[[5, 6, 7, 8]]]])

for idx, x in np.ndenumerate(arr):


if(x==4):
print(x)
"""
We pass a sequence of arrays that we want to join to the concatenate() function,
along with the axis. If axis is not explicitly passed, it is taken as 0.

Join two 2-D arrays along rows (axis=1):


"""

import numpy as np

arr1 = np.array([[1, 2], [3, 4]])

arr2 = np.array([[5, 6], [7, 8]])

arr = np.concatenate((arr1, arr2), axis=1)

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

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

arr3 =np.array([7,8,9])

arr_row = np.stack((arr1, arr2, arr3), axis=1)

print(arr_row)

print(end="\n")

arr_col = np.stack((arr1, arr2, arr3), axis=0)

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

arr = np.array([1, 2, 3, 4, 5, 6])


newarr = np.array_split(arr, 4)

print(newarr)

"""
[array([1, 2]), array([3, 4]), array([5]), array([6])]

Note: The return value is a list containing four arrays. """

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])

newarr = np.array_split(arr, 3)

print(newarr[0])
print(newarr[1])
print(newarr[2])
"""prints
[1 2]
[3 4]
[5 6] """

# splitting a 2-d arrays into 3 parts


import numpy as np

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)

""" returns list of 3 2-d arrays


[array([[1, 2, 3],[4, 5, 6]]),
array([[ 7, 8, 9], [10, 11, 12]]),
array([[13, 14, 15], [16, 17, 18]])]
"""
"""
Searching Arrays
You can search an array for a certain value, and return the indexes that get a match.

To search an array, use the where() method.

Find the indexes where the value is 4: """

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 4, 4])

x = np.where(arr == 4)

print(x)

"""Find the indexes where the values are even:"""

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

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

arr = np.array([6, 7, 8, 9])

x = np.searchsorted(arr, 7)
print(x)

"""Example explained: The number 7 should be inserted on index 1 to remain the sort
order."""

"""Find the indexes where the values 2, 4, and 6 should be inserted:"""

import numpy as np

arr = np.array([1, 3, 5, 7])

x = np.searchsorted(arr, [2, 4, 6])

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."""

"""Creating the Filter Array --must read it works differently here


In the example above we hard-coded the True and False values, but the common use is to
create a filter array based on conditions.

Example
Create a filter array that will return only values higher than 42:"""

import numpy as np

arr = np.array([41, 42, 43, 44])

# Create an empty list


filter_arr = []

# go through each element in arr


for element in arr:
# if the element is higher than 42, set the value to True, otherwise False:
if element > 42:
filter_arr.append(True)
else:
filter_arr.append(False)

newarr = arr[filter_arr]

print(filter_arr)
print(newarr)

"""
[False, False, True, True]
[43 44]"""

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

filter_arr = arr % 2 == 0 or arr>3


print(filter_arr)
newarr = arr[filter_arr] # standard to supply array of true false filtered value to another
array to get th ereal result
print(newarr)

"""[False True False True False True False]


[2 4 6]"""

You might also like