PYTHON LEARNING MADE EASY
Basic Python Syntax
Comments:
Comments are any text to the right of the # symbol and are mainly useful as notes
for the reader of the program.
Use as many useful comments as you can in your program to:
Explain assumptions
Explain important decisions
Explain important details
Explain problems you're trying to solve
Explain problems you're trying to overcome in your program, etc.
For example:
Single line comments – For a single line comments, # is used.
o print ('hello world') #This is single line comment
Multiline comments – For multiline comments, ‘’’/””” (Triple quotes) are
used.
o """ For multi-line
comment use three
double quotes
"""
print("Hello World!")
Single quotes:
You can specify strings using single quotes such as 'Quote me on this'.
All white space i.e. spaces and tabs, within the quotes, are preserved as-is.
Python doesn't care if you use single quotes or double quotes to print a single
statement.
Double Quotes:
Strings in double quotes work exactly the same way as strings in single quotes.
An example is: "What's your name?"
Triple Quotes:
You can specify multi-line strings using triple quotes - ( """ or ''' ). You can use
single
quotes and double quotes freely within the triple quotes. An example is:
'''This is a multi-line string. This is the first line.
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
'''
Python back slash
The Python back slash is used for continuation of the print statement. You can
stretch a
single statement across multiple lines:
print("Hello\
world")
String inside the quotes:
For printing a string, either a pair of single (' ') quotes or pair of double quotes (" ")
can
be used as shown in the succeeding examples:
print ("Hello World 'Mr' Bond")
print ('old world "but" still good')
The format method:
Sometimes we may want to construct strings from other information. This is where
the
format() method is useful.
age = 20
name = 'Swaroop'
print('{0} was {1} years old when he wrote this book'.format(name, age))
print('Why is {0} playing with that python?'.format(name))
Also note that the numbers are optional, so you could have also written as:
age = 20
name = 'Swaroop'
print('{} was {} years old when he wrote this book'.format(name, age))
print('Why is {} playing with that python?'.format(name))
Notice that we could have achieved the same using string concatenation:
name + ' is ' + str(age) + ' years old'
Escape sequence in Python
The escape sequence is used to insert the tab, the newline, the backspace, and other
special characters into your code. They give you greater control and flexibility to
format your statements and code:
Escap Sequence Meaning
e
b Backspace
a Sound system bell
n Newline
t Horizontal tab
The character
' Single quotation mark
" Double quotation mark
print('\a')
print('This is line#1\nThis is line#2\nThis is line#3')
print('This is line#1\tThis is line#2\tThis is line#3')
print("I know, they are 'great'")
String concatenation
Two strings can be joined using the + operator:
print("Only way to join" + "two strings")
Formatted output
Consider an example where you would want to print the name, marks, and the age
of the
person:
print("Name", "Marks", "Age")
print("Amit", 90, 15)
print("Hina",95,15)
print("Hue",99,14)
Python allows you to set the formatted output, using %d (int), %f (float),
%s(string).
If you used %5d, it means 5 spaces. If you used %5.2f, it means 5 spaces and .2
means precision. The decimal part of the number or the precision is set to 2.
Let's use the formatting on the preceding example:
print("Name Marks Age")
print("%s %12.2f %11d" %("Amit", 90, 15))
print("%s %12.2f %11d" %("Hina",95,15))
print("%s %12.2f %11d" %("Hue",99,14))
Indentation
The most unique characteristic of Python, unlike other programming languages, is
indentation. Indentation not only makes Python code readable, but also
distinguishes each
block of code from the other. Let's explain this with an example:
def fun():
pass
for each in "Australia":
pass
C:\Users\user\PycharmProjects\Py1\venv\Scripts\python.exe
C:/Users/user/PycharmProjects/Py1/MyPy1.py
File "C:/Users/user/PycharmProjects/Py1/MyPy1.py", line 2
pass
^
IndentationError: expected an indented block
Process finished with exit code 1
The solution is, properly indentation in code.
def fun():
pass
for each in "Australia":
pass
Variables
Variables are just parts of your computer's memory where you store some
information. Unlike literal constants, you need some method of accessing these
variables and hence you give them names.
There are certain rules or naming conventions for naming variables. The following
are the rules:
Reserved key words such as if, else, and so on cannot be used for naming
variables
Variable names can begin with _, $, or a letter
Variable names can be in lower case and uppercase
Variable names cannot start with a number
White space characters are not allowed in the naming of a variable
You can assign values to the variable using = or assignment operator.
Syntax:
variable= expression
Single assignment
city='London' # A string variable assignment.
money = 100.75 # A floating point number assignment
count=4 #An integer assignment
Multiple assignment
a=b=c=1
Augmented Assignment
x+=
# Total value of a portfolio made up of two blocks of stock
portfolio = 0
portfolio += 150 * 2 + 1/4.0
portfolio += 75 * 1 + 7/8.0
print (portfolio)
Removing Assignment
Suntex
del var1[,var2[,var3[....,varN]]]]
Example:
N1 = 1
N2 = 2
del N2
print(N1)
print(N2)
Data types in Python
Data types can be broadly categorized into five different types, listed as follows:
Numbers
o Integers and long integers - Integers include zero, all of the positive
whole numbers, and all of the negative whole numbers. The int or
integer data type ranges from -231 to (231-1); the leading minus sign
shows the negative values. Beyond these ranges, the interpreter will
add L to indicate a long integer.
o Floating point numbers - Numbers with certain places after the
decimal point are referred to as floating point numbers in the
programming language:
The floating point number type ranges approximately from -10
to 10^308 and has 16 digits of precision.
There are two ways to write a floating point number. It can be
written using
ordinary decimal notation or scientific notation. Scientific
notation is often useful for mentioning very large numbers.
o Complex numbers - A complex number has both real and imaginary
parts, and Python allows you to specify this data type in a very easy
and convenient way.
Syntax:
<variable name>=complex(x,y)
OR
<variable name>=x+yj
Here, x is the real part and y is the imaginary part. Here, j plays
the role of iota.
o Boolean data type - A Boolean data type generally has only two
values 'True' or 'False'. Boolean data type is a sub type of integers.
Syntax:
<variable name>=<'True' or 'False'>
x=10
y=12
print(x==y)
String
Tuples
List
Dictionary
____________________________________________________
1. NUMBER DATA TYPE EXPLANATION
X=10 #Example of integer
Y=12.7 #Example of float
Arithmetic Operations:
Arithmetic Operators (Addition, Subtraction, Multiplication, Exponent,
Division, Floor Division, Modulus)
print(10+5)
print(10-5)
print(10*5)
print(10**2)
print(10/5)
print(12//5)
print(14%6)
Comparison Operations:
Comparison Operators (==,</LT,<=/LE,>/GT,>=/GE,NE/!=)
x=10
y=15
print(x==y)
print(x<y)
print(x<=y)
print(x>y)
print(x>=y)
print(x!=y)
Assignment Operations:
Assignment Operator '='
Total=200
Region='North'
Multiple Assignment Example1
x=y=z=150
print(x,y,z)
Multiple Assignment Example2
x,y=100,200
print(x,y)
Logical Operations:
Logical Operator (AND,OR,NOT)
print (1>4 and 5>4)
print (1>4 or 5>4)
print (not(4>5))
2. STRING DATA TYPE EXPLANATION
str1="satyamev jayte"
print (Str1)
str1="shramamev jayte"
print (str1)
Operations on Strings
1. The Subscript Operator - Used to access the elements of string
2. Slicing for Substrings - Used to access the elements of string
print(str1[2:6])
print(str1[2:])
print(str1[:5])
print(str1[:])
3. String Methods - COUNT, FIND
str2="The Avengers"
print(str1.count('T'))
print(str1.count('e'))
str3="peace begins with a smile"
print(str3.find('with'))
4. String Case Methods - UPPER, LOWER, CAPITALIZE, TITLE,
SWAPCASE
str4="manoj jangra"
print(str4.upper())
print(str4.lower())
print(str4.capitalize())
print(str4.title
print(str4.swapcase())
5. String Strip Methods
str5="manoj jangram"
print(str5.rstrip("m"))
str5="manoj jangra#"
print(str4.rstrip('#'))
str5=' manoj kumar '
print(str5.rstrip())
6. String Split Methods
str6='27-12-2009'
print(str6.split('-',1)) #1st part split
print(str6.split('-',2)) #1st, 2nd part split
print(str6.split('-',3)) #1st, 2nd part & 3rd part split
str7="mohit raj"
print(str7.split())
7. String Justify Methods - LJUST, RJUST, CENTER, ZFILL, REPLACE,
JOIN
print(str7.ljust(15,'@')) #Left justify
print(str7.rjust(15,'#')) #Right justify
print(str7.center(16,'*')) #Centrally justified
account_no='1810037305'
print(account_no.zfill(20)) #Filling a string with characters
str8="manoj kumar"
print(str8.replace("kumar","jangra"))#Repacing a part of string with other
part
name=['mohit','raj']
print(" ".join(name))#Joining parts of strings
3. TUPLE DATA TYPE EXPLANATION
tup1=()
Tup2=(2,1,3,”manoj”,10,”hina”)
Indexing Tuple
Print(tup2[0])
Print(tup2[2])
Slicing of tuple
Print(tup2[2,5])
Print(tup2[2:])
Print(tup2[:5])
Print(tup2[-3,-2])
Unpacking the items of tuples
tup3=(1,2,3)
A,b,c=tup3
Print(a,b,c)
Tuple functions – len(), max(), min()
Print(len(tup3)): 3
Print(max(tup3)): 3
Print(min(tup3)):1
Operations of tuples
(+) – Addition operator
Print(tup3+tup4)
(*) – Multiplication operator
Print(tup*3): 1,2,3,1,2,3,1,2,3
4. LIST DATA TYPE EXPLANATION
Creating a list
Lis1=[] #List with null values
Print(lis1)
Creating a list with values
Lis2=[‘banana’,’mango’,’apple’,’carrot’]
Print(lis2)
Unpacking list values
Lis3=[2,3,5]
X,Y,Z=Lis3
Print(X,Y,Z)
List operations
Print(lis3[0])
Print(lis3[3])
Slicing of List
Print(lis3[2,6])
Print(lis3[2:])
Print(lis[:4])
Print(lis3[1:13:3])
Updating the list
Avengers=[‘thor’,’hulk’,’captain’]
Avengers=[2]
Avengers[2]=’captain-america’
Deleting values from a list
del list1[1]
print(list1)
del list1[2:5]
print(list1)
del list1
print(list1)
Addition of Python lists
veg_list=['carrot','ladyfinger','reddish']
fru_list=['mango','banana']
fin_list=veg_list+fru_list
print(fin_list)
Multiplication of lists
av=['vision','sam']
av_double=av*2
print(av_double)
in operator
if 'vision' in av:
print('yes')
List functions
len() –
print(len(fin_list))
max () –
print(fin_list)
min() –
print(fin_list)
list () –
tup1=(1,4,3)
tup_2_list=list(tup1)
print(tup_2_list)
sorted () –
tup1=(1,4,3)
tup_2_list=list(tup1)
print(tup_2_list)
print(sorted(tup_2_list))
List methods
append () –
veg_list.append('spinach')
veg_list.append('corriendor')
print(veg_list)
extend() –
lis1=[10,20,40,30]
lis2=[40,60]
lis1.extend(lis2)
print(lis1)
count () –
print(lis1.count(10))
index () –
print(lis1.index(20))
insert()-
veg_list.insert(0,'zeera')
print(veg_list)
remove() –
veg_list.remove('carrot')
print(veg_list)
reverse() –
veg_list.reverse()
print(veg_list)
5. DICTIONARY DATA TYPE EXPLANATION
Empty_dic={}
best_team={'australia':'bradman','india':'shrikant','shrilanka':'jaisurya'}
print(best_team)
Operations on the dictionary
Accessing the values of dictionary
print(best_team['shrilanka']
Deleting an item from the dictionary
del best_team['india']
print(best_team)
Updating the values of the dictionary
best_team['shrilanka']='sanath'
print(best_team)
Adding an item to the dictionary
best_team['england']='batham'
best_team['pakistan']='miyandad'
print(best_team)
Dictionary functions
len() –
print(len(best_team))
str() –
str(best_team)
print(best_team)
max() –
max(best_team)
print(best_team)
min() –
min(best_team)
print(best_team)
dict() –
dict(best_team)
print(best_team)
Dictionary Methods –
new_bestteam=best_team.copy()
print(new_bestteam)
get() –
print(best_team.get('india'))
setdefault() –
print(best_team.setdefault('india'))
key() –
port1 = {80: 'http', 18: None, 19: 'Unknown', 22: 'SSH', 23: 'Telnet'}
print(port1.keys())
values() –
port1 = {80: 'http', 18: None, 19: 'Unknown', 22: 'SSH', 23: 'Telnet'}
print(port1.values())
items() –
port1.items()
print(port1)
update() –
port1 = {80: 'http', 18: None, 19: 'Unknown', 22: 'SSH', 23: 'Telnet'}
port2={25:'given', 30:'not taken'}
port1.update(port2)
print(port1)
clear() –
port1.clear()
print(port1)