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

Module 6 Python

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

Module 6 Python

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

Introduction to Different Numeric Types

There are three numeric types in Python:


int
float
complex
Variables of numeric types are created when you assign a value to
them

Example:
x = 1 # inty = 2.8 # floatz = 1j # complex

Ch .Venkata RamiReddy Department Of Computer Science


Introduction to Different Numeric Types
Int
Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length

x = 1y = 35656222554887711z = -3255522print(type(x))print(type(y))print(type(z))

Ch .Venkata RamiReddy Department Of Computer Science


Introduction to Different Numeric Types
Float
Float, or "floating point number" is a number, positive or negative, containing one
or more decimals.

x = 1.10y = 1.0z = -35.59print(type(x))print(type(y))print(type(z))

Ch .Venkata RamiReddy Department Of Computer Science


Introduction to Different Numeric Types
Complex
Complex numbers are written with a "j" as the imaginary part:

x = 3+5jy = 5jz = -5jprint(type(x))print(type(y))print(type(z))

Ch .Venkata RamiReddy Department Of Computer Science


Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
#convert from int to float:
x = float(1)
#convert from float to int:
y = int(2.8)
#convert from int to complex:
z = complex(1)
print(x)
print(y)
print(z)
print(type(x))
1.0
print(type(y)) 2
print(type(z)) (1+0j)
<class 'float'>
<class 'int'>
<class 'complex'>

Ch .Venkata RamiReddy Department Of Computer Science


525

Mathematical Functions
The min() and max() functions can be used to find the lowest or highest value in an iterable:

x = min(5, 10, 25)


y = max(5, 10, 25)
print(x)
print(y)
5
25
The math.ceil() method rounds a number upwards to its nearest integer, and
the math.floor() method rounds a number downwards to its nearest integer, and returns
the result:

import mathx = math.ceil(1.4)y = math.floor(1.4)print(x) # returns 2print(y) # returns 1

Ch .Venkata RamiReddy Department Of Computer Science


525

Mathematical Functions
The math.fmod() method returns the remainder (modulo) of x/y.
import math# Return the remainder of x/y
print(math.fmod(20, 4))
print(math.fmod(20, 3))
0
2

import math
print(math.pow(2, 3)) #8

import math
print (math.sqrt(9)) #3
print (math.sqrt(25)) #5

Ch .Venkata RamiReddy Department Of Computer Science


Mathematical Functions
import math
#Return factorial of a number
print(math.factorial(3)) #6
print(math.factorial(5)) #120

import math
T= (1, 2, 3)
L = (3, 4, 5)
#Return the product of the elements
print(math.prod(T)) #6
print(math.prod(L)) #60

Ch .Venkata RamiReddy Department Of Computer Science


Random Numbers
randint():Returns a random number between the given range
import random
#returns a number between 3 and 9 (both included)
print(random.randint(3, 9))
random(): Returns a random float number between#4 0 and 1
import random
print(random.random()) #0.627
choice() : The choice() method returns a randomly selected element from the specified
sequence.
import random
mylist = ["apple", "banana", "cherry"]
print(random.choice(mylist))

apple

Ch .Venkata RamiReddy Department Of Computer Science


Python program where the user has to guess a randomly generated
number
import random
def guess_the_number():
# Generate a random number between 1 and 100
secret_number = random.randint(1, 100)

print("Welcome to Guess the Number Game!")


attempts = 0
while True:
# Get user's guess
guess = int(input("Enter your guess: "))
attempts += 1
# Check if the guess is correct
if guess == secret_number:
print(f"Congratulations! You guessed the number in {attempts} attempts.")
break
elif guess < secret_number:
print("Too low. Try again.")
else:
print("Too high. Try again.")
guess_the_number()

Ch .Venkata RamiReddy Department Of Computer Science


Strings
String is sequence/array of characters.
Strings in python are surrounded by either single quotation marks, or double
quotation marks.
a=‘hello’ b=“Python”

Ch .Venkata RamiReddy Department Of Computer Science


Indexing, and Slicing
str = 'programiz'
print( str[0])
print(str[-1])
print(str[:3] ) p
z
print(str[4:] ) pro
print(str[1:5] ) ramiz
rogr
print(str[5:-2]) am
print( str * 3) programizprogramizpro
gramiz

Ch .Venkata RamiReddy Department Of Computer Science


Operations on Strings
Compare Two Strings
We use the == operator to compare two strings. If two strings are equal, the
operator returns True. Otherwise, it returns False.

Example:
str1 = "Hello, world!"
str2 = "I love Python."
str3 = "Hello, world!"

# compare str1 and str2


