Everything You Need to Learrn Python
Everything You Need to Learrn Python
Copy
e can display the content present in object using prit function as follows:-
w
var1 =
"Shruti"
print
(
"
Hi my name is: " ,var1)
Copy
The input function is used to take input as string or character from the user as follows:
var1 =
input (
"Enter your name: "
)
print
(
"My name is: "
, var1)
Copy
o take input in form of other datatypes we need to typecaste them as follows:-
T
To take input as an integer:-
var1=
int
(
input
(
"
enter the integer value" ))
print
(var1)
Copy
o take input as an float:-
T
var1=
float
(
input
(
"
enter the float value"
))
print
(var1)
Copy
range Function
r ange function returns a sequence of numbers, eg, numbers starting from 0 to n-1 for
range(0, n)
range
(int_start_value,int_stop_value,int_step_value)
Copy
ere the start value and step value are by default 1 if not mentioned by the programmer.
H
but int_stop_value is the compulsory parameter in range function
example-
Display all even numbers between 1 to 100
for
iinrange (
0
,
1
01,
2
)
:
print
(i)
Copy
Comments
omments are used to make the code more understandable for programmers, and they
C
are not executed by compiler or interpreter.
Copy
Multi-line comment
''This is a
'
multi-line
comment'''
Copy
Escape Sequence
n escape sequence is a sequence of characters; it doesn't represent itself (but is
A
translated into another character) when used inside string literal or character. Some of the
escape sequence characters are as follows:
Newline
Newline Character
print
(
"\n"
)
Copy
Backslash
Copy
Single Quote
Copy
Tab
Copy
Backspace
Copy
Octal value
Copy
Hex value
Copy
Carriage Return
arriage return or \r will just work as you have shifted your cursor to the beginning of the
C
string or line.
pint(
"\r"
)
Copy
Strings
ython string is a sequence of characters, and each character can be individually
P
accessed using its index.
String
ou can create Strings by enclosing text in both forms of quotes - single quotes or double
Y
quotes.
variable_name =
"String Data"
Copy
xample
e
str
=
"
Shruti"
print
(
"string is "
,
s
tr
)
Copy
Indexing
he position of every character placed in the string starts from 0th position ans step by
T
step it ends at length-1 position
Slicing
licing refers to obtaining a sub-string from the given string. The following code will
S
include index 1, 2, 3, and 4 for the variable named var_name
Slicing of the string can be obtained by the following syntax-
string_var[int_start_value:int_stop_value:int_step_value]
Copy
var_name[
1
:
5
]
Copy
ere start and step value are considered 0 and 1 respectively if not mentioned by the
h
programmmer
isalnum() method
Returns True if all the characters in the string are alphanumeric, else False
string_variable.isalnum()
Copy
isalpha() method
Copy
isdecimal() method
Copy
isdigit() method
Copy
islower() method
Copy
isspace() method
Copy
isupper() method
Copy
lower() method
Copy
upper() method
Copy
strip() method
Copy
List
List in Python represents a list of comma-separated values of any data type between
A
square brackets.
var_name = [element1, element2, ...]
Copy
These elements can be of different datatypes
Indexing
he position of every elements placed in the string starts from 0th position ans step by
T
step it ends at length-1 position
List is ordered,indexed,mutable and most flexible and dynamic collection of elements in
python.
Empty List
Copy
index method
Returns the index of the first element with the specified value
list
.index(element)
Copy
append method
Copy
extend method
Add the elements of a given list (or any iterable) to the end of the current list
list
.extend(iterable)
Copy
insert method
Copy
pop method
Copy
remove method
The remove() method removes the first occurrence of a given item from the list
list
.remove(element)
Copy
clear method
Copy
count method
Copy
reverse method
Copy
sort method
Copy
Tuples
Tuples are represented as comma-separated values of any data type within parentheses.
Tuple Creation
Copy
These elements can be of different datatypes
Indexing
he position of every elements placed in the string starts from 0th position ans step by
T
step it ends at length-1 position
Tuples are ordered,indexing,immutable and most secured collection of elements
Lets talk about some of the tuple methods:
count method
Copy
index method
It searches the tuple for a specified value and returns the position.
tuple
.index(value)
Copy
Sets
set is a collection of multiple values which is both unordered and unindexed. It is written
A
in curly brackets.
Copy
var_name =
set
([element1, element2, ...])
Copy
et is unordered,immutable,non-indexed type of collection.Duplicate elements are not
S
allowed in sets.
Set Methods
add() method
clear() method
Copy
discard() method
Copy
intersection() method
Copy
issubset() method
Copy
pop() method
Copy
remove() method
Copy
union() method
Dictionaries
he dictionary is an unordered set of comma-separated key:value pairs, within {}, with the
T
requirement that within a dictionary, no two keys can be the same.
Dictionary
Copy
ictionary is ordered and mutable collection of elements.Dictionary allows duplicate
D
values but not duplicate keys.
Empty Dictionary
By putting two curly braces, you can create a blank dictionary
mydict={}
Copy
By this method, one can add new elements to the dictionary
<dictionary>[<key>] = <value>
Copy
If a specified key already exists, then its value will get updated
<dictionary>[<key>] = <value>
Copy
del keyword is used to delete a specified key:value pair from the dictionary as follows:
del
<dictionary>[<key>]
Copy
len() method
It returns the length of the dictionary, i.e., the count of elements (key: value pairs) in the
dictionary
len
(dictionary)
Copy
clear() method
Copy
get() method
Copy
items() method
Copy
keys() method
Copy
values() method
Copy
update() method
Copy
Indentation
In Python, indentation means the code is written with some spaces or tabs into many
different blocks of code to indent it so that the interpreter can easily execute the Python
code.
Indentation is applied on conditional statements and loop control statements. Indent
specifies the block of code that is to be executed depending on the conditions.
Conditional Statements
he if, elif and else statements are the conditional statements in Python, and these
T
implement selection constructs (decision constructs).
if Statement
if
(conditional expression):
statements
Copy
if-else Statement
if
(conditional expression):
statements
else
:
statements
Copy
if-elif Statement
if
(conditional expression):
statements
elif
(conditional expression):
statements
else
:
statements
Copy
if
(conditional expression):
if
(conditional expression):
statements
else
:
statements
else
:
statements
Copy
xample-
e
a=
15
b=
20
c=
12
if
(a>b
anda>c):
print
(a,
"is greatest"
)
elif
(b>c
and
b>a):
print
(b,
" is greatest"
)
else
:
print
(c,
"is greatest"
)
Copy
Loops in Python
loop or iteration statement repeatedly executes a statement, known as the loop body,
A
until the controlling expression is false (0).
For Loop
he for loop of Python is designed to process the items of any sequence, such as a list or
T
a string, one by one.
for
<variable> in<sequence>:
statements_to_repeat
Copy
example-
for
i
inrange
(
1
,
1
01
,
1
)
:
print
(i)
Copy
While Loop
while loop is a conditional loop that will repeat the instructions within itself as long as a
A
conditional remains true.
while
<logical-expression>:
loop-body
Copy
example-
=
i 1
while
(i<=
100
):
print
(i)
i=i+
1
Copy
Break Statement
he break statement enables a program to skip over a part of the code. A break statement
T
terminates the very loop it lies within.
for
<var> in<sequence>:
statement1
if
<condition>:
break
statement2
statement_after_loop
Copy
example-
for
i
inrange
(
1
,
1
01
,
1
)
:
print
(i ,end=
" "
)
if
(i==
50
):
break
else
:
print
(
"
Mississippi"
)
print
(
"
Thank you")
Copy
Continue Statement
he continue statement skips the rest of the loop statements and causes the next iteration
T
to occur.
for
<var> in<sequence>:
statement1
if
<condition> :
continue
statement2
statement3
statement4
Copy
example-
for
i
in[
2
,
3
,
4
,
6
,
8
,
0
]
:
if
(i%2
!=
0
)
:
continue
print
(i)
Copy
Functions
function is a block of code that performs a specific task. You can pass parameters into a
A
function. It helps us to make our code more organized and manageable.
Function Definition
def
my_function
():
#statements
Copy
def keyword is used before defining the function.
Function Call
my_function()
Copy
henever we need that block of code in our program simply call that function name
W
whenever neeeded. If parameters are passed during defing the function we have to pass
the parameters while calling that function
example-
def
add
():
#function defination
a=
10
b=
20
print
(a+b)
add()
#function call
Copy
The function return statement return the specified value or data item to the caller.
return
[value/expression]
Copy
rguments are the values passed inside the parenthesis of the function while defining as
A
well as while calling.
def
my_function (arg1,arg2,arg3....argn):
#statements
my_function(arg1,arg2,arg3....argn)
Copy
xample-
e
def
add
(a,b):
return
a+b
x=add(
7
,
8
)
print
(x)
Copy
File Handling
ile handling refers to reading or writing data from files. Python provides some functions
F
that allow us to manipulate data in the files.
open() function
var_name =
open
(
"file name"
,
" mode"
)
Copy
modes-
.
1 r - to read the content from file
2. w - to write the content into file
3. a - to append the existing content into file
4. r+: To read and write data into the file. The previous data in the file will be
overridden.
5. w+: To write and read data. It will override existing data.
. a+: To append and read data from the file. It won’t override existing data.
6
close() function
var_name.close()
Copy
read () function
Copy
It returns a list of lines
readlines()
#returns a list
Copy
It returns one line at a time
readline
#returns one line at a time
Copy
write function
This function writes a sequence of strings to the file.
write()
#Used to write a fixed sequence of characters
to a file
Copy
It is used to write a list of strings
writelines()
Copy
Exception Handling
n exception is an unusual condition that results in an interruption in the flow of a
A
program.
basic try-catch block in python. When the try block throws an error, the control goes to
A
the except block.
try
:
[Statement body block]
raise
Exception()
except
Exceptionname:
[Error processing block]
Copy
else
he else block is executed if the try block have not raise any exception and code had
T
been running successfully
try
:
#statements
except
:
#statements
else
:
#statements
Copy
finally
inally block will be executed even if try block of code has been running successsfully or
F
except block of code is been executed. finally block of code will be executed compulsory
Copy
Creating an object
Copy
self parameter
he self parameter is the first parameter of any function present in the class. It can be of
T
different name but this parameter is must while defining any function into class as it is
used to access other data members of the class
onstructor is the special function of the class which is used to initialize the objects. The
C
syntax for writing a class with the constructor in python
class
CodeWithHarry :
Default constructor
#
def
__init__
(self):
self.name =
"CodeWithHarry"
Copy
Inheritance in python
y using inheritance, we can create a class which uses all the properties and behavior of
B
another class. The new class is known as a derived class or child class, and the one
whose properties are acquired is known as a base class or parent class.
It provides the re-usability of the code.
class
Base_class :
pass
class
derived_class (Base_class):
pass
Copy
Types of inheritance-
● ingle inheritance
S
● Multiple inheritance
● Multilevel inheritance
● Hierarchical inheritance
filter function
he filter function allows you to process an iterable and extract those items that satisfy a
T
given condition
filter
(function, iterable)
Copy
issubclass function
Copy
Iterator
Copy
Generator
Copy
Decorators
ecorators are used to modifying the behavior of a function or a class. They are usually
D
called before the definition of a function you want to decorate.
property
@
def
name
(self):
return
self.__name
Copy
setter Decorator
Copy
deleter Decorator