Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
34 views

Python

The document discusses Python programming and its features. Python is an open source, interpreted, high-level programming language. It has gained popularity due to its extensive library packages and can be used for software development, web development, data analysis, and more.

Uploaded by

alonelife
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Python

The document discusses Python programming and its features. Python is an open source, interpreted, high-level programming language. It has gained popularity due to its extensive library packages and can be used for software development, web development, data analysis, and more.

Uploaded by

alonelife
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 36

Python programming

· Futualistic and popular

· Because of its popularity, many peoples, companies etc makes projects using python

· Developed by Guido van Rossum , 1991

· 2002, 2003, 2005, 2010

· Since 2017, top programming language

· Most popular feature – library packages

Library packages

· It is due to the packages, many applications are developed

· Today python is having 2500-3000 packages

Two types of packages

1. in built packages

2. user defined packages

· Python – open source software – can download for free

· A mix up language

Python+html

Python+java

· Faster execution

· Error finding is easy due to some availabilities

· Python can be done on software, online compilers , mobile applications

· Python – 3x series, 2x series, pycharms

· www.python.org

· 3.10.0 version

· Python can work in two modes

· Script mode - can save programs


· Shell mode/ command line interpreter – instant output or cannot save program

Basic I/O operations -

· Input operations-

· Syntax – input()

· Eg.1:- Add two numbers

A=7

B=7

Print(a+b)

Output = 14

· eg. 2. Add two strings

A=”hari”

B=”krishnan”

Print(a+b)

Output = harikrishnan

# STRINGS WILL JOIN IN OUTPUT

· eg. 3 .

A=8

B=9

Print(“a+b”)

Output= a+b

# A+b is considered as a string because of quote

· eg. 4.

A=input(“enter any numbers:”)

B=input(“enter any numbers:”)


Print(a+b)

output

Enter any numbes: 20

Enter any numbers: 40

2040

#Addition not processed because of we gave input as strings

· eg. 5.

A=int(input(“enter any numbers:”))

B=int(input(“enter any numbers:”))

Print(a+b)

Output

Enter any numbers: 20

Enter any numbers:40

60

#To show number as output or to understand to python, we can give


int instructions (non-decimal numbers)

#To perform with decimal numbers, we can use the instruction – float
(absolute numbers)

· eg.6.

A=float(input(“enter any value:”))

B=float(input(“enter any value:”))

Print(a+b)

Output

Enter any value:8.7

Enter any value:5.9


14.6

· Output operations -the command which we use for getting the things printed when we enter in
idle or command line interpreter is the print function which is the output function of python

print()

· print() function can be used for two purposes

1. data will be shown as same what we type in idle or command line

eg:- print(“hareena”)

2. processed results will be shown from the given contents

· Idle .> file > new file > new window > enter program > run > run module 5 > save > output

Examples

1. Print(“hareena”) - output – hareena

2. Print(‘nitheesh’) - nitheesh

· If we type without single and double quotes, we didn’t get output

Eg;- print(anu) --------- error output

Eg:-

anupama=4 ( anupama is considered as a variable to store a number, not a string)

Print(anupama)

Output = 4

· If we give without quotes, then a value must be assigned

· If we give quote, then that same content will be printed

· If we give without quotes, then results will be processed, if there is any value, it will be
processed and output will be given

Eg:-

r=4
Print(“r”)

Output – r

DATA TYPE MODELS IN PYTHON

· In what always python accepts input or in what always we can give input

Data types models

1. list

2. tuple

3. set

4. dictionary

5. string

6. int

7. float

List

· It is used to store multiple items in a single variable

· eg.

