Python Beginner
Python Beginner
1. String.
2. List.
3. Tuple.
4. Set
5. Dictionary.
Numbers -- Number data types store numeric
values. They are immutable data types, means
that changing the value of a number data type
results in a newly allocated object.
• For example −
• var1 = 1
• var2 = 10
• You can also delete the reference to a number
object by using the del statement.
• The syntax of the del statement is −
• del var1[,var2[,var3[....,varN]]]]
• Python support four different numerical types:
1. int(signed integers)
2. Long(long integers)
3. Float(floating point real values)
4. Complex(complex numbers)
• Examples
• a=5
• Print(a,”is of type”, type(a))
a=2.0
Print(a,”is of type”, type(a))
a=1+2j
Print(a,”is complex number?”, isinstance(1+2j, complex))
Nested IF Statement:
Examples:
total = 100
#country = "US“
country = "AU“
if country == "US“
: if total <= 50:
print("Shipping Cost is $50")
elif total <= 100:
print("Shipping Cost is $25")
elif total <= 150:
print("Shipping Costs $5")
else:
print("FREE")
if country == "AU":
if total <= 50:
print("Shipping Cost is $100")
else:
print("FREE")
• Switch Statement:
A switch statement is a multi way branch
statement that compare the value of a
variable the value specified in case
statements.
Python language doesn’t have a switch
statement.
Python- loop statment
• A loop statement allows us to execute a
statement or group of statements multiple times.
For Loop: Executes a sequence of statements
multiple times and abbreviates the code that
manages the loop variable.
• While Loop: Repeats a statement or group of
statements while a given condition is loop body.
TRUE. It tests the condition before executing
the
• Examplers:
1. Ex. For loop: fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
my_function("Emil")
my_function(“Twitter")
my_function("Linus")
• Output:
The return Statement
• The statement return [expression] exits a function, optionally passing back
an expression to the caller. A return statement with no arguments is the
same as return None.
Example:
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;
# Now you can call sum function
total = sum( 10, 20 );
print "Outside the function : ", total
OutPut: Inside the function : 30
Outside the function : 30
Python –OOPs Concepts
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the
printname method:
x = Person(“john", “Doe")
x.printname()
Create a Child class:
Examples:
• To create a class that inherits the functionality from another
class, send the parent class as a parameter when creating the
child class.
• Create a class named Student, which will inherit the
properties and methods from the Person class.
class Student(Person):
pass
Python - Encapsulation
Encapsulation means that the internal representation of on
object is generally hidden from view outside of the object’s
definition.
Encapsulation:we can restrict access to methods and variables.
This prevent data from direct modification which is called
encapsulation
In Python, we denote private attribute using underscore as prefix
i.e single “ _ “ or double “ __“.
• Example:
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
Python- Regular Expr
• A RegEx, or Regular Expression, is a sequence of characters
that forms a search pattern.
• RegEx can be used to check if a string contains the specified
search pattern.
RegEx Module
• Python has a built-in package called re, which can be used to
work with Regular Expressions.
• Import the re module
import re
RegEx in Python:
When you have imported the re module, you can start using regular
expressions:
• Example
Search the string to see if it starts with "The" and ends with
"Spain"
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
• RegEx Functions:
1. Findall: Returns a list containing all matches
2. Search: Returns a match object if there is a
match anywhere in the string.
3. Split: Returns a list where the string has been
split at each match
4. Sub: Relplaces one or many matches with a
string.
Examples:
1. import re
str = "The rain in Spain"
x = re.findall("ai", str)
print(x)
• import re
str = "The rain in Spain"
x = re.search("\s", str)
print("The first white-space character is located in position:", x.start())
3.import re
str = "The rain in Spain"
x = re.split("\s", str)
print(x)
Output:====
4. import re
str = "The rain in Spain"
x = re.sub("\s", "9", str)
print(x)
Python –File Handling
2. f = open("demofile.txt", "r")
print(f.readline())
f.close()
Python- file write
• 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
Examples:f =
open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
• gedit web-s.py
• Now, let’s write our code in this file.
• First, let us import all the necessary libraries:
driver = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver")
products=[] #List to store name of the product
prices=[] #List to store price of the product
ratings=[] #List to store rating of the product
driver.get("https://www.flipkart.com/laptops/~buyback-guarantee-on-laptops-
/pr?sid=6bo%2Cb5g&uniq"
content = driver.page_source
soup = BeautifulSoup(content)
for a in soup.findAll('a',href=True, attrs={'class':'_31qSD5'}):
name=a.find('div', attrs={'class':'_3wU53n'})
price=a.find('div', attrs={'class':'_1vC4OE _2rQ-NK'})
rating=a.find('div', attrs={'class':'hGSR34 _2beYZw'})
products.append(name.text)
prices.append(price.text)
ratings.append(rating.text)
• Step 5: Run the code and extract the data
• To run the code, use the below command:
python web-s.py
• Step 6: Store the data in a required format
• After extracting the data, you might want to store it in a
format. This format varies depending on your requirement.
For this example, we will store the extracted data in a CSV
(Comma Separated Value) format. To do this, I will add the
following lines to my code:
df=pd.DataFrame({'ProductName':products,'Price':prices,'Ra
ting':ratings})
df.to_csv('products.csv', index=False, encoding='utf-8')
• Now, I’ll run the whole code again.
• A file name “products.csv” is created and this file contains the
extracted data.