Python-Course-PPT
Python-Course-PPT
You can use Python on GNU/Linux, Windows, FreeBSD, Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, BeOS,
OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acorn RISC OS, VxWorks, PlayStation, Sharp Zaurus, Windows CE and
PocketPC!
FEATURES OF PYTHON
● Interpreted - Python, on the other hand, does not need compilation to binary. You just run the program
directly from the source code. Internally, Python converts the source code into an intermediate form called
bytecodes and then translates this into the native language of your computer and then runs it.
● Extensive Libraries - The Python Standard Library is huge indeed. It can help you do various things
involving regular expressions,documentation generation, unit testing, threading, databases, web browsers,
CGI, FTP, email, XML, XML-RPC, HTML, WAV files, cryptography, GUI (graphical user interfaces), and other
system-dependent stuff. Remember, all this is always available wherever Python is installed.
● Free and open source.
What is Python ?
●
● Interpreted, object oriented, high level
programming language.
●
● We can do any type of development that we
want.
●
● It is designed to be human readable.
●
● Hundreds of python libraries and
frameworks.
●
● Huge community.
What can we do with Python ?
INPUT /
OUTPUT
To take input from the user we use input() function.
All about print()
The print() function prints the specified message to the screen, or other standard output specified.
We can pass multiple arguments all at once and it will print it in the same line.
Multiple print will result in multiple lines. First print will be printed in the first line
and second print will be printed in the second line.
We can print in the same line by specifying the end argument in print. By default it is ‘\n’ that
means new line. We can change that to empty space just by giving end = ‘’
All about print()
We can also print the values passed in one print statement into multiple lines and format it according to our wish.
‘\n’ is used to break the line and Here we have specified ‘\n\t’. ‘\n’
print everything after \n in new line will break the line and ‘\t’ is used
for tab or four spaces.
Comments in Python
Comments are non-executable python code.
We use comments to -
Variable name
print(id(first_num )
)
● Variable name should start with a letter or underscore.
● We cannot use python keywords as variable names.
RULES FOR NAMING ●
●
Do not use numbers at the start of variable names.
The only allowed special character is underscore (_) .
VARIABLES ● Variable names can only have alphanumeric characters
(A-Z,a-z,0-9) and underscore.
● Variable names are case sensitive (e.g Age, age and AGE
are different variable names)
OPERATORS
Operator Operands
Float type -
Numeric Floats are the numbers with decimal values.
Types: Complex -
Complex types has a real and imaginary part.
Hex function -
hex() function is used to convert a decimal number into a
hexadecimal form
Bin Function -
Numeric bin() is used to convert a decimal number into a binary
number.
Oct function
oct() is used to convert a decimal number into a octal form.
Attempting to index beyond the end of Attempting to index beyond the start of
string results in error. string using negative indexing also results
in error.
#slicing
a = 'Codegnan code stars'
Strings in python have a unique built in operation that can be accessed by using %
operator to do positional string formatting.
#string formatting
first_name = 'John'
last_name = 'Harris'
print('Hello',first_name,last_name)
Formatting :
print(first_name + ' ' + last_name)
String
Formatting :
str.format() method
Formatting :
str.format() method
Using ‘+’ operator on string
will result in string
concatenation.
String
Functions: Using ‘*’ operator will result
in multiplying the string that
many number of times.
c = 'codegnan'
print(c.isupper()) #check whether the string is uppercase or not
print(c.islower()) #check whether the string is lowercase or not
Returns Boolean
print(c.isdigit()) #check whether the string is a digit or not
True or False
print(c.isalpha()) #check whether the string is alphanumeric(A-Z,a-z) or not
print(c.startswith('lo')) #check whether the string starts with "lo"
print(c.endswith('l')) #checks whether the string ends with "l"
String Methods
Some more methods -
➢ index() - gives the index of the string.
➢ rindex() - looks from right to left.
➢ isalnum() - checks whether the string is alphanumeric or not.
➢ isspace() - checks if the string is having only whitespace.
➢ isascii() - checks if the string has ascii representation or not.
➢ rfind() - looks for the specified string from right side.
➢ rjust() - right align the string
➢ ljust() - left align the string.
➢ swapcase() - swaps the case of the string.
➢ isdecimal() - checks if the string has decimal values.
➢ casefold() - converts all the alphabets in lower.
languages = "java,python,c,c++"
d = languages.split(',') #splits the string
after each occurrence of ',' into different
substrings and return a list of strings
print(d)
● Lists are mutable data types that means we can add, update and
delete the element of the lists.
Lists:
Indexing
Slicing
length of list
Lists Methods
Lists: course = ["Python","Html","Java","Machine
Learning" ] #create list - course
Append() - adds the element at
print(course) #print course
the end of the list.
course.append ('IoT') #append IoT to list course
print(course) #print course after appending
'IoT'
#Extend
Dictionary print(dct)
If <expression> :
statement-1
If statement-2
…………….
Statements: statement-n
a = 15
if a > 10 :
Conditional Statements are handled print("A is greater than 10")
by if statement in python. It is used
for making decisions.
Syntax
Statements: a = 15
if a > 10 :
print("A is greater than 10")
else:
print("A is less than 10")
If- else
Statement
flowchart
Syntax
If <expression> :
statement
elif <expression> :
statement
If- elif elif <expression> :
statement
Statements: else:
statement
num = 10
if (num==0):
print("Number is 0")
elif (num > 5):
print("Number is greater than 5")
else:
print("Number is less than 5")
Nested IF
condition
Loops
Syntax
Loop:
a = 1
while a < 10:
print(a)
a +=1
Syntax
Loop:
lst = [10,20,30,40,50]
for var in lst:
print(var)
range() function generates
the integer numbers
between the start number
and end number
assert:
Functions
To define a Data to pass in
Name of the function
function
function
Syntax
Functions: ‘ ‘ ‘docstring’ ’ ’
statements
header
Function print(a + b)
#a function executes when it is called we
addition = add(50,60)
print(addition)
Functions:
parameters / arguments
● Positional arguments
● Keyword arguments
● Default arguments
● Variable length arguments
● Keyword variable length arguments
Functions: def greet(name,message):
''' A Function to greet a person
Positional arguments with message'''
print(name + " " + message)
Positional arguments are the
arguments that need to be greet('Monica','good morning')
included in the proper
position or order.
def grocery(item,price):
'''Function with two keyword arguments
'item','price'
Functions: '''
print(f'Price: {price}')
Keyword arguments print(f'Item name : {item}')
Keyword arguments are the #call the function and pass the keyword arguments
arguments that identifies the value
arguments by their name.
grocery(item='Soap',price=44)
def grocery(item,price=50.5):
'''Function with default
'''
Functions: print(x)
foo() #call the function
Global variable
If we change the value of x inside the function it will throw an error. We have to
use global keyword while declaring variable x, if we want to change the value
A variable declared outside inside the function
of a function or in global
scope is known as global x = 10
variable. Global variables can
def add5():
be accessed inside and
outside of a function. global x
x = x + 5
print(x)
add5(10)
def local_example():
''' Example of local variable'''
x = "Hello"
print(x)
local_example()
Local variable
The variables declared inside
a function body are known
as local variables.
Local variables cannot be
accessed outside a function
body.
def display(name): #main function
Functions:
''' Function inside a function to greet'''
def message(): #function inside a function
return "Good Morning!"
Function inside result = message () + ' ' + name
another function return result
display('Manvendra')
def display(name,func):
Recursion: else:
return (x * factorial(x-1))
When a function calls factorial(3)
itself over and over again
it is known as recursion. #factorial(3) # 1st call with 3
#3 * factorial(2) # 2nd call with 2
#3 * 2 * factorial(1) # 3rd call with 1
#3 * 2 * 1 # return from 3rd call as number=1
#3 * 2 # return from 2nd call
#6 # return from 1st call
Anonymous Function :
Lambda
● An anonymous function is a function which has no
name.
● Normal functions are defined using def keyword,
while lambda functions are defined using lambda
keyword.
● Lambda function can have any number of argument
Lambda: but only 1 expression
An anonymous function
is a function which has Syntax
no name.
lambda arguments : expression
map(): map()
new_lst = list(map(lambda x : x**2,lst))
The map() function is similar to the
print(new_lst)
filter() function but acts on each
element and perhaps changes that
element.
List Comprehension
List Comprehension
Iterating through a loop using for loop.
print(dict1_tripleCond)
Generators
# A simple generator function
def my_gen():
n = 1
print('This is printed first')
# Generator function contains yield statements
yield n
Generators: n += 1
print('This is printed second')
Generators are iterators, a kind yield n
of iterators you can only iterate
over once. n += 1
It is created like ordinary
print('This is printed at last')
function but uses yield keyword
instead of return. yield n
We have to import the file first using from mymodule import greet as gt
import and then use the functionality.
from mymodule import greet as gt
There are different ways to import gt(“Manvendra”, “Hello”)
module.
def greeting(name,message):
return name + ‘ ’ + message
Modules: Person = {‘Name’ : ‘Manvendra’,
‘Age’ : 23, ‘Company’ : ‘Codegnan’ }
Variables in Modules
We are opening the files and have created fp object to store the file content. We won’t see the file
contents if we print fp.
There are 3 different functions to read the file
contents :-
0 means move to 0th position, 1 means maintain the current position and 2 means move at the end.
In w+ mode also it overwrites everything in the file. We can perform both read and write
operations .
In a+ mode it appends the content to the file. It does not overwrites the content of the file.
We can perform the read and write operations when file opened in append mode.
Errors and Exceptions in
Python
Syntax Error :
When proper syntax of language is not
followed a syntax error is thrown.
Errors:
Errors are the problem in the lst = [10,20,30,40,50] We can solve a
code that will stop the execution for i in lst syntax error by
of the program. print(i) writing the correct
syntax.
Types of errors in python -
● Syntax errors
● Logical error(Exceptions) A syntax error is thrown.
Exceptions:
Exceptions are raised when some
internal error occur which A = 100
changes the normal flow of the Mark = A/0
program. # when we divide any number by 0 ZeroDivisionError
exception is raised.
The output of modf will result in a tuple where the first element will be the
math.modf(5)
decimal value and the other will be the integral part.
random.randrange(10,100) Gives a random number between 0 and 100 it does not includes
the endpoint.
import sys
print(‘hello world’) The program will exit after printing the hello world and will not print
sys.exit() the bye world
print(‘bye world’)