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

Python File by MAK

The document provides information on various Python concepts including comments, variables, data types, functions, classes, and inheritance. It discusses how comments start with #, how variables are created without declaration, and how data types can change. Functions are defined using def and can take arguments. Classes use the class keyword and the __init__() method initializes properties. Inheritance allows a class to inherit methods from another class.

Uploaded by

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

Python File by MAK

The document provides information on various Python concepts including comments, variables, data types, functions, classes, and inheritance. It discusses how comments start with #, how variables are created without declaration, and how data types can change. Functions are defined using def and can take arguments. Classes use the class keyword and the __init__() method initializes properties. Inheritance allows a class to inherit methods from another class.

Uploaded by

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

Python Comments

Comments starts with a #, and Python will ignore them:

Python Comments
#This is a comment
print("Hello, World!") #This is a comment

Creating Variables
Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

Variables in Python
x = 5
y = "John"
print(x)
print(y)

Variables do not need to be declared with any particular type, and can even
change type after they have been set.

Data Type can be define using comments


x = 4 # x is of type int
x = "Sally" # x is now of type str

Changing Data Types – Casting


If you want to specify the data type of a variable, this can be done with casting.

Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Single or Double Quotes?
String variables can be declared either by using single or double quotes:

Example
x = "John"
# is the same as
x = 'John'

Case-Sensitive
Variable names are case-sensitive.

Global Variables
Variables that are created outside of a function (as in all of the examples above)
are known as global variables.

Create a variable outside of a function, and use it inside the function

x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

If you create a variable with the same name inside a function, this variable will
be local, and can only be used inside the function. The global variable with the
same name will remain as it was, global and with the original value.

#convert from float to int:


b = int(y)

Random Number
Python does not have a random() function to make a random number, but Python
has a built-in module called random that can be used to make random numbers:
Generating Random number
Import the random module, and display a random number between 1 and 9:

import random

print(random.randrange(1, 10))

Strings are Arrays


Like many other popular programming languages, strings in Python are arrays
of bytes representing unicode characters.

However, Python does not have a character data type, a single character is
simply a string with a length of 1.

Square brackets can be used to access elements of the string.

Example
Get the character at position 1 (remember that the first character has the
position 0):

a = "Hello, World!"
print(a[1])

String Length
To get the length of a string, use the len() function.

Example
The len() function returns the length of a string:

a = "Hello, World!"
print(len(a))

Slicing
You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part
of the string.
MID Function
Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

Note: The first character has index 0.

Pick one by one ALL Characters in a STRING


name = "MAK CS"
for x in range(len(name)):
print(name[x:x+1])

Slice From the Start


By leaving out the start index, the range will start at the first character:

Pick 5 characters from LEFT


Get the characters from the start to position 5 (not included):

b = "Hello, World!"
print(b[:5])

Pick Characters from Right


By leaving out the end index, the range will go to the end:

Example
Get the characters from position 2, and all the way to the end:

b = "Hello, World!"
print(b[2:])
Negative Indexing
Use negative indexes to start the slice from the end of the string:

Example
Get the characters:

From: "o" in "World!" (position -5)

To, but not included: "d" in "World!" (position -2):

b = "Hello, World!"
print(b[-5:-2])

Upper Case Conversion


The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())

Lower Case Conversion


The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.lower())
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y
Python Logical Operators
Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are x < 5 and x < 10


true

or Returns True if one of the statements x < 5 or x < 4


is true

not Reverse the result, returns False if the not(x < 5 and x
result is true < 10)

Creating an ARRAY
Create a List/Array:

thislist = ["apple", "banana", "cherry"]


print(thislist)

Example
Return the third, fourth, and fifth item:

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])

Note: The search will start at index 2 (included) and end at index 5 (not
included).

Note: The first item has index 0.


Append Items
To add an item to the end of the list, use the append() method:

Example
Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]


thislist.append("orange")
print(thislist)

While Loop – Printing all elements in an ARRAY


Print all items, using a while loop to go through all the index numbers

thislist = ["apple", "banana", "cherry"]


i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1

Python Conditions and If statements


Python supports the usual logical conditions from mathematics:

• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b

IF THEN ELSE
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Nested If
You can have if statements inside if statements, this is
called nested if statements.

Example
x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

Example
Using the start parameter:

for x in range(2, 6):


print(x)

The range() function defaults to increment the sequence by 1, however it is


possible to specify the increment value by adding a third parameter: range(2,
30, 3):

Example
Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):


print(x)

Creating a Function
In Python a function is defined using the def keyword:

Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:

Example
def my_function():
print("Hello from a function")

my_function()

Arguments
Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:

Example
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the
function:

Printing ALL Elements in an ARRAY using FUNCTION


def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]

my_function(fruits)

Code for Recursion


def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

Create a Class
To create a class, use the keyword class:

Creating a CLASS
Create a class named MyClass, with a property named x:

class MyClass:
x = 5

The __init__() Function


The examples above are classes and objects in their simplest form, and are not
really useful in real life applications.

To understand the meaning of classes we have to understand the built-in


__init__() function.

All classes have a function called __init__(), which is always executed when the
class is being initiated.

Use the __init__() function to assign values to object properties, or other


operations that are necessary to do when the object is being created:

Class with PUBLIC Constructor


