Tokens or Lexical Units are the smallest individual unit in a program.
They are of 5 types:-
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 are the names given to different parts of program like variables ,objects ,classes ,lists etc.
Rules for Python identifiers
Variable names must be a non-keyword word with no spaces in between.
Variable names must be made up of only letters ,number and underscores( _ ) .
Variable names can not begin with a number ,although they may contain numbers.
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
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.
Escape Sequence | Denotion |
---|---|
\\ | Backlash(\) |
\’ | Single quote(‘) |
\n | New line character |
\t | Vertical Tab(4 spaces) |
These are numeric values.
These are just True or False **
This is None literal used to denote absence of any value.
thislist = ["apple", "banana", "cherry"]
[0]
, the second tem has index [1]
tc[-1]
last second item [-2]
,and so on.len()
function.list1 = ["abc", 34, True, 40, "male"]
thislist = list(("apple", "banana", "cherry")) > # note the double round-brackets
It is also possible to slice a list in following way:
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]
thistuple = ("apple", "banana", "cherry")
_tuple=1,2,3,4
# _tuple is a tuple
[0]
, the second item has index [1]
tc.thistuple = ("apple", "banana", "cherry", "apple", "cherry")
len()
function:
py
histuple = ("apple", "banana", "cherry")
rint(len(thistuple))
thistuple = ("apple",)#This is a tuple
thistuple = ("apple")#This is not a tuple
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
thisset = {"apple", "banana", "cherry"}
len()
method.
thisset = {"apple", "banana", "cherry"}
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
set4 = {"abc", 34, True, 40, "male"}
set()
constructor to make a set.
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
len()
function.
print(len(thisdict))
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
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 |
Most common punctuators of Python are:-
( ) { } [ ] ; , . \ # @ : = ‘ “
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 |
Syntax:
if condition:
pass
elif condition2:
pass
else:
pass
Python has two primitive loop commands:
while
loop we can execute a set of statements as long as a condition is true.i = 1
while i < 6:
print(i)
i += 1
break
statement we can stop the loop even if the while condition is trueWith the continue statement we can stop the current iteration, and continue with the next.
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.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
The else keyword in a for loop specifies a block of code to be executed when the loop is finished. A nested loop is a loop inside a 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
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_name()
None
Files are most crucial elements in running of programs because they helps in storing information permanently.
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. |
Two ways are there in order to open files in python:
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.
Syntax:
file_handle=open(file_name,mode)
#Code
file_handle.close()
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.
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()
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 a line of the file and returns in form of a string.For specified n, reads at > most n> bytes. However, does not reads more than one line, even if n exceeds the length > of the l> ine.
Syntax
file_handle=open(file_name,mode)
read_content=file_handle.readline()
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
A csv fle is simply a kind of file wherein data is stored with commas separating them. >CSV stands for Comma Separated Files.
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()
Syntax:
import csv
with open(file_handle, 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
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()
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()