100% found this document useful (1 vote)
23 views

Python Course

Uploaded by

alt.nq-4o3am7yj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
23 views

Python Course

Uploaded by

alt.nq-4o3am7yj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 107

MPRASHANT

PYTHON SCRIPTING
MPRASHANT

Why Python?
MPRASHANT

Easy to read and learn


Various existing libraries and frameworks
Large community and documentation
Automate our day to day task
Can create GUI based apps, websites and
games
MPRASHANT

Python Installation &


Setup
Python on LINUX
MPRASHANT

SENDING OUTPUT print("Hello World!")


TO TERMINAL..
MPRASHANT

Using #
#This is a singleline comment

Multi-line comment
COMMENTS
"""
first line
your comment here
last line
"""
Variables
MPRASHANT

name="Paul"
WHAT ARE
VARIABLES? print(name)
MPRASHANT

Should not start with

VARIABLES number

RULE No space
No special character
MPRASHANT

name="Paul"

TYPES OF age=30

DATA IN price=25.5
VARIABLES? bol=True/False
MPRASHANT

Check type of data


WHAT ARE
VARIABLES? print(type(age))
MPRASHANT

a=10
b=2

ARITHMETIC print(a+b)
OPERATIONS?
We can perform
+,-,/,*
MPRASHANT

To find the
ARITHMETIC 2^5
OPERATIONS print(2**5)
// AND **
MPRASHANT

2 × (3 + 4)² ÷ 5 - 6
ARITHMETIC
OPERATIONS BODMAS rule
MPRASHANT

PRINTING name="Paul"
STRING
print(f’My name is {name}’)
VARIABLE
String Operations
Strings are immutable

We can use ‘Hello’ or “Hello”

Use + to add two strings ‘Hello’ + ‘World’


MPRASHANT

msg="Hello World!"

msg.lower()
STRING msg.upper()
OPERATIONS msg.title()

msg.split()
Lists
Ordered Sequence of different types of values
MPRASHANT

How to define a List?


users=['raju', 'sham', 'paul']

LISTS How to get values from a list?


users[0]
users[1]
users[-1]
MPRASHANT

Adding item to a List?


users.append('alex')

LISTS How to delete values from a list?


users.remove('raju')
MODIFY
How to modify values from a list?
users[1]="Shan"
MPRASHANT
Adding item to a List at given position?
users.insert(1, 'shanu')

How to delete values from a list using

LISTS index no?

MODIFY del users[2]

Length of list
len(users)
MPRASHANT

Sorting the items in list?


users.sort()
users.sort(reverse=True) or

LISTS users.reverse()

SORTING
Temporary sorting of items?
print(users.sorted())
MPRASHANT

Popping the items in list?

LISTS users.pop()
users.pop(2)
MPRASHANT
Getting first two items
users[:2]

Getting middle 3 items


SLICING users.[1:4]

LISTS
Getting last 2 items
users.[-2:]
MPRASHANT
sell=[2, 9, 13, 28, 35, 4, 56]

Getting min or max


min(sell)
NUMERIC max(sell)

LISTS
Getting sum of items
sum(sell)
Tuples
MPRASHANT

Same as list, however you can't


modify the items of Tuple.

TUPLES Immutable
Ordered

days=('mon', 'tue', 'wed')


Dictionaries
key:value
MPRASHANT

DICTIONARY
car={'brand':'Audi', 'model':'Q3'}

print("Brand of car is " + car['brand'])


print("Model of car is " + car['model'])
MPRASHANT

DICTIONARY
car.get('brand')

By using the get() function, if key


is not present it return none rather
than error.
MPRASHANT

Adding item to a Dictionary?


car['color']="Red"

DICTIONARY
MODIFY How to delete values from a
dictionary?
del car['brand']
MPRASHANT

Getting no. of key-value a

DICTIONARY Dictionary?

LENGTH len(car)
Sets
Unordered and Unique elements
MPRASHANT

SETS my_set = {’A’, ‘B’, ‘C’}


User Interaction
MPRASHANT

TAKING INPUT
FROM USER...
name = input("What's your name? ")
age = int(input('Your age'))
Conditional Statement
MPRASHANT

if age >= 18:


print("You can vote!")
IF-ELSE else:
print("You can't vote!")
MPRASHANT
users=['paul', 'raju', 'sham']
if 'paul' in users:
print("User Exist")
--------------------------------

IF-ELSE elist=[]
if elist:
print('List is not empty')
else:
print('List is empty')
MPRASHANT

Equal x == 20

Greaterthanorequalto x >= 20

OPERATORS
Lessthanorequalto x <= 50

Not Equal x != 20

Greater Than x > 20

Less Than x < 20


MPRASHANT

if marks >= 80:

print("1st Division")

elif marks >= 60:


ELIF print("2nd Division")
else:
print("Failed!")
If-else Nesting
Logical Operators
and, or
MPRASHANT

