Python File by MAK
Python File by MAK
Python Comments
#This is a comment
print("Hello, World!") #This is a comment
Creating Variables
Python has no command for declaring a variable.
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.
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.
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.
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))
However, Python does not have a character data type, a single character is
simply a string with a length of 1.
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])
b = "Hello, World!"
print(b[:5])
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:
b = "Hello, World!"
print(b[-5:-2])
a = "Hello, World!"
print(a.upper())
a = "Hello, World!"
print(a.lower())
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations:
+ 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:
not Reverse the result, returns False if the not(x < 5 and x
result is true < 10)
Creating an ARRAY
Create a List/Array:
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).
Example
Using the append() method to append an item:
• 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:
Example
Increment the sequence with 3 (default is 1):
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")
E.g. if you send a List as an argument, it will still be a List when it reaches the
function:
my_function(fruits)
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
All classes have a function called __init__(), which is always executed when the
class is being initiated.
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.
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.
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.
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
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()
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.
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.
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.
"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
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.
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()
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
"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
self.__name = name
self.__age = age
def getname(self):
return self.__name
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)]
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:
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)
print(Output)
while len(username) != 3:
newfile = open('newhighscore','w')
for x in range(10):
newfile.writelines(FileData[x][0] + "\n")
newfile.writelines(FileData[x][1] + "\n")
newfile.close()
WriteTopTen()