1. A=["bus”,”car”,”truck”,”motorcycle”]

Print(type(a))

Output= <class “list”>

#A is a variable which is used to store items such as bus, truck, car and
motorcycle

2. raj=["apple”,”orange”,”cherry”]

Print(type(raj))

Output= <class ‘list’>

· To find the length of list

1. A=["apple”,”car”,”orange”,”cherry”]
Print(len(a))

Output=4

Tuple

· It is used to store multiple items in a single variables

· It is one of the commonly used built in datatype of python

· Tuple is a connection which is ordered and unchangeable

· It is represented using round bracket

· Eg:-

1. A=("eye”,”ear”,”nose”,”head”)

Print(type(a))

Output=<class ‘tuple’>

2. To find the length of number of items in a tuple?

A=("apple”,”orange”,”cherry”,”mango”)

Print(len(a))

Output= 4

Set

· It is used to store multiple items in a single variable

· It is represented using { }

· It is unordered, unchangeable, unindexed

· Eg:-

1. A={“truck”,”car”,”bus”}

Print(type(a))

Output = <class ‘set’>

2. to find the length of set

A={“car”,”bus”,”truck”}
Print(len(a))

Output= 3

Dictionary

· It is used to store data values in key value pairs

· To create tables

· Eg:-

A={“name”:”sandra”,”age”:”21”,address”:”poolakkal house”} -

#name is the key , Sandra is the value

Print(type(a))

Output=<class ‘dict’>

Control flow in python

· How can we execute program code

· 2 types of control flow

1. Decision making

2. Looping structure

Decision making

· It produces true or false outcome

· Statements in decision making

1. If condition

· Syntax

If condition :

statement

· Eg:-1.

A=3
If a>0:

Print(“a is greater”)

Print(“a is positive number”)

Output = a is greater

A is positive number

· eg.2.

Vincy=-4

If vincy>0:

Print(“vincy is greater”)

Print(“vincy is a positive number”)

Output= no output

#Condition does not satisfy

2. if else statement

· Syntax

If condition:

Statement

Else :

Statement

Eg:-1.

A=-8

If a>0:

Print(“a is greater”)

Print(“a is a positive number”)

Else :

Print(“a is lesser”)
Output: a is lesser

eg.2.

a=6

If a=0:

Print(“a is equal”)

Else:

Print(“a is lesser”)

Output = syntax error

#Because of condition must be a==0

#Single= is not considered as equal to

eg.3

A=6

If a==6:

Print(“a is equal”)

Else:

Print(“a is lesser”)

Output= a is equal

3. If elif else statement

· it is used to check for multiple expressions

· Syntax

If condition:

Statements

Elif condition:

Statements

Else:
statements

Eg:- 1. eg.2

A=3.5 a=-4

If a>0: if a>0:

Print(“a is greater”) print(“a is greater”)

Elif a==0: elif a==0:

Print(“a is zero”) print(“a is zero”)

Else: else:

Print(“a is lesser”) print(“a is lesser”)

Output= a is greater output= a is lesser

4. Nested if statement

· When we use if inside another if

· Syntax

If condition:

If condition:

Statement

Else:

Statement

Else:

statement

Eg:- 1.

A=float (input(“enter a number:”))

If a>=0:

if a==0:
print(“a is zero”)

else:

print(“a is greater than zero”)

Else:

print(“a is lesser than zero”)

Output = enter a number: 1.67

A is greater than zero

Enter a number: -1.2

A is lesser tham zero

FOR LOOP IN PYTHON

· It is used for iterating over a sequence, means it travels throughout the sequence

· We can use list, string, set, dictionary in for loop

Eg:_

A=["apple”,”cat”,”dog”]

For x in a:

Print(x)

Output:- apple

Cat

Dog

· A is the list, x in a means- x is considered as individuals(apple cat dog)

· We can give not only c except a

· When we give multiple inputs and we need to get multiple outputs then we use for loop

Eg:-

Hareena=["car”,”bus”,”truck”]

For vincy in hareena:


Print(vincy)

Output- car

Bus

Truck

· How to use for loop in string

For x in “nadeeka”

Print(x)

Output=n

· Break statement in for loop

Giving a break inside a for loop

Eg:-’

a=["car”,”bus”,”cat”,”tiger”,”truck”]

for x in a:

print(x)

if x==”cat”:

break

output = car

bus

cat
A=["car”,”bus”,”tiger”,”truck”]

For x in a:

If x==”tiger”:

Break

Print(x)

Output= car

Bus

#Print gave after break so output excluding cat

21/06/2023

CONTINUE STATEMENT

· It is just opposite to break statement

· In this where we apply continue that item will not come in output

· Eg:-1. list

Hareena=["nitheesh”,”nadeeka”,”maria”,”anu”,”meera”]

For ancy in hareena:

If ancy==”maria”:

Continue

Print(ancy)

Output= nitheesh

Nadeeka

Maria

meera

#here didn’t display anu because of continue statement


· Eg 2. string

For vincy in “maria”:

If vincy==”i”:

continue

Print(vincy)

Output= m

RANGE FUNCTION

· It returns a sequence of numbers starting from zero and increments by 1 and ends at a specified
number.

· Ie., it will start from 0,1,2,3,4..........and ends at in any number

· Syntax

Range()

Eg.1.

For x in range(9):

Print(x)

Output= 0

7
8

Eg2.

For x in range(2,6):

Print(x)

Output= 2

#`Output in between 2 and 6

Eg.3.

For x in range(2,10,2):

Print(x)

Output = 2

Eg.4.

For x in range(4,20,5):

Print(x)

Output = 4

14

19

#Numbers b/w 4 and 20 with difference 5

FOR ELSE STATEMENT


Eg:

For x in range(8):

Print(x)

Else:

Print(“the-end”)

Output= 0

the-end

NESTED FOR LOOP

· A for loop inside another for loop

· Eg.

A=["red”,”yellow”,”white”,”orange”]

B=["car”,”bus”,”truck”]

For x in a:

For d in b:

Print(x,d)

Output=

Red car

Red bus
Red truck

Yellow car

yellow bus

yellow truck

White car

white bus

white truck

Orange car

orange bus

orange truck

PASS STATEMENT

· Empty or a blank loop is known as a pass statement

· For loops cannot be empty, but for some condition or reason a for loop with no content will be
put in the pass statement to avoid getting an error

· Eg.

For x in (0,1,2):

Pass

Output= blank output without error

· Eg.2.

For x in “raj”:

Pass

Output= blank

04/07/2023

· File Operations in Python

· To create a file using python software, create content, to edit texts etc
· To create a .txt file, pdf, word etc

· Steps will be the same for every file creation

· Python has several function for creating, reading, updating and deleting files

· We need a function

Open()

· It will take 2 parameters

-File name

-Mode

· Syntax

F=open()

F=open(“file name”,”mode”)

F=open(“raj.txt”,”r”)

· 4 types of mode

1. Read mode - “r”

it will open the file for reading

2. Append mode - “a”

already we have some contents in a file, for adding extra contents we use
append

3. Write - “w”

it will open the file for writing and create a file if it doesn’t exist

4. Create a file - “x”

it creates specified file and returns error if the file exist

Eg:-

F=open(“file source”,”r”)

Print(f.read())

Output – read specified file


F=open(“file source”,”r”)

Print(f.read(5))

Output= printing 5 letters in the document

· File source – eg:- C:/Users/haree/OneDrive/Documents/E waste trial.txt

· Counting space also

· To read a single line

F=open(“file source”,”r”)

Print(f.readline())

Print(f.readline())

· Append mode

F=open(“file source”,”a”)

F.write(“variables are used in python”)

F.close()

Output = file content replaced by variables are used in python

· Creating a file using python

· to delete file

Import OS

OS.remove(“file source”)

Output deleting file

CLASS BY NEW FACULTY

STRINGS
· List of characters in order-immutable

· Accessing values in a string (In python sting index starts from zero)

S=”Data Science World”

S[0]

S[5]

S[18]

S[19]

Print(“s[3]”,s[3])

· [:] slicing/ range operator

S=”Data Science World”

S[:]

Print(“s[5:12]”) , s[5:12] #upper bound exclusion

A=’welcome’

A[1:5]

A[:2] #same as a[0:2]

A[2:]

A[-1]

A[::-1] #reversing

· In/not-in operator (membership operator)

· Returns TRUE if letter exits in a given string otherwise retuns FALSE

A=’welcome’

Print(“w” in a)
Print(“s” in a)

K=”w” in a

· Not-in operator

Print (“w” not in a)

Print(“s” not in a)

Eg:-

S=”Data Science World”

‘Data science world’ ------output

S[0]

‘D’ -----o/p

S[0:3]

‘Dat’ ---------o/p

S[0:4]

‘Data’ -------o/p

S=”Data science World”

S[0:6]

‘Data S’ ---------o/p

· To find length of a string

A=’welcome’

L-len(a)

· To find occurrence of a given charater in a string

H=”hello"

Print(h.count(“l”))
· To find index of a given character in a string

Print(h.find(“l”))

F=”hai hello welcome”

Print(f.count(“ “))

02/08/2023

OPERATORS

· Arithmetic operators

· relational operators

· logical operators

· assignment operators

· bitwise operators

· special operators - membership operators and identical operators

ARITHMETIC OPERATORS

· + ----------- addition

· _ ------------substraction

· *------------multiplication

· /------------float division

· //-----------floor division

· %-----------modulus/remainder

· **----------exponentiation

c=a+b

a,b are operands

+ is the operator
a+b is the operation

eg:-

a=11

b=10

c=a+b

print("sum of {} and {} is {}") format(a,b,c)

3. 3+6

4. 6-4

5. 5/2 #float div

6. 5//2 # floor div

7. 10%3 # remainder

8. 2**3 # exponetiation

RELATIONAL OPERATOR

· USED TO COMPARE VALUES, RETURNS TRUE /FALSE AS RESULT

9. == equal to a==b

10. != not equal to a!=b

11. > greater than a>b

12. >= greater than or equal to a>=b

13. < less than a<b

14. <= less than or equal to a<=b

eg:-

a=9

b=7

c=a>b

output= true
· output will be true / false only

Eg:-

x=10

y=5

z=2

15. greater than

print(x>y) o/p--true

print(x>y>z) o/p--true

2. less than

print(x<y) o/p---false

print(y<x) o/p---true

3. equal to

print(x==y) #false

print(x==10) #true

4. not equal to

print(x!=y) #true

print(10!=x) #false

and so on

LOGICAL OPERATOR

· used to combine conditions

· AND, OR, NOT

OR

0+0 0

0+1 1
1+0 1

1+1 1

AND

0.0 0

0.1 0

1.0 0

1.1 1

eg:

1. a=5

b=0

c= a and b

output = 0

2. a=5

b=0

c=a or b

output= 5

3. a=1

not(a)|

4. a=0

not(a)

ASSIGNMENT OPERATOR
· To used to assign values to variables

a=7

print(a)

· compound assignment operators

1. a=a+5

a+=5

a output = 17

2. a=a-5

a-=5

a output=7

3. a=a*5

a*=5

a output=175

BITWISE OPERATORS

· &---bitwise AND (ampersand)

· |---bitwise OR

· ~---bitwise NOT(tilde symbol)

· >>---bitwise right shift

· <<---bitwise left shift

· bit numbers

0 0000

1 0001

2 0010

3 0011

4 0100
5 0101

6 0110

7 0111

8 1000

9 1001

10 1010

11 1011

12 1100

13 1101

14 1110

15 1111

a=10

b=4

· bitwise multiplication(AND)

0.0 0

1.0 0

0.1 0

1.1 1

c=a & b

c #0000

· bitwise addition(AND)

0+0 0

0+1 1

0+1 1

1+1 0
1+1+1 1

e=a^b

e #1110

· bitwise negation

a=10

~a - adding 1 in least b significant digit and add negative

output = -11

· bitwise shift

a=5 a in binary 0101

· bitwise right shift by one place

a>>1 output= 2

· bitwise left shift by one place

a=5

a<<1 output=10

SPECIAL OPERATORS

· identity operator-reference quality operator

· membership operator

· identity operator - is, is not

· used to check if 2 values are located in the same memory

1. a1=3

b1=3

print(a1 is b1) o/p = true

print(a1 is not b1) o/p= false

print(id(a1)) #memory address of a1 and b1 are same o/p=2350243840304


print(id(b1)) o/p= 2350243840304

2. a2='parvathy'

b2='renisha'

print(a2 is b2) o/p= false

print(a2 is not b2) o/p= true

print(id(a2)) o/p= 2350248865648

print(id(b2)) o/p= 2350251296176

· identity operator is not valid with lists

L1=[1,2,3]

L2=[1,2,3]

print(L1 is L2) o/p = false

print(L1 is not L2) o/p= True

print(id(L1)) 2350281340416

print(id(L2)) 2350279332800

· membership operator - in, not-in

to test whether the value or variable is present in a sequence

x='goodmorning'

print('G' in x) true

print('k' not in x) false

CONDITIONAL STATEMENT

· it performs different computations or actions depending on whether a specific boolean


constraint evaluates to true or false

1. simple if

in R {}

python intantation

x=1
if(x==10):

print('the value is 10')

2. if-else

x=1

if(x==10):

print('the value is 10')

else:

print('the value is not 10)

· if-else using minimal code

x=10

y=8

print("x is less than y" if(x<y) else "x is greater than y") # A if(condition) else B

o/p - x is greater than y

#s= "x is less than y" if(x<y) else "x greater than y"

#print(s)

· in another way

x=10

y=8

if(x<y):

print('x is less than y')

else:

print('x is greater than y')

o/p = x is greater than y

· to get user input

name=input("enter your name")


name

number=int(input("enter a number"))

number

type(number)

number_flt=float(input("enter a number")

number_flt o/p - enter a number type number

number_flt

displaying the number

type(number_flt) o/p - <class 'int'>

eg:- x=input('enter your name')

enter your name hareena

hareena

type(x)

<class 'str'>

3. if-elif-else

to check multiple conditions (more than 2)

number=int(input("enter a number"))

number

if(number>0):

print("number is positive")

elif(number<0):
print("number is negative")

else:

print("number is zeo")

eg:-

x=int(input("enter a numner"))

if(x>0):

print("number is positive")

elif(x<0):

print("number is negative")

else:

print("number is zero")

output= enter a number 23

number is positive

enter a number -12

number is negative

4. nested if-another if/if-else / if-elif-else case inside an if or else block

number=int(input("enter a number"))

number

if(number<0):

print("number less than 10")

else:

if(number=10):

print("number is 10")

elif(number>10 and Number<20):


print("number is between 10 and 20")

elif(number==20):

print("number is 20")

else:

print("number is greater than 20")

eg:-

x=int(input("enter a number"))

if(x<0):

print("x less than 10")

else:

if(x==10):

print("x is 10")

elif(x>10 and x<20):

print("x is between 10 and 20")

elif(x==20):

print("x is 20")

else:

print("x is greater than 20")

output= enter a number 32

x is greater than 20

· take input from user

ch=input("enter any character: ")

· check for uppercase , lowercase

if(ch.isupper()):
print(ch, "is UPPERCASE alphabet")

elif(ch,islower()):

print(ch, "is LOWERCASE alphabet")

elif(ch.isdigit()):

print(ch, "is a digit")

else:

print(ch,"a special character")

eg:

ch=input("enter any character")

if(ch.isupper()):

print(ch,"is UPPERCASE alphabet")

elif(ch.islower()):

print(ch, "is LOWERCASE alphabet")

elif(ch.isdigit()):

print(ch,"is a digit")

else:

print(ch, "a special character")

output = enter any characterHareena

Hareena a special character

enter any character321

321 is a digit

enter any characterHAREENA

HAREENA is UPPERCASE alphabet

HOMEWORK
1. Accept a string as user input. check that string with your name, if both matches then print "names are
same". if they do not match then print"names are different"

x=input("enter a name")

if(x==hareena):

print("names are same")

else:

print("names are different")

output= enter a name hareena

names are same

enter a name sandra

names are different

2. write a program to check whether the number that is taken as user input is odd or even

x=int(input("enter a number"))

if((x%2)==0):

print("number is even")

else:

print("number is odd")

3. A company insures its drivers in the following cases

- if the driver is married

- if the driver is unmarried , male & above 30 years of age

- if the driver is unmarried, female and above 25 years of age

in all other cases the driver is not insured . If the marital status, sex and age of the driver are the inputs,
write a program to determine whether the driver is to be insured or not
marital_status = input("Enter marital status (married/unmarried): ")

sex = input("Enter sex (male/female): ")

age = int(input("Enter age: "))

if marital_status == "married":

print("Driver is insured.")

elif marital_status == "unmarried":

if sex == "male" and age > 30:

print("Driver is insured.")

elif sex == "female" and age > 25:

print("Driver is insured.")

else:

print("Driver is not insured.")

else:

print("Driver is not insured.")

You might also like