Python Learning Made Easy
Python Learning Made Easy
Comments:
Comments are any text to the right of the # symbol and are mainly useful as notes
for the reader of the program.
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
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.
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:
print("Hello\
world")
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")
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:
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:
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
Formatted output
Consider an example where you would want to print the name, marks, and the age
of the
person:
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.
Indentation
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
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
Syntax:
variable= expression
Single 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)
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.
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
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)
x,y=100,200
print(x,y)
Logical Operations:
str1="satyamev jayte"
print (Str1)
str1="shramamev jayte"
print (str1)
Operations on Strings
print(str1[2:6])
print(str1[2:])
print(str1[:5])
print(str1[:])
str2="The Avengers"
print(str1.count('T'))
print(str1.count('e'))
str3="peace begins with a smile"
print(str3.find('with'))
str4="manoj jangra"
print(str4.upper())
print(str4.lower())
print(str4.capitalize())
print(str4.title
print(str4.swapcase())
str5="manoj jangram"
print(str5.rstrip("m"))
str5="manoj jangra#"
print(str4.rstrip('#'))
str5=' manoj kumar '
print(str5.rstrip())
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())
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])
tup3=(1,2,3)
A,b,c=tup3
Print(a,b,c)
Operations of tuples
Print(tup3+tup4)
Print(tup*3): 1,2,3,1,2,3,1,2,3
Creating a list
Print(lis1)
Lis2=[‘banana’,’mango’,’apple’,’carrot’]
Print(lis2)
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])
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)
Empty_dic={}
best_team={'australia':'bradman','india':'shrikant','shrilanka':'jaisurya'}
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)