Notes

Python Basics Notes



Tokens



Keywords


Keywords are the words having special meaning reserved by a programming language.


Keyword Description
break used to exit loop and used to exit
char basic declaration of a type character
const prefix declaration meaning variable can not be changed
continue go to bottom of loop in for, while loops
class to define a class
def to define a function
elif shortcut for (else if) used in else if ladder
else executable statement, part of “if” structure
float basic declaration of floating point
for executable statement, for loop
from executable statement, used to import only specific objects from a package
if executable statement
import to import modules
pass keyword to specify noting is happening in the codeblock, generally used in classes
return executable statement with or without a value
while executable statement, while loop

Point to note: range is not a keyword


Identifiers


Identifiers are the names given to different parts of program like variables ,objects ,classes ,lists etc.


Rules for Python identifiers



Scope Of Variables


The part of a program where a variable is accessible is called its scope. LEGB Rule is the rule that descides the scope of variables.
L=Local
E=Enclosed
G=Global
B=Built-in


Literals


String Literals

String literal is a sequence of character surrounded by quotes.

string='Sam Varghese'#Single line string literal

string='Sam\
Varghese'#Multiline String literal
string='''Sam
Varghese'''#This multiline string does not require slash.

Important Escape Sequences
Escape Sequence Denotion
\\ Backlash(\)
\’ Single quote(‘)
\n New line character
\t Vertical Tab(4 spaces)

Numeric Literals

These are numeric values.


Boolean Literals

These are just True or False **

Special Literal None

This is None literal used to denote absence of any value.


List Literals

lst=[1,2,3,4,5,6,7,8]
sliced_lst=lst[1:6:2]#Syntax: lst[start_index,stop_index,step]
liced_lst is now [2,5,6]

Tuple Literals

_tuple=1,2,3,4

# _tuple is a tuple

Set Literal

Dictionary Literal

Operators

Operator Description
( ) grouping parenthesis, function call, tuple declaration
[ ] array indexing, also declaring lists etc.
! relational not, complement, ! a yields true or false
~ bitwise not, ones complement, ~a
- unary minus, - a
+ unary plus, + a
* multiply, a * b
/ divide, a / b (returns floating point result)
% modulo, a % b
+ add, a + b
- subtract, a - b
« shift left, left operand is shifted left by right operand bits
>> shift right, left operand is shifted right by right operand bits
< less than, result is true or false, a %lt; b
<= less than or equal, result is true or false, a <= b
> greater than, result is true or false, a > b
>= greater than or equal, result is true or false, a >= b
== equal, result is true or false, a == b
!= not equal, result is true or false, a != b
& bitwise and, a & b
^ bitwise exclusive or XOR, a ^ b
| bitwise or, a | b
&&, and relational and, result is true or false, a < b && c >= d
||, or relational or, result is true or false, a < b || c >= d
= store or assignment
+= add and store
-= subtract and store
*= multiply and store
/= divide and store
%= modulo and store
«= shift left and store
>>= shift right and store
&= bitwise and and store
^= bitwise exclusive or and store
|= bitwise or and store
, separator as in ( y=x,z=++x )




Operators Precedence Order

Operator(In precedence order)
()
**
+, - ,~
* ,/ ,// ,%
+ ,-
« ,»
&
^
|
==, !=, >, >=, < ,<=, is ,is not ,in ,not in
not
and
or



Punctuators

Most common punctuators of Python are:-
( ) { } [ ] ; , . \ # @ : = ‘ “


Operators