condition1 and condition2

If both conditions are true then


true else false
LOGICAL
OPERATORS condition1 or condition2

If any of the condition is true


then true
For Loop
Execute a block of code for each item in the
sequence
(such as a list, tuple, string, or range)
MPRASHANT

for i in 1,2,3,4,5:
print(i)

Other ways to write For loop


FOR LOOP
num=[1,2,3,4,5]
for i in num:
print(i)
MPRASHANT

Other ways to write For loop

age_info={'Raju':25, 'Sham':30}

for name, age in age_info.items():


FOR LOOP print("Age of " + name +
"is " + age)

for name in age_info.keys():


for age in age_info.values():
FizzBuzz Program
The program should add numbers from 1 to
a specified number in a list.
For multiples of 3, it should be "Fizz,"
For multiples of 5, it should be "Buzz,"
For numbers multiples of both 3 and 5, it
should be "FizzBuzz."
Print the list
While Loop
MPRASHANT count=1

while count <= 5:


print(count)
count += 1
WHILE
LOOP -------------------------------
msg=''
while msg != 'quit':
msg = input("Your message..")
print(msg)
MPRASHANT

active=True

while active:
WHILE msg = input("Your message..")

LOOP if msg == 'exit':


active=False
MPRASHANT

num=[1, 29, 20, 29, 40, 50, 29]

WHILE while 29 in num:


num.remove(29)
LOOP
MPRASHANT

break - to stop the loop

USEFUL
continue - to stop current iteration
CONCEPTS...
of loop and start next iteration
MPRASHANT

msg=''

while True:
BREAK msg = input("Your message..")
if msg == 'exit':
break
else:
print(msg)
MPRASHANT
users=[]
name=''

while True:
name = input("Your name..")
if msg == 'exit':
CONTINUE break
elif name in users:
print("User already exist")
continue
else:
print(name)
Functions
MPRASHANT

Block of code which perform some


task and run when it is called.
Can be reuse many times in our
WHAT ARE
program which lessen our lines of
FUNCTIONS?
code.
We can pass arguments to the method
MPRASHANT

Defining a Function
def myfun():
print("Function is called")
HOW TO MAKE
FUNCTIONS?
Calling a Function
myfun()
MPRASHANT

Defining a Function
def user_info(name, age):
print("Name is "+ name)
ARGUMENTS
print(f"Age is {age}")
PASSING
FUNCTIONS?
Calling a Function
user_info('raju', 30)
MPRASHANT

Defining a Function
def user_info(name, age=20):
print("Name is "+ name)
DEFAULT
VALUES print(f"Age is {age}")

FUNCTIONS?
Calling a Function
user_info('sham')
MPRASHANT

Defining a Function
def user_info(name, age=None):
print("Name is "+ name)
NONE
ARGUMENT if age:

FUNCTIONS? print(f"Age is {age}")

Calling a Function
user_info('sham')
MPRASHANT

def addition(num1, num2):


sum = num1 + num2

RETURN return sum

RESULT IN
FUNCTIONS? print(addition(10, 20))
MPRASHANT

def car_detail(brand, *features):


print(f"Car brand - {brand}")
for feature in features:
DYNAMIC print(f" - {feature}")
ARGUMENTS
FUNCTIONS car_detail('Audi', 'Sunroof')
car_detail('Tata', '360cam',
* 'safe')
MPRASHANT

DYNAMIC
ARGUMENTS
FUNCTIONS

**
MPRASHANT Make a file named cal.py

def addition(num1, num2):


sum = num1 + num2
FUNCTIONS return sum
AS
MODULE ------------------------
import cal

cal.addition(10, 20)
We can pass list as argument in a function
Object Oriented Programming

Classes
Objects
Classes
A class is a blueprint or a template for
creating objects and it defines the
structure and behaviour of that objects.
Objects
An object is an instance of a class. with its
own unique data and the ability to
perform actions
Objects

Class emp1
name
email
dept
salary
Employees
emp2
Creating Objects
Modifying Attributes
Working with FILES
Writing into a File
Reading from a File (whole content)
Reading from a File (line by line)
Exceptional Handling
Python Modules &
Packages
Python Built-in Module
random
datetime
Dice Game
What is PyPI & PiP
Most powerful and flexible open source
data analysis / manipulation tool
Print the csv file
Print only salary column
Find min and max salary
Find data of employee with
Emp_id 105
Max salary
Find total & average salary of employees
Print full name of employee id 103
Change the salary of Sham to 80000
Remove the data of Leena
Sort the data with salary (min to max)
Add a new column ‘bonus’ with value 10%
of salary
Drop the ‘salary’ column
Working with EMAILS
Weather Checking App
Working with API
Assignment
Create a Calculator Program
Python Program to Run
Linux Commands
MPRASHANT

THANK YOU

You might also like