print(str1 == str2)

# compare str1 and str3 False


print(str1 == str3) True

Ch .Venkata RamiReddy Department Of Computer Science


Operations on Strings
Join Two or More Strings
In Python, we can join (concatenate) two or more strings using
the + operator.

greet = "Hello, "


name = "Jack"
result = greet + name
print(result)

# Output: Hello, Jack

Ch .Venkata RamiReddy Department Of Computer Science


Operations on Strings
Python String Length
In Python, we use the len() method to find the length of a string.
greet = 'Hello’
print(len(greet)) # Output: 5
String Membership Test
We can test if a substring exists within a string or not, using the keyword in
Example:
in:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.") not in:
else: txt = "The best things in life are free!"
print("Yes, 'free' is not present.")
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")

Ch .Venkata RamiReddy Department Of Computer Science


Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Syntax:
for variable in String:
print(variable)
Ex:

str="Python"
for i in str: P
print(i) y
t
h
o
n

Ch .Venkata RamiReddy Department Of Computer Science


Looping Through a String Programs

1. Write a python program to count no of a’s in your name?


Ex: Devansh o/p: 1

2. Write a python program to remove the vowels in the given string


3 . Write a pthon program Remove Punctuations From a String
I/P: "Hello!!!, he said ---and went.“
O/P: Hello he said and went

Ch .Venkata RamiReddy Department Of Computer Science


Write a python program to count no of a’s in your name?

name= "Havya"
count=0
for char in name:
if char== 'a':
count=count+1
print("No of a in my name is:",count)

No of a in my name is: 2

Ch .Venkata RamiReddy Department Of Computer Science


Program to remove the vowels in the given string

vowels="aeiou"
my_str = "Hello I am Devansh"
no_vowel = ""
for char in my_str:
if char not in vowels:
no_vowel= no_vowel + char
print(no_vowel)

Hll I m Dvnsh

Ch .Venkata RamiReddy Department Of Computer Science


Program Remove Punctuations From a String

punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
my_str = "Hello!!!, he said ---and went."
no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char
print(no_punct)

Output:
Hello he said and went

Ch .Venkata RamiReddy Department Of Computer Science


Python String Methods
count():The count() method returns the number of times a specified value appears in the
string.
txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple")
print(x)
O/P: 2
capitalize() :It converts the first character of a string to upper case and the rest is lower
case.

txt = "python is FUN!"


x = txt.capitalize()
print (x)

O/P: Python is fun!

Ch .Venkata RamiReddy Department Of Computer Science


Python String Methods
The startswith() method returns True if the string starts with the specified value,
otherwise False.
txt = "welcome to my world."
x = txt.startswith("wel")
print(x)
O/P: True
The endswith() method returns True if the string ends with the specified value,
otherwise False.

txt = "Hello, welcome to my world."


x = txt.endswith("world.")
print(x)

O/P: True

Ch .Venkata RamiReddy Department Of Computer Science


Python String Methods
find():Searches the string for a specified value and returns the position of first occurrence where it
was found
The find() method returns -1 if the value is not found.
rfind(): Searches the string for a specified value and returns the position of last occurrence where it
was found

txt = "Hello, welcome to my world." 1


x = txt.find("e") 13
y = txt.rfind("e")
print(x)
print(y)

index():Searches the string for a specified value and returns the position of first occurrence where it was found
The index() method returns exception if the value is not found.

txt = "Hello, welcome to my world."


x = txt.index("o")
O/P: 4
print(x)

Ch .Venkata RamiReddy Department Of Computer Science


Python String Methods
split():Splits the string based on separator, and returns a list