Create a class named Person, use the __init__() function to assign values for
name and age:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

Note: The __init__() function is called automatically every time the class is
being used to create a new object.

Object Methods
Objects can also contain methods. Methods in objects are functions that belong
to the object.

Let us create a method in the Person class:

Example
Insert a function that prints a greeting, and execute it on the p1 object:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

Note: The self parameter is a reference to the current instance of the class,
and is used to access variables that belong to the class.

The pass Statement


class definitions cannot be empty, but if you for some reason have
a class definition with no content, put in the pass statement to avoid getting an
error.

Creating an EMPTY Class


class Person:
pass
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and
properties from another class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived
class.

Create a Parent Class


Any class can be a parent class, so the syntax is the same as creating any other
class:

Inheritance Example
Create a class named Person, with firstname and lastname properties, and
a printname method:

class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

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()
Declaring Attributes as PRIVATE
class Person:
def __init__(self, fname, lname):
self.__firstname = fname
self.__lastname = lname

Create a Child Class


To create a class that inherits the functionality from another class, send the
parent class as a parameter when creating the child class:

Person is parent and Student is Child


Create a class named Student, which will inherit the properties and methods
from the Person class:

class Student(Person):
pass

Note: Use the pass keyword when you do not want to add any other properties
or methods to the class.

Now the Student class has the same properties and methods as the Person
class.

Example
Use the Student class to create an object, and then execute
the printname method:

x = Student("Mike", "Olsen")
x.printname()

Add the __init__() Function


So far we have created a child class that inherits the properties and methods
from its parent.

We want to add the __init__() function to the child class (instead of


the pass keyword).

Note: The __init__() function is called automatically every time the class is
being used to create a new object.
Example
Add the __init__() function to the Student class:

class Student(Person):
def __init__(self, fname, lname):
#add properties etc.

When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.

Note: The child's __init__() function overrides the inheritance of the


parent's __init__() function.

To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:

Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)

Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.

These exceptions can be handled using the try statement:

Exception Code
The try block will generate an exception, because x is not defined:

try:
print(x)
except:
print("An exception occurred")

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:

Example
This statement will raise an error, because x is not defined:
print(x)

Example
Print one message if the try block raises a NameError and another for other
errors:

try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

File Handling
The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not
exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Example
f = open("demofile.txt", "r")
print(f.read())

Read Lines
You can return one line by using the readline() method:
Reading a Line from File
Read one line of the file:

f = open("demofile.txt", "r")
print(f.readline())

By calling readline() two times, you can read the two first lines:

Close Files
It is a good practice to always close the file when you are done with it.

Example
Close the file when you are finish with it:

f = open("demofile.txt", "r")
print(f.readline())
f.close()

Note: You should always close your files, in some cases, due to buffering,
changes made to a file may not show until you close the file.

Write to an Existing 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

Example
Open the file "demofile2.txt" and append content to the file:

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())
Example
Open the file "demofile3.txt" and overwrite the content:

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the appending:


f = open("demofile3.txt", "r")
print(f.read())

Create a New File


To create a new file in Python, use the open() method, with one of the following
parameters:

"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

Creating a Class with Constructor defined


class college:

def __init__(self, name, age):

self.__name = name

self.__age = age

def getname(self):

return self.__name

Declaring parent class


class section(college): #college is the parent

Random Files
import pickle

class record:
def __init__(self,name,age):

self.name = name

self.age = age

student = [record("MAK",12),record("zaki",34),record("mino",33)]

studentfile = open('cedarfile.dat', 'w+b')

pickle.dump(student[0],studentfile)

pickle.dump(student[1],studentfile)

pickle.dump(student[2],studentfile)

studentfile.close()

readfile = open('cedarfile.dat','r+b')

newstudent = []

for x in range(3):

newstudent.append(pickle.load(readfile))

print(newstudent[2].name)

import pickle

class record:

def __init__(self, name, age, grno):

self.name = name

self.age = age

self.grno = grno

student = [record("mak",23,10),record("zaki",34,11),record("shah",55,23)]

f = open('randomfile.dat', 'w+b')

address = hash(student[1].grno)
f.seek(address)

pickle.dump(student[1],f)

f.close()

newstudent = record("",0,0)

f = open('randomfile.dat', 'rb')

address = hash(11)

f.seek(address)

newstudent = pickle.load(f)

print(newstudent.name)

Create a Record Data Type


class Student:
def __init__(self,fn,a):
self.FirstName = fn
self.age = a

Declaring a 2D Array having 2 columns 11 rows, STRING Datatype


FileData = [[""] *2 for i in range(11)] #string

Displaying a 2D Array having 2 columns and 10 rows using procedure

def OutputHighScores ():

for x in range(0, 10):

Output = FileData[x][0] + " " + FileData[x][1]

print(Output)

Applying a validation Check on user name for 3 characters only.


username = input("enter 3 character Name ")

while len(username) != 3:

username = input("Re-enter it should be only 3 characters ")

Writing a 2D array into a Text File using a Procedure


def WriteTopTen():

newfile = open('newhighscore','w')

for x in range(10):

newfile.writelines(FileData[x][0] + "\n")

newfile.writelines(FileData[x][1] + "\n")

newfile.close()

WriteTopTen()

You might also like