KEMBAR78
Python Reviewer 1 | PDF | Parameter (Computer Programming) | Python (Programming Language)
0% found this document useful (0 votes)
13 views9 pages

Python Reviewer 1

Python

Uploaded by

lonymarasigan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views9 pages

Python Reviewer 1

Python

Uploaded by

lonymarasigan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Syntax The __init__() Function

Python Datetime: (called automatically every time the class is


being used to create a new object.)
1. x = datetime.datetime.now()
Create a class named Person, use the __init__()
print(x)
function to assign values for name and age:
2. import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B")) class Person:
Output: June
def __init__(self, name, age):
3. from datetime import date
birth = date(2005, 3, 14) self.name = name
today = date(2020, 3, 14)
delta = today - birth self.age = age
years = delta.days // 365
days = delta.days % 365
print("You are", years, "years and", p1 = Person("John", 36)
days, "days old.")
4. def add(x, y):
return (x+y) print(p1.name)
def subtract(x, y):
print(p1.age)
return (x-y)
print(calc.add(10, 2))

Output:
Create a class named MyClass, with property
John
named x:
36
syntax:

class MyClass:

x=5
OBJECT METHODS

Objects can also contain methods. Methods in


Create Object
objects are functions that belong to the object.
Now we can use the class named MyClass to
create objects:
Example
Example
Insert a function that prints a greeting, and
Create an object named p1, and print the value
execute it on the p1 object:
of x:

p1 = MyClass()

print(p1.x)
class Person: p1 = Person("John", 36)

def __init__(self, name, age): p1.myfunc()

self.name = name

self.age = age Modify Object Properties

You can modify properties on objects like this:

def myfunc(self):

print("Hello my name is " + self.name) class Person:

def __init__(self, name, age):

p1 = Person("John", 36) self.name = name

p1.myfunc() self.age = age

The self Parameter def myfunc(self):

The self parameter is a reference to the current print("Hello my name is " + self.name)
instance of the class, and is used to access
variables that belong to the class.
p1 = Person("John", 36)
It does not have to be named self, you can call it
whatever you like, but it has to be the first
parameter of any function in the class:
p1.age = 40

Use the words mysillyobject and abc instead of


self: print(p1.age)

class Person: Delete Object Properties

def __init__(mysillyobject, name, age): You can delete properties on objects by using
the del keyword:
mysillyobject.name = name

mysillyobject.age = age
class Person:

def __init__(self, name, age):


def myfunc(abc):
self.name = name
print("Hello my name is " + abc.name)
self.age = age
def myfunc(self): class definitions cannot be empty, but if you for
some reason have a class definition with no
print("Hello my name is " + self.name)
content, put in the

pass statement to avoid getting an error.


p1 = Person("John", 36)

class Person:
del p1.age
pass

print(p1.age)
Parent Class

Any class can be a parent class, so the syntax is


the same as creating any other class:

Delete Objects

You can delete objects by using the del keyword: Example

Create a class named Person, with firstname


and lastname properties, and a printname
class Person: method:
def __init__(self, name, age):

self.name = name class Person:


self.age = age def __init__(self, fname, lname):

self.firstname = fname
def myfunc(self): self.lastname = lname
print("Hello my name is " + self.name)

def printname(self):
p1 = Person("John", 36) print(self.firstname, self.lastname)

del p1 #Use the Person class to create an object, and


then execute the printname method:

print(p1)
x = Person("John", "Doe")

The pass Statement x.printname()


Child Class

To create a class that inherits the functionality x = Student("Mike", "Olsen")


from another class, send the parent class as a
x.printname()
parameter when

creating the child class:


child class that inherits the properties and
methods from its parent.
Example

Create a class named Student, which will inherit


We want to add the __init__() function to the
the properties and methods from the Person
child class (instead of the pass keyword).
class:

Note: The __init__() function is called


class Student(Person):
automatically every time the class is being used
pass to create a new object.

Note: Use the pass keyword when you do not Example


want to add any other properties or methods to
Add the __init__() function to the Student class:
the class.

class Student(Person):
Now the Student class has the same properties
and methods as the Person class. def __init__(self, fname, lname):

#add properties etc.


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

self.firstname = fname class Person:


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

self.firstname = fname
def printname(self): self.lastname = lname
print(self.firstname, self.lastname)

def printname(self):
class Student(Person): print(self.firstname, self.lastname)
pass
class Student(Person): print("Hello my name is " + self.name)

def __init__(self, fname, lname):


class Student(Person): # child class
Person.__init__(self, fname, lname) def __init__(self, name, age, course, year):
super().__init__(name, age, course)
self.year = year
x = Student("Mike", "Olsen")
person1 = Student("Kasandra", 20, "BSIT", 2026)
x.printname()
person1.introduce()

class & objects lesson /input user/

class Person: class Person:


def __init__(self, name, age, course): def __init__(self, name, age, course, year):
self.name = name self.name = name
self.age = age self.age = age
self.course = course self.course = course
self.year = year
def introduce(self): // sa loob ang objects
print("Hello my name is " + self.name) def introduce(self):
print("Hello, my name is" + self.name)
person1 = Person("Kasandra", 20, "BSIT") print("I am " + self.age + " years old")
print("Taking " + self.course + " course")
print("My name is " + person1.name) print("Year admitted: " + self.year)
print("Age: "+ str(person1.age))
print("Course: " + (person1.course)) name = input("Enter your name: ")
age = str(input("Enter your age: "))
person1.introduce() course = input("Enter your course: ")
year = input("What year were you admitted? ")
/ clean version /
person = Person(name, age, course, year)
class Person: # parent class person.introduce()
pass
def __init__(self, name, age, course):
self.name = name shopping = ["banana, apple, mango"]
self.age = age print("Please choose fruits from the list: ")
self.course = course print(shopping)
item_name = input("Enter a fruit: ")
def introduce(self): quantity = int(input("How many? "))
print("My name is " + self.name)
print("Age: " + str(self.age))
print("Course: " + (self.course)) class Shop: # parent class
print("Year: " + str(self.year)) def __init__(self, item_name, quantity):
self.item = item_name in Python is –
self.quantity = quantity