Ex1:
txt = "welcome to the Python Class"
x = txt.split()
print(x) O/P: ['welcome', 'to', 'the', 'Python', ‘Class']

Ex2:

txt = "hello, my name is Peter, I am 26 years old"


x = txt.split(", ")
print(x)
['hello', 'my name is Peter', 'I am 26 years old']

Ch .Venkata RamiReddy Department Of Computer Science


Python String Methods
strip() removes any spaces at the beginning and at the end of the string
lstrip() Remove spaces to the left of the string:
rstrip() Remove spaces to the right of the string

txt = " banana "


x = txt.strip()
y = txt.lstrip()
z = txt.rstrip()
print(x)
print(y)
print(z) banana
banana
banana

Ch .Venkata RamiReddy Department Of Computer Science


Python String Methods
The replace() method replaces a specified value with another value. .
txt = "one one was a race horse"
x = txt.replace("one", "three")
print(x)
O/P: three three was a race horse
upper() : Converts a string into upper case

txt = "Hello my friends"


x = txt.upper()
print(x)
O/P: HELLO MY FRIENDS
lower() :Converts a string into lower case

txt = "Hello my FRIENDS"


x = txt.lower()
print(x)
O/P: hello my friends

Ch .Venkata RamiReddy Department Of Computer Science


Python String Methods
The join() method takes all items from list/tuple and joins them into one string.

mylist = ["John", "Peter", "Vicky"]


x = " ".join(mylist)
print(x)
O/P: John Peter Vicky

Ch .Venkata RamiReddy Department Of Computer Science


Program to sort alphabetically the words form a string
Version-1: a
my_str = "hi this is a python class" class
words= my_str.split() hi
is
words.sort() python
this
for i in words:
print(i)

Version-1:
ori_str = "hi this is a python class"
words= ori_str.split()
words.sort()
sor_str=" ".join(words)
print("Orginal:",ori_str)
print("After Sorting:",sor_str) Orginal: hi this is a python class
After Sorting: a class hi is python this

Ch .Venkata RamiReddy Department Of Computer Science


File Handling
A file is the collection of data stored on a disk in one unit identified by filename

Types of files
file attributes:
1. Name: File name is the name given to the file. A name is usually a string of characters.
2. Identifier: Identifier is a unique number for a file. It identifies files within the file system. It is
not readable to us, unlike file names.
3. Type: Type is another attribute of a file which specifies the type of file such as archive file
(.zip), source code file (.c, .java), .docx file, .txt file, etc.
4. Location: Specifies the location of the file on the device (The directory path). This attribute is
a pointer to a device.
5. Size: Specifies the current size of the file (in Kb, Mb, Gb, etc.) and possibly the maximum
allowed size of the file.
6. Protection: Specifies information about Access control (Permissions about Who can read,
edit, write, and execute the file.) It provides security to sensitive and private information.
7. Time, date, and user identification: This information tells us about the date and
time on which the file was created, last modified, created and modified by which user, etc.
File I/O-Opening and Closing files
In Python, we use the open() method to open files.
open() returns a “file handle/pointer” is a variable used to perform operations
on the file.
A file handle or pointer denotes the position from which the file contents will be
read or written.
When file is opened, file pointer points to the beginning of the file.

Syntax: f= open(filename, mode)


In mode, we specify whether we want to read 'r', write 'w' or append 'a' to the
file.

Example:

f = open("demofile.txt", "r")
File I/O-Opening and Closing files
File I/O-Opening and Closing files

close(): Closes an opened file.


f = open("demofile.txt", "r")
f.close()
Write Operations: write()

The write() function writes any string to an open file.


To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content

Syntax : filehandle.write(string);
Here, string parameter is the content to be written into the opened
file.

Ch .Venkata RamiReddy Department Of Computer Science


Write Operations: write()

Ex: Open the file “first.txt" and overwrite the content

f = open('first.txt' , 'w')
str = "Hello Welcome to Python class"
f.write(str) first.txt
Hello Welcome to Python class
f.close()

Ex: Open the file “first.txt" and append the content

f = open('first.txt' , 'a')
str = " File Handling"
f.write(str)
f.close() first.txt
Hello Welcome to Python class File Handling

Ch .Venkata RamiReddy Department Of Computer Science


Read Operations: read()

The read() method reads a data from an open file.


To read a file in Python, we must open the file in reading mode.
Syntax: filehandle.read([count]);
f = open( 'first.txt' , 'r’) O/P: Hello Welcome to Python class File
str1 = f.read() Handling
print(str1)
f.close()

Read only Parts of the File:

f = open( 'first.txt' , 'r')


str1 = f.read(5)
print(str1) O/P:
f.close() Hello

Ch .Venkata RamiReddy Department Of Computer Science


Read Operations: readline()

Using the readline() method, we can read a file line by line.


by default, this method reads the first line in the file.
For example, If you want to read the first five lines from a text file, run a loop five
times, and use the readline() method in the loop’s body.
Using this approach, we can read a specific number of lines.

Reading First N lines From a File Using readline():

f = open( ‘crickter.txt' , 'r')


for i in range(3):
print(f.readline()) O/P:
f.close() Sachin
Dravid
Ganguly

Ch .Venkata RamiReddy Department Of Computer Science


Read Operations: readlines()
readlines() method read entire file contents line by line into a list.

f = open( 'crickter.txt' , 'r') O/P:


print(f.readlines()) ['Sachin\n', 'Dravid\n', 'Ganguly\n', 'Laxman']
f.close()

Reading last N lines from a file

N=2
f = open( 'crickter.txt' , 'r') O/P:
print(f.readlines()[N:]) ['Ganguly\n', 'Laxman']
f.close()

Reading File in Reverse Order

f = open( 'crickter.txt' , 'r') O/P:


lines = f.readlines() Laxman
rev_lines=reversed(lines) Ganguly
for i in rev_lines: Dravid
print(i) Sachin
File Positions: seek()
The seek() function sets/change the position of a file pointer.
Syntax:
f.seek(offset, whence)
How many points the pointer will move is computed from
adding offset to a reference point; the reference point is given by
the whence argument
A whence value of 0 means from the beginning of the file.
A whence value of 1 uses the current file position
A whence value of 2 uses the end of the file as the reference point.
File Positions: seek()
f = open( 'second.txt' , 'r')
# read all characters from file
str1 = f.read()
print("Before:",str1)

f.seek(5)
str2 = f.read()
print("After Seek:",str2)

f.seek(0,2)
Before: Hello this is VIT-AP University
str3 = f.read() After Seek: this is VIT-AP University
print("AFter End:",str3) AFter End:
f.close()

Ch .Venkata RamiReddy Department Of Computer Science


Renaming and Deleting Files
rename() method is used to rename a file
remove() function is used to delete a file
These methods are a part of the os module

Ex:
import os
os.rename("one.txt","two.txt")
os.remove("three.txt")

Ch .Venkata RamiReddy Department Of Computer Science


Write a Python program to read first n lines of a file.
n=2
f = open( 'crickter.txt' , 'r')
lines=f.readlines()[:n]
O/P:
for i in lines: Sachin
Dravid
print(i)
f.close()

Ch .Venkata RamiReddy Department Of Computer Science


Program to count the no of lines ,words and characters in a file
f = open( 'crickter.txt' , 'r')
contents=f.readlines()
NW=0
NC=0
NL=0
for line in contents:
NL=NL+1
words=line.split()
NW=NW+len(words)
NC=NC+len(line)
print("Number of Lines:",NL) O/P:
Number of Lines: 4
print("Number of Words:",NW) Number of Words: 4
Number of Characters: 28
print("Number of Characters:",NC)
f.close()

Ch .Venkata RamiReddy Department Of Computer Science


Write a python program copy one file content into another file.

f1=open("crickter.txt","r")
f2=open("cri.txt","a")
line=f1.read()
f2.write(line)

Ch .Venkata RamiReddy Department Of Computer Science


Working with CSV files in Python

CSV (Comma-Separated Values) is one of the file formats for storing and
exchanging tabular data.

Reading CSV files Using csv.reader()


To read a CSV file in Python, we can use the csv.reader() function.

import csv
f=open('protagonist.csv', 'r’)
reader = csv.reader(f)
for row in reader: O/P:
print(row) ['SN', 'Movie', 'Protagonist']
['1', 'Lord of the Rings', 'Frodo Baggins']
['2', 'Harry Potter', 'Harry Potter']

Ch .Venkata RamiReddy Department Of Computer Science


Working with CSV files in Python

Writing CSV files Using csv.writer():


To write to a CSV file in Python, we can use the csv.writer() function.
The csv.writer() function returns a writer object that converts the user's data into
a delimited string.
This string can later be used to write into CSV files using the writerow() function.

import csv
f=open('protagonist.csv', 'w’)
writer = csv.writer(f)
writer.writerow(["SN", "Movie", "Protagonist"])
writer.writerow([1, "Lord of the Rings", "Frodo Baggins"])
writer.writerow([2, "Harry Potter", "Harry Potter"])

Ch .Venkata RamiReddy Department Of Computer Science


Working with CSV files in Python

Writing multiple rows with writerows():

import csvf=open('protagonist.csv', 'w’)


writer = csv.writer(f)
csv_rowlist = [["SN", "Movie", "Protagonist"], [1, "Lord of the Rings", "Frodo Baggins"],
[2, "Harry Potter", "Harry Potter"]]
writer.writerows(csv_rowlist)

Ch .Venkata RamiReddy Department Of Computer Science


various directory handling functions

Creating a Directory
import os
os.mkdir('mydir’)

Get Current Working Directory


import os
Current working directory: C:\Users\chvrr
cwd = os.getcwd()
print("Current working directory:", cwd)

Listing Files and Directories


import os
print(os.listdir('.'))

Ch .Venkata RamiReddy Department Of Computer Science


various directory handling functions

Change Directory
import os
os.chdir('mydir’)

Renaming a Directory
import os
os.rename('mydir','mydir2’)

Deleting a Directory
import os
os.rmdir('mydir’)

Ch .Venkata RamiReddy Department Of Computer Science

You might also like