You are on page 1of 5

variableName = 10

floatingNumber = 10.63587
print(type(floatingNumber)) --> class 'float'
floatingNumber = int(floatingNumber) --> typecasting to int
print(type(floatingNumber)) --> int
print(floatingNumber) --> will print 10 - it entirely dismisses the decimal value

what are operators and their different type


+ -> addition operator
// -> quotient operator will be integer
% -> remainder
and , or , not(2<5)

string and how to define it


fruit = "Apple"
will be stored as sequence of characters
A - 0
p - 1
p - 2
l - 3
e - 4
fruit[-1] - it will return the last character
fruit[-2] - l

string = 'String is among python's data types' or Python\'s


invalid syntax - as python's has ended the string
we need to use double quote

String formatting
print("{} is a great programming language for
beginners".format(programminglanguage))
name = "John"
f'Good morning, {name}. How are you today?'

modify the string by assigning it again


fruit = "Banana"

string.upper()
string.lower()
string.replace("easy" , "powerful")

#slice -> string[0:6(index+1)] - will get Python

#length - computers the number of character - len(string)

LIST -
favFruits = ["apple","mango","strawberry"]
operators on the list

favFruits.append("Kiwi");
favFruits.insert(1,"Mango")
favFruits.remove("strawberry")
favFruits.sort() - sorts alphabetically or numberically based on the content

favFruits.reverse()
favFruits.pop() - will remove the last element
TUPLE - with normal bracket
is a collection of immutable(data cannot be changed) objects
historicalWarDate = (1914,1939)
historicalWarDate[1] = 2017 - does not support
del(historicalWarDate)
can create a new tuple from existing tuples
mytuple = (1,2,"hello") = can have multiple datatype
mytuple=("mouse",(1,2,3)) - nested tuple
my_tuple=3,4.6,"dog"
a,b,c = my_tuple
print(a) - 3
print(b) - 4.6
print(c) - dog

Dictionaries
collection of key value pair

#dictionaryname = {key1:value1,key2:value2}
priceOfCamera = {"sony" : 500 , "nikon" : 600 ,"canon" : 700}
priceOfCamera["sony"]

change the value of the key


priceOfCamera["nikon"] = 800 - will update the value

operations on dictionary
priceOfCamera.keys() - will get all the keys of the dictionary
priceOfCamera.values() - will get all the values of the keys
copyofpriceofcameras = priceOfCameras.copy()

del(priceOfCamera["sony"])
priceOfCamera.clear() - will return the empty the dictionary

conditional statements - an
if totalMarks >= 90: - begining of the line
print("congratulations") - should have indentation and the following lines
should have

the same indentation


else:
print("u have cleared")

else ifs
if totalMarks >= 90: - begining of the line
print("congratulations")
elif totalMarks >= 40:
print("u have cleared")
else:
print("u have failed")

nested if
if totalMarks >= 90: - begining of the line
print("congratulations")
if totalMarks = 100:
print("You have cleared with full marks")

print (5, not a == 7 and b == 7)


print (9, not a == 7 and b == 6)
we can use "in" operator
list = ["ajay","vijay","Ramesh"]
if 'vijay' in list:
print("vijay is there ")
while loop
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1

print ("End of while loop!")

number = int(input())

for loop
for fruit in fruits:block of statement that follows the
print (fruit)

numbers = [2, 3, 5]
getsum = [ i+2 for i in numbers ]
print (getsum)
[4,5,7]

numbers = [2, 3, 5]
getnum = [ i+2 for i in numbers if i<5]
print (getnum)
[4,5]

#range()
for number in range(1,10):
print(number)//1 to 9

while number<10

number = 1
for row in range(1,4,1):
for column in range(1,4):
print(number,end =' ')
number = number + 1
print()

Function
def myFirstFunction():
print("My first program")

myFirstFunction()

def printMax(a, b):


if a > b:
print(a, 'is maximum')
elif a == b:
print(a, 'is equal to', b)
else:
print(b, 'is maximum')

printMax(3, 4)
4 is maximum

def say(message, times = 1):


print(message * times)

say('Hello')
say('World', 5) - times has default value as 1 else it will print it 5 times

def func(a, b=5, c=10):


print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c=24)
func(c=50, a=100)

x = 50
def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)
func(x)
print('x is still', x)
x is 50
Changed local x to 2
x is still 50

Dictionary is hastable -key-value pair


dict = {} //curly braces for dictionary
dict['one'] = "this is one";
dict[2] = "this is two"
dict = {'name' : 'value','code':'value'}
dict.keys() or .values()

filehandling
set the working directory -
capmdata= open(workingdir+'capm_dem.txt','r')
print ("Content is ", capmdata.read())

newcapmdata = open(workingdir+'capm_dem.txt','r+')
newcapmdata.write ("Sold Value: " '235$')
capmdata.seek(0,0)
capmdata.close()
capmdata.close()
print(newcapmdata.read())

numPy - scientific calculations


pandas
import numPy
import pandas ===> dataframes ==>providing fast, flexible, and expressive data
structures designed to make working with relational or labeled data both easy
and intuitive.
import beautiful- web crawling
Exception handling

def avg( numList ):


"""Raises TypeError or ZeroDivisionError exceptions."""
sum = 0
for v in numList:
sum = sum + v
return float(sum)/len(numList)

def avgReport(numList):
try:
m= avg(numList)
print ("Average = ", m)
except TypeError as ex:
print ("TypeError:", ex)
except ZeroDivisionError as ex:
print ("ZeroDivisionError:", ex)
finally://always executed
print("Finished avgReport")

list1 = [10,20,30,40] # If used this should run fine


list2 = [] # If used this is empty, it would throw
ZeroDivisionError
list3 = [10,20,30,'abc'] # If used this should throw TypeError

try...finally
MemoryError - ram size and lot of dictionary values

key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u',


'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c',
'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',
'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S',
'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A',
'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 'W':'J',
'X':'K', 'Y':'L', 'Z':'M'}
str = "Pnrfne pvcure zrgubq vf anzrq nsgre Whyvhf Pnrfne"
i=0
output = ""
for i in str:
if i in key.values():
output += key[i]
else:
output += i
print(output)

You might also like