def calculate(self): file = open(“filename”, “mode”)


if self.item == "banana":
price = 5
total_banana = price * self.quantity # Open a file
print("Banana cost 5 pesos each")
print("Please pay " + str(total_banana) + " fo = open("foo.txt", "wb")
pesos") print ("Name of the file: ", fo.name)

elif self.item == "apple": print ("Closed or not: ", fo.closed)


price = 10
print ("Opening mode: ", fo.mode)
total_apple = price * self.quantity
print("Apple cost 10 pesos each") fo.close()
print("Please pay " + str(total_apple) + "
It will produce the following output –
pesos")
Name of the file: foo.txt
elif self.item == "mango":
Closed or not: False
price = 15
total_mango = price * self.quantity Opening mode: wb
print("Mango cost 15 pesos each")
print("Please pay " + str(total_mango) + "
pesos") Closing File in Python

else:
print("Item is not available") file = open("example.txt", "w")

file.write("This is an example.")
ItemOne = Shop(item_name, quantity)
file.close()
ItemOne.calculate()
print ("File closed successfully!!")

FILE
Using "with" Statement for Automatic File
Opening a File in Python
Closing

Example
To perform any file operation, the first step is to
In this example, the file is automatically closed
open the file. Python's built-in open() function is
at the end of the with block, so there is no need
used
to call close() method explicitly –
to open files in various modes, such as reading,
with open("example.txt", "w") as file:
writing, and appending. The syntax for opening
a file
file.write("This is an example using the with print(line, end='')
statement.")

print ("File closed successfully!!")


We get the output as follows –
Following is the output of the above code −
Hello!!!
File closed successfully!!
Welcome to TutorialsPoint!!!

Reading a File in Python


Writing to a File in Python
• read() − Reads the entire file.
Writing to a file in Python involves opening the
• readline() − Reads one line at a time. file in a mode that allows writing, and then
using various methods to add content to the
• readlines − Reads all lines into a list.
file.

To write data to a file, use the write() or


Example: Using read() method writelines() methods. When opening a file in
write mode ('w'), the file's existing content is
In the following example, we are using the erased.
read() method to read the whole file into a
single string – Example: Using the write() method

with open("example.txt", "r") as file: In this example, we are using the write()
method to write the string passed to it to the
content = file.read() file. If the file is opened in 'w' mode, it will
print(content) overwrite any existing content. If the file is
opened in 'a' mode, it will append the string to
the end of the file −
Following is the output obtained –

Hello!!! with open("foo.txt", "w") as file:


Welcome to TutorialsPoint!!! file.write("Hello, World!")

print ("Content added Successfully!!")


Example: Using readlines() method

Now, we are using the readlines() method to Output of the above code is as follows –
read the entire file and splits it into a list where
each element is a line – Content added Successfully!!

with open("example.txt", "r") as file:

lines = file.readlines() Example: Using the writelines() method In here,


we are using the writelines() method to take a
for line in lines: list of strings and writes each string to the file.
It is useful for writing multiple lines at once –  FileNotFoundError: File doesn’t exist

 TypeError: Incompatible data type

lines = ["First line\n", "Second line\n", "Third  IndexError: Index is out of range
line\n"]

with open("example.txt", "w") as file:


Topic 2: Python Functions
file.writelines(lines)
 Definition: A reusable block of code
print ("Content added Successfully!!") that performs a specific task.

 Syntax:

The result obtained is as follows – python

Content added Successfully!! Copy code

Python Long Quiz Reviewer def function_name(parameters):

Topic 1: Exception Handling in Python # code block

 Definition: A way to manage errors that return value


happen while a program is running.
Types of Arguments:
 Keywords: try, except, else, finally, raise
 Required arguments
Example Structure:
 Keyword arguments
python
 Default arguments
Copy code
 Variable-length arguments (*args,
try: **kwargs)

risky_code() Return Statement:

except ExceptionType:  Ends the function and can return a


value.
handle_exception()
Built-in Functions:
else:
 Examples: print(), len(), type(), int()
no_exception_code()
User-defined Functions:
finally:
 Functions that the programmer creates
cleanup_code()
for custom tasks.
Common Exceptions:

 ZeroDivisionError: Dividing by zero


Topic 3: Python Tkinter (GUI Programming)
 ValueError: Invalid input value
Overview:
 Tkinter is Python’s standard GUI library.

Widget Examples:

 Button, Label, Entry, Text, Canvas,


Frame, Checkbutton, Radiobutton

Steps to Create a GUI:

1. Import tkinter

2. Create the main window

3. Add widgets (controls)

4. Start the GUI with mainloop()

Geometry Managers:

 pack(): Packs widgets


vertically/horizontally

 grid(): Places widgets in a grid layout

 place(): Places widgets using


coordinates

Styling and Attributes:

 Size: width, height

 Colors: bg (background), fg (foreground)

 Fonts: ("Arial", 12, "bold")

 Borders: RAISED, SUNKEN, GROOVE,


etc.

Dialog Boxes and Inputs:

 simpledialog.askstring() – text input

 filedialog.askopenfilename() – file
chooser

 messagebox.showinfo() – show
messages

ttk Module:

 A modern set of themed widgets like


Combobox, Notebook, Progressbar, etc.

You might also like