Operator Description  
( ) grouping parenthesis, function call, tuple declaration  
[ ] array indexing, also declaring lists etc.  
! relational not, complement, ! a yields true or false  
~ bitwise not, ones complement, ~a  
- unary minus, - a  
+ unary plus, + a  
* multiply, a * b  
/ divide, a / b (returns floating point result)  
% modulo, a % b  
+ add, a + b  
- subtract, a - b  
« shift left, left operand is shifted left by right operand bits  
>> shift right, left operand is shifted right by right operand bits  
< less than, result is true or false, a %lt; b  
<= less than or equal, result is true or false, a <= b  
> greater than, result is true or false, a > b  
>= greater than or equal, result is true or false, a >= b  
== equal, result is true or false, a == b  
!= not equal, result is true or false, a != b  
& bitwise and, a & b  
^ bitwise exclusive or XOR, a ^ b  
| bitwise or, a b
&&, and relational and, result is true or false, a < b && c >= d  
||, or relational or, result is true or false, a < b || c >= d  
= store or assignment  
+= add and store  
-= subtract and store  
*= multiply and store  
/= divide and store  
%= modulo and store  
«= shift left and store  
>>= shift right and store  
&= bitwise and and store  
^= bitwise exclusive or and store  
|= bitwise or and store  
, separator as in ( y=x,z=++x )  




Operator(In precedence order)
()
**
+, - ,~
* ,/ ,// ,%
+ ,-
« ,»
&
^
|
==, !=, >, >=, < ,<=, is ,is not ,in ,not in
not
and
or

Conditional branching

Syntax:

if condition:
    pass
elif condition2:
    pass
else:
    pass

Loops

Python has two primitive loop commands:

  1. while loops
  2. for loops

While Loop

For Loop

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
  for y in fruits:
    print(x, y)
for x in [0, 1, 2]:
  pass

Functions

def function_name():

  """function docs"""

  return
print(functio_name.__doc__)#2 dot then underscores before and after doc
lst=[1,2,3]
def example():
  lst.append(4)
example()
print(lst)
#Though lst was modified in local scope , still on printing lst ,output is [1,2,3,4]

Function call

function_name()

File Handling

Files are most crucial elements in running of programs because they helps in storing information permanently.

Modes Of Opening Files


Mode Description
r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.


Opening Files

Two ways are there in order to open files in python:


Using With Open Method

Syntax:

with open(file_name,mode):
  #operations

The advantage of using this method of opening file is that we do not need to close file >explicitly.


Using Open Method

Syntax:

file_handle=open(file_name,mode)
#Code
file_handle.close()

Text Files

In this type of file, Each line of text is terminated with a special character called > EOL(End of Line), which is the new line character (‘\n’) in python by default.

Writing Into A Text File

Syntax:

file_handle=open(file_name,mode)
file_handle.write(text_to_be_written)#Text shoub always be a string
file_handle.close()

Suppose if we have a list and we want to put all its elements into a file , then use >writelines:

file_handle=open(file_name,mode)
file_handle.writelines(list)
file_handle.close()

Reading A Text File

This method enables us to read all contents of a file if no parameters is given. If > anyp> arameter (which is an integer) is given ,then that number of bytes are read.

Syntax

 file_handle=open(file_name,mode)
 read_content=file_handle.read()
 file_handle.close()

Reads all the lines and return them as each line a string element in a list.

Syntax

file_handle=open(file_name,mode)
read_content=file_handle.readlines()
file_handle.close()

Note: ‘\n’ is treated as a special character of two bytes



CSV Files

A csv fle is simply a kind of file wherein data is stored with commas separating them. >CSV stands for Comma Separated Files.


Writing Into CSV File

Syntax:

import csv
file_handle=open(file_name,mode,newline='')
writer_object=csv.writer(file_handle)
writer.writerow([items])
file_handle.close()

To write contents of 2 dimensional list ,use writerows:-
Syntax

import csv
file_handle=open(file_name,mode,newline='')
writer_object=csv.writer(file_handle)
writer.writerows([[],[],[],,,])
file_handle.close()

Reading A CSV File

Syntax:

import csv
with open(file_handle, 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

Binary Files

Writing Binary Files

Syntax:

import pickle
file_handle=open(file_name,mode)#Mode will be like wb ,ab so on
pickle.dump(list,file_handle)
file_handle.close()

Reading Binary Files

Syntax:

import pickle
file_handle=open(file_name,mode)
file_content=pickle.load(file_handle)
for i in file_content:
  print(i)
file_handle.close()