0% found this document useful (0 votes)
9 views28 pages

Crash Course On Python

Uploaded by

Nithish Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
9 views28 pages

Crash Course On Python

Uploaded by

Nithish Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 28

Crash Course On

Python
By Google
Short Notes By Nithish
Week 1:

<-> Python Can Be Your Calculator:


 4+5=9
 9*7=63
 3**2=9
 3/2=1.5
 3//2=1
Week 2:

<-> Data Types:


 type(“a”)  string

<-> Variables:
 EX: length=4
width=5
area=length*width
<->Expressions , Numbers and Type conversions:
->Implicit Conversion:
 The interpreter automatically converts one data type into another
 EX: print(1+1.5)2.5 [ // Interpreter converts int 1 to float ]
print(1+”1.5”)Error
->Explicit Conversion :
 The type conversion to be done by us by our need
 EX: print(1+int(“1.5”)) 2.5[//We type casted string into int]
.

<-> Defining Functions:


 We use def keyword to define a function
 EX: def greetings(name):
print(“Welcome, “ + name)
greetings(“Nithish”)  “Welcome, Nithish”
<-> Returning Values:
 EX: def convert_seconds(seconds):
hours = seconds//3600
minutes = (seconds-hours*3600)//60
remaining_seconds = seconds-hours*3600-minutes*60
return hours , minutes , remaining_seconds
hours , minutes , seconds = convert_seconds(5000)
.
 <->Conditionals:
 EX: def isEven(num):
if(num % 2 == 0):
print(“Even”)
elif(num % 2 == 1):
print(“Odd”)
else:
print(“Invalid”)
isEven(24)  “Even”
Week 3:

<-> While Loops:


 EX: x=0
while x < 5:
print(x)
x += 1
 Output:: 0
1
2
3
4
.

<-> For Loops :


 EX: 1 : for i in range(4):
print(“Hello World”)
 Output: “Hello World”
“Hello World”
“Hello World”
“Hello World”

 EX: 2 : for x in range(1,10,2):


print(x , end=“ “)
 Output: 1 3 5 7 9
Week 4:
 <->String Operations:
 len(string) Returns the length of the string
 for character in string Iterates over each character in th
e string
 if substring in string Checks whether the substring is par
t of the string
 string[i] Accesses the character at index i of the string,
starting at zero
 string[i:j] Accesses the substring starting at index i, en
ding at index j -
1. If i is omitted, it's 0 by default. If j is omitted, it
’s
len(string) by default
.

 <->String Methods:
 string.lower() / string.upper() Returns a copy of the string with all
lower / upper case characters
 string.lstrip() / string.rstrip() / string.strip() Returns a copy of
the string without left / right / left or right whitespace
 string.count(substring) Returns the number of times substring is pres
ent in the string
 string.isnumeric() Returns True if there are only numeric characters
in the string. If not, returns False.
 string.isalpha() Returns True if there are only alphabetic characters
in the string. If not, returns False.
 string.split() / string.split(delimiter) Returns a list of substrings
that were separated by whitespace / delimiter
 string.replace(old, new) Returns a new string where all occurrences o
f old have been replaced by new.
 delimiter.join(list of strings) Returns a new string with all the str
ings joined by the delimiter
.
<-> Strings :
 EXAMPLES:
 name="Nithish Kumar“
 (1).print(name[3:6])  “his”
 (2).print(name*3)  “Nithish KumarNithish KumarNithish
Kumar”
 (3).print(len(name))  13
 (4).print(name[-1] ,name[-2],name[-5])  “r” “a” “k”
 (5).print(name[3:])  “hish Kumar”
 (6).print(name.index("h"))  3
 (7).print( "Nit" in name )  True
 (8).print(name.upper())  “NITHISH KUMAR”
 (9).print(name.lower())  “nithish kumar”
 (10).print("
. chinni ".strip())  “chinni”
 (11).print(" chinni ".lstrip())  “chinni “
 (12).print(" chinni ".rstrip())  “ chinni”
 (13).print(name.count("i"))  2
 (14).print(name.endswith("mar"))  True
 (15).print("123984".isnumeric())  True
 (16).print(" Ni ".join(["This","a","b","c","d"]))
 ”This Ni a Ni b Ni c Ni d”
 (17).print("This is a example of split method".split())
 [“This” , ”is” , “a” , “example” , “of” , “split” , “method”]
 number=len(name)*3
 (18).print("Hello {}, your lucky num is {}".format(name,number))
 ”Hello Nithish Kumar, your lucky num is 39”
 (19).print("Hello {name}, your lucky num is {num}".format(name=name,num=len(name
)*3))
 ”Hello Nithish Kumar, your lucky num is 39”
Formatting Expressions:
 {:d} integer value '{:d}'.format(10.5) → '10'
 {:.2f} floating point with that many decimals '{:.2f}'.f
ormat(0.5) → '0.50'
 {:.2s} string with that many characters '{:.2s}'.f
ormat('Python') → 'Py'
 {:<6s} string aligned to the left that many spaces '{
:<6s}'.format('Py') → 'Py '
 {:>6s} string aligned to the right that many spaces '{
:>6s}'.format('Py') → ' Py'
 {:^6s} string centered in that many spaces '{:^6s}'.f
ormat('Py') → ' Py '
Lists:
 EXAMPLES:
 friends=['Nithish','Kumar','Sahash','Chinni','Santhu']
 (1).for friend in friends:
 print("Hi "+friend)
 (2).print(friends[1])  “Kumar”
 (3).print(friends[2:])  “[“Sahash” , ”Chinni” , ”Santhu”]
 (4).print(len(friends))  5
 (5).print(friends[-3])  “Sahash”
 (6).print(friends.index("Kumar"))  1
 (7).print('Sahash' in friends)  True
 (8).print(friends[1].upper())  “KUMAR”
 (9).print(friends[2].lower())  “SAHASH”

. (10).friends.append("Ash")
 print(friends)  [“Nithish” , “Kumar” , “Sahash” ,
“Chinni” , “Santhu” , “Chinni”]
 (11).friends.insert(1,"Pikachu")
 print(friends)
 (12).friends.remove("Pikachu")
 print(friends)
 (13).friends.pop(3)
 print(friends)
 winners=[ “Nithish” , ”Prem” , ”saiki”]
for index , person in enumerate(winners):
print(“ {} – {} “.format(index+1,person))
Output:
1 – “Nithish”
2 – “Prem”
3 – “saiki”
EX: multiples = [x*7 for x in range(1,11)] {//List Comprehensions}
print(multiples)  [7,14,21,28,35,42,49,56,63,70]
<->Tuple:

 As we mentioned earlier, strings and lists are both exampl


es of sequences. Strings are sequences of characters, and
are immutable. Lists are sequences of elements of any data
type, and are mutable. The third sequence type is the tup
le. Tuples are like lists, since they can contain elements
of any data type. But unlike lists, tuples are immutable.
They’re specified using parentheses instead of square bra
ckets.
 EX: tuplee=("Mango","Banana","Orange")
print(type(tuplee))  Tuple
Lists and Tuples Operations Cheat
Sheet:
 <->Commom Sequence Operations:
 len(sequence) Returns the length of the sequence
 for element in sequence Iterates over each element in the seque
nce
 if element in sequence Checks whether the element is part of th
e sequence
 sequence[i] Accesses the element at index i of the sequence, st
arting at zero
 sequence[i:j] Accesses a slice starting at index i, ending at i
ndex j-
1. If i is omitted, it's 0 by default. If j is omitted, it's le
n(sequence) by default.
 for index, element in enumerate(sequence) Iterates over both th
e indexes and the elements in the sequence at the same time
.

 <->List Specific Operations and Methods:


 list[i] = x Replaces the element at index i with x
 list.append(x) Inserts x at the end of the list
 list.insert(i, x) Inserts x at index i
 list.pop(i) Returns the element a index i, also removing it fro
m the list. If i is omitted, the last element is returned and r
emoved.
 list.remove(x) Removes the first occurrence of x in the list
 list.sort() Sorts the items in the list
 list.reverse() Reverses the order of items of the list
 list.clear() Removes all the items of the list
 list.copy() Creates a copy of the list
 list.extend(other_list) Appends all the elements of other_list
at the end of list
Dictionary:
 <->Operations:
 len(dictionary) - Returns the number of items in the dicti
onary
 for key in dictionary - Iterates over each key in the dict
ionary
 for key, value in dictionary.items() - Iterates over each
key,value pair in the dictionary
 if key in dictionary -
Checks whether the key is in the dictionary
 dictionary[key] - Accesses the item with key key of the di
ctionary
 dictionary[key] = value - Sets the value associated with k
ey
 del dictionary[key] - Removes the item with key key from t
he dictionary
.

 <->Methods:
 dict.get(key, default) - Returns the element corresponding
to key, or default if it's not present
 dict.keys() - Returns a sequence containing the keys in th
e dictionary
 dict.values() - Returns a sequence containing the values i
n the dictionary
 dict.update(other_dictionary) - Updates the dictionary wit
h the items coming from the other dictionary. Existing ent
ries will be replaced; new entries will be added.
 dict.clear() - Removes all the items of the dictionary
 <---->print(dir(“str”))  gives the methods of string
 <---->print(help(“str”))  gives the information about string
methods
.
 EX:
 wdct={"c":10,"pyt":23,"html":5,"css":7,"js":11}
 (1).print(type(wdct))
 (2).print(wdct.keys())
 (3).print(wdct.values())
 (4).print("css" in wdct)
 (5).print(wdct['html'])
 (6).wdct["txt"]=9
print(wdct)
 (7).del wdct['html’]
print(wdct)
 (8).for exten in wdct:
print(exten)
.

 (9).for ext,count in wdct.items():


print("There are {} files with the .{} extension".format(count
,ext))

 (10).def letter_count(text):
result={}
for letter in text:
if letter not in result:
result[letter]=0
result[letter]+=1
return result
print(letter_count("This is a string"))
Week 5:

 <->OOPS:
 EXAMPLES:
 (1). class apple:
 color=""
 flavour=""
 goldenapple=apple()
 goldenapple.color="red"
 goldenapple.flavour="Sweet"
 print(goldenapple.color)  “red”
 print(goldenapple.flavour)  “Sweet”
 (2).class piglet:

. name=""
def speak(self):
print("Oink ! I am {} Oink!".format(self.name))
hamlet=piglet()
hamlet.name="Hamlet"
hamlet.speak()  “Oink ! I am Hamlet Oink!”
 (3).class goldApple:
 “””This is a docstring which tells us about the what something does”””
def __init__(self,color,flavour):
self.color=color
self.flavour=flavour
def __str__(self):

return "This apple is {} and its color is {}".format(self.color,sel


f.flavour)
jonagold=goldApple("red","sweet")
print(jonagold)  “This apple is sweet and its color is
red”
print(jonagold.color,jonagold.flavour)  red sweet
.
 <->Classes and Instances:
 Classes define the behavior of all instances of a specific
class.
 Each variable of a specific class is an instance or object
.
 Objects can have attributes, which store information about
the object.
 You can make objects do work by calling their methods.
 The first parameter of the methods (self) represents the c
urrent instance.
 Methods are just like functions, but they can only be used
through a class
. <->Special Methods:
 Special methods start and end with __.
 Special methods have specific names, like __init__ for the cons
tructor or __str__ for the conversion to string.
 <-> Documenting classes, methods and functions:

You can add documentation to classes, methods, and functions by u


sing docstrings right after the definition. Like this:
 class ClassName:
"""Documentation for the class."""
def method_name(self, other_parameters):
"""Documentation for the method."""
body_of_method
def function_name(parameters):
"""Documentation for the function."""
body_of_function
.
 <->Inheritance:
 EX: class Fruits:
def __init__(self,color,flavour):
self.color=color
self.flavour=flavour
class Apple(Fruits):
pass
class Grapes(Fruits):
pass
new_apple=Apple("red","Sweet")
grapes=Grapes("Green","Sour")
print(new_apple.color,new_apple.flavour)  “red” “Sweet”
print(grapes.color,grapes.flavour)  “Green” “Sour”
Python Modules:

 EXAMPLES:
 (1). import random [//This imports the random module]
print(random.randint(1,10))  prints a random num
btw 1-10
 (2). import datetime
print(datetime.datetime.now()) prints the date and time
 EX: num=[7,5,9,1,4]
print(sorted(num))  [1,4,5,7,9]
print(num)  [7,5,9,1,4]
print(num.sort())  [1,4,5,7,9]
print(num)  [1,4,5,7,9]

You might also like