Python 3 Functions and Syntax Guide
Python 3 Functions and Syntax Guide
Hello World
[Link] Page 1 of 6
12/28/20, 12:55 AM
Comments
A comment is a piece of text within a program that is
not executed. It can be used to provide additional # Comment on a single line
information to aid in understanding the code.
The # character is used to start a comment and it user = "JDoe" # Comment after code
continues until the end of the line.
Arithmetic Operations
Python supports di!erent types of arithmetic
operations that can be performed on literal numbers, # Arithmetic operations
variables, or some combination. The primary
arithmetic operators are: result = 10 + 30
result = 40 - 10
●
+ for addition
result = 50 * 5
●
- for subtraction result = 16 / 4
result = 25 % 2
●
* for multiplication
result = 5 ** 3
●
/ for division
●
% for modulus (returns the remainder)
●
** for exponentiation
[Link] Page 2 of 6
12/28/20, 12:55 AM
Plus-Equals Operator +=
The plus-equals operator += provides a convenient
way to add a value to an existing variable and assign # Plus-Equal Operator
the new value back to the same variable. In the case
where the variable and the value are strings, this counter = 0
operator performs string concatenation instead of counter += 10
addition.
The operation is performed in-place, meaning that any # This is equivalent to
other variable which points to the variable being
updated will also be updated.
counter = 0
counter = counter + 10
Variables
A variable is used to store data that will be used by the
program. This data can be a number, a string, a # These are all valid variable names
Boolean, a list or some other data type. Every variable and assignment
has a name which can consist of letters, numbers, and
the underscore character _ . user_name = "@sonnynomnom"
The equal sign = is used to assign a value to a user_id = 100
variable. After the initial assignment is made, the value verified = False
of a variable can be updated to new values as needed.
points = 100
points = 120
[Link] Page 3 of 6
12/28/20, 12:55 AM
Modulo Operator %
A modulo calculation returns the remainder of a
division between the "rst and second number. For # Modulo operations
example:
zero = 8 % 4
●
The result of the expression 4 % 2 would
result in the value 0, because 4 is evenly divisible
nonzero = 12 % 5
by 2 leaving no remainder.
●
The result of the expression 7 % 3 would
return 1, because 7 is not evenly divisible by 3,
leaving a remainder of 1.
Integers
An integer is a number that can be written without a
fractional part (no decimal). An integer can be a # Example integer numbers
positive number, a negative number or the number 0
so long as there is no decimal portion. chairs = 4
The number 0 represents an integer value but the tables = 1
same number written as 0.0 would represent a broken_chairs = -2
#oating point number. sofas = 0
# Non-integer numbers
lights = 2.5
left_overs = 0.0
String Concatenation
Python supports the joining (concatenation) of strings
together using the + operator. The + operator is # String concatenation
also used for mathematical addition operations. If the
parameters passed to the + operator are strings, first = "Hello "
then concatenation will be performed. If the second = "World"
parameter passed to + have di!erent types, then
Python will report an error condition. Multiple result = first + second
variables or literal strings can be joined together using
the + operator. long_result = first + second + "!"
[Link] Page 4 of 6
12/28/20, 12:55 AM
Errors
The Python interpreter will report errors present in
your code. For most error cases, the interpreter will if False ISNOTEQUAL True:
display the line of code where the error was detected ^
and place a caret character ^ under the portion of SyntaxError: invalid syntax
the code where the error was detected.
ZeroDivisionError
A ZeroDivisionError is reported by the Python
interpreter when it detects a division operation is numerator = 100
being performed and the denominator (bottom denominator = 0
number) is 0. In mathematics, dividing a number by bad_results = numerator / denominator
zero has no de"ned value, so Python treats this as an
error condition and will report a ZeroDivisionError and
ZeroDivisionError: division by zero
display the line of code where the division occurred.
This can also happen if a variable is used as the
denominator and its value has been set to or changed
to 0.
Strings
A string is a sequence of characters (letters, numbers,
whitespace or punctuation) enclosed by quotation user = "User Full Name"
marks. It can be enclosed using either the double game = 'Monopoly'
quotation mark " or the single quotation mark ' .
If a string has to be broken into multiple lines, the longer = "This string is broken up \
backslash character \ can be used to indicate that over multiple lines"
the string continues on the next line.
SyntaxError
A SyntaxError is reported by the Python interpreter
when some portion of the code is incorrect. This can age = 7 + 5 = 4
include misspelled keywords, missing or too many
brackets or parenthesis, incorrect operators, missing File "<stdin>", line 1
or too many quotation marks, or other conditions.
SyntaxError: can't assign to operator
[Link] Page 5 of 6
12/28/20, 12:55 AM
NameError
A NameError is reported by the Python interpreter
when it detects a variable that is unknown. This can misspelled_variable_name
occur when a variable is used before it has been
assigned a value or if a variable name is spelled NameError: name
di!erently than the point at which it was de"ned. The
'misspelled_variable_name' is not
Python interpreter will display the line of code where
defined
the NameError was detected and indicate which name
it found that was not de"ned.
print() Function
The print() function is used to output text,
numbers, or other printable information to the print("Hello World!")
console.
It takes one or more arguments and will output each print(100)
of the arguments to the console separated by a space.
If no arguments are provided, the print() pi = 3.14159
function will output a blank line. print(pi)
[Link] Page 6 of 6
12/28/20, 12:55 AM
Functions
[Link] Page 1 of 6
12/28/20, 12:55 AM
Function Parameters
Sometimes functions require input to provide data for
their code. This input is de!ned using parameters. def write_a_book(character, setting,
Parameters are variables that are de!ned in the special_skill):
function de!nition. They are assigned the values which print(character + " is in " +
were passed as arguments when the function was setting + " practicing her "
called, elsewhere in the code.
+
For example, the function de!nition de!nes
special_skill)
parameters for a character, a setting, and a skill, which
are used as inputs to write the !rst sentence of a
book.
Multiple Parameters
Python functions can have multiple parameters. Just
as you wouldn’t go to school without both a backpack def ready_for_school(backpack,
and a pencil case, functions may also need more than pencil_case):
one input to carry out their operations. if (backpack == 'full' and
To de!ne a function with multiple parameters, pencil_case == 'full'):
parameter names are placed one after another,
print ("I'm ready for school!")
separated by commas, within the parentheses of the
function de!nition.
Functions
Some tasks need to be performed multiple times
within a program. Rather than rewrite the same code # Define a function my_function()
in multiple places, a function may be de!ned using the with parameter x
def keyword. Function de!nitions may include
parameters, providing data input to the function. def my_function(x):
Functions may return a value using the return return x + 1
keyword followed by the value to return.
# Invoke the function
print(my_function(2)) # Output:
3
print(my_function(3 + 5)) # Output:
9
[Link] Page 2 of 6
12/28/20, 12:55 AM
Function Indentation
Python uses indentation to identify blocks of code.
Code within the same block should be indented at the # Indentation is used to identify
same level. A Python function is one type of code code blocks
block. All code under a function declaration should be
indented to identify it as part of the function. There def testfunction(number):
can be additional indentation within a function to
# This code is part of testfunction
handle other statements such as for and if so print("Inside the testfunction")
long as the lines are not indented less than the !rst
sum = 0
line of the function code.
for x in range(number):
# More indentation because 'for'
has a code block
# but still part of he function
sum += x
return sum
print("This is not part of
testfunction")
Calling Functions
Python uses simple syntax to use, invoke, or call a
preexisting function. A function can be called by doHomework()
writing the name of it, followed by parentheses.
For example, the code provided would call the
doHomework() method.
Function Arguments
Parameters in python are variables — placeholders for
the actual values the function needs. When the def sales(grocery_store,
function is called, these values are passed in as item_on_sale, cost):
arguments. print(grocery_store + " is selling
For example, the arguments passed into the function " + item_on_sale + " for " + cost)
.sales() are the “The Farmer’s Market”,
“toothpaste”, and “$1” which correspond to the
sales("The Farmer’s Market",
parameters grocery_store , "toothpaste", "$1")
item_on_sale , and cost .
[Link] Page 3 of 6
12/28/20, 12:55 AM
three_squared, four_squared,
five_squared = square_point(3, 4, 5)
[Link] Page 4 of 6
12/28/20, 12:55 AM
year_to_check = 2018
returned_value
= check_leap_year(year_to_check)
print(returned_value) # 2018 is not
a leap year.
[Link] Page 5 of 6
12/28/20, 12:55 AM
Global Variables
A variable that is de!ned outside of a function is called
a global variable. It can be accessed inside the body of a = "Hello"
a function.
In the example, the variable a is a global variable def prints_a():
because it is de!ned outside of the function print(a)
prints_a . It is therefore accessible to
prints_a , which will print the value of a . # will print "Hello"
prints_a()
[Link] Page 6 of 6
12/28/20, 12:55 AM
Control Flow
[Link] Page 1 of 6
12/28/20, 12:55 AM
elif Statement
The Python elif statement allows for continued
# elif Statement
checks to be performed after an initial if
statement. An elif statement di!ers from the
pet_type = "fish"
else statement because another expression is
provided to be checked, just as with the initial if
if pet_type == "dog":
statement.
print("You have a dog.")
If the expression is True , the indented code
elif pet_type == "cat":
following the elif is executed. If the expression print("You have a cat.")
evaluates to False , the code can continue to an elif pet_type == "fish":
optional else statement. Multiple elif # this is performed
statements can be used following an initial if to print("You have a fish")
perform a series of checks. Once an elif else:
expression evaluates to True , no further elif print("Not sure!")
statements are executed.
[Link] Page 2 of 6
12/28/20, 12:55 AM
or Operator
The Python or operator combines two Boolean
True or True # Evaluates to True
expressions and evaluates to True if at least one of
True or False # Evaluates to True
the expressions returns True . Otherwise, if both
False or False # Evaluates to
expressions are False , then the entire expression
False
evaluates to False .
1 < 2 or 3 < 1 # Evaluates to True
3 < 1 or 1 > 6 # Evaluates to
False
1 == 1 or 1 < 2 # Evaluates to True
Equal Operator ==
The equal operator, == , is used to compare two
values, variables or expressions to determine if they # Equal operator
are the same.
If the values being compared are the same, the if 'Yes' == 'Yes':
operator returns True , otherwise it returns # evaluates to True
False . print('They are equal')
The operator takes the data type into account when
making the comparison, so a string value of "2" is if (2 > 1) == (5 < 10):
not considered the same as a numeric value of 2 . # evaluates to True
print('Both expressions give the
same result')
c = '2'
d = 2
if c == d:
print('They are equal')
else:
print('They are not equal')
[Link] Page 3 of 6
12/28/20, 12:55 AM
Comparison Operators
In Python, relational operators compare two values or
expressions. The most common ones are: a = 2
b = 3
●
< less than a < b # evaluates to True
●
> greater than a > b # evaluates to False
a >= b # evaluates to False
●
<= less than or equal to a <= b # evaluates to True
●
>= greater than or equal too a <= a # evaluates to True
[Link] Page 4 of 6
12/28/20, 12:55 AM
if Statement
The Python if statement is used to determine the
execution of code based on the evaluation of a # if Statement
Boolean expression.
test_value = 100
●
If the if statement expression evaluates to
True , then the indented code following the if test_value > 1:
statement is executed. # Expression evaluates to True
print("This code is executed!")
●
If the expression evaluates to False then the
indented code following the if statement is
if test_value > 1000:
skipped and the program executes the next line
# Expression evaluates to False
of code which is indented at the same level as
print("This code is NOT executed!")
the if statement.
else Statement
The Python else statement provides alternate
# else Statement
code to execute if the expression in an if
statement evaluates to False .
test_value = 50
The indented code for the if statement is executed
if the expression evaluates to True . The indented
if test_value < 1:
code immediately following the else is executed print("Value is < 1")
only if the expression evaluates to False . To mark else:
the end of the else block, the code must be print("Value is >= 1")
unindented to the same level as the starting if line.
test_string = "VALID"
if test_string == "NOT_VALID":
print("String equals NOT_VALID")
else:
print("String equals something
else!")
[Link] Page 5 of 6
12/28/20, 12:55 AM
and Operator
The Python and operator performs a Boolean
comparison between two Boolean values, variables, or True and True # Evaluates to True
expressions. If both sides of the operator evaluate to True and False # Evaluates to
True then the and operator returns True . If False
either side (or both sides) evaluates to False , then
False and False # Evaluates to
False
the and operator returns False . A non-Boolean
value (or variable that stores a value) will always
1 == 1 and 1 < 2 # Evaluates to True
1 < 2 and 3 < 1 # Evaluates to
evaluate to True when used with the and
operator.
False
"Yes" and 100 # Evaluates to True
Boolean Values
Booleans are a data type in Python, much like integers,
"oats, and strings. However, booleans only have two is_true = True
values: is_false = False
●
True print(type(is_true))
●
False # will output: <class 'bool'>
not Operator
The Python Boolean not operator is used in a
Boolean expression in order to evaluate the expression not True # Evaluates to False
to its inverse value. If the original expression was not False # Evaluates to True
True , including the not operator would make 1 > 2 # Evaluates to False
the expression False , and vice versa.
not 1 > 2 # Evaluates to True
1 == 1 # Evaluates to True
not 1 == 1 # Evaluates to False
[Link] Page 6 of 6
12/28/20, 12:55 AM
Lists
[Link] Page 1 of 5
12/28/20, 12:55 AM
Lists
In Python, lists are ordered collections of items that
allow for easy use of a set of data. primes = [2, 3, 5, 7, 11]
List values are placed in between square brackets [ print(primes)
] , separated by commas. It is good practice to put a
space between the comma and the next value. The empty_list = []
values in a list do not need to be unique (the same
value can be repeated).
Empty lists do not contain any values within the square
brackets.
[Link] Page 2 of 5
12/28/20, 12:55 AM
[Link] Page 3 of 5
12/28/20, 12:55 AM
Zero-Indexing
In Python, list index begins at zero and ends at the
length of the list minus one. For example, in this list, names = ['Roger', 'Rafael', 'Andy',
'Andy' is found at index 2 . 'Novak']
List Indices
Python list elements are ordered by index, a number
referring to their placement in the list. List indices berries = ["blueberry", "cranberry",
start at 0 and increment by one. "raspberry"]
To access a list element by index, square bracket
notation is used: list[index] . berries[0] # "blueberry"
berries[2] # "raspberry"
[Link] Page 4 of 5
12/28/20, 12:55 AM
List Slicing
A slice, or sub-list of Python list elements can be
selected from a list using a colon-separated starting tools = ['pen', 'hammer', 'lever']
and ending point. tools_slice = tools[1:3] # ['hammer',
The syntax pattern is 'lever']
myList[START_NUMBER:END_NUMBER] . tools_slice[0] = 'nail'
The slice will include the START_NUMBER index,
and everything until but excluding the # Original list is unaltered:
END_NUMBER item. print(tools) # ['pen', 'hammer',
When slicing a list, a new list is returned, so if the slice 'lever']
is saved and then altered, the original list remains the
same.
sorted() Function
The Python sorted() function accepts a list as
an argument, and will return a new, sorted list unsortedList = [4, 2, 1, 3]
containing the same elements as the original. sortedList = sorted(unsortedList)
Numerical lists will be sorted in ascending order, and print(sortedList)
lists of Strings will be sorted into alphabetical order. It # Output: [1, 2, 3, 4]
does not modify the original, unsorted list.
[Link] Page 5 of 5
12/28/20, 12:55 AM
Loops
[Link] Page 1 of 5
12/28/20, 12:55 AM
break Keyword
In a loop, the break keyword escapes the loop,
numbers = [0, 254, 2, -1, 3]
regardless of the iteration number. Once break
executes, the program will continue to execute after
the loop. for num in numbers:
In this example, the output would be: if (num < 0):
print("Negative number
●
0 detected!")
break
●
254
print(num)
●
2
# 0
●
Negative number detected!
# 254
# 2
# Negative number detected!
[Link] Page 2 of 5
12/28/20, 12:55 AM
[Link] Page 3 of 5
12/28/20, 12:55 AM
In!nite Loop
An in!nite loop is a loop that never terminates. In!nite
loops result when the conditions of the loop prevent it
from terminating. This could be due to a typo in the
conditional statement within the loop or incorrect
logic. To interrupt a Python program that is running
forever, press the Ctrl and C keys together on
your keyboard.
[Link] Page 4 of 5
12/28/20, 12:55 AM
[Link] Page 5 of 5
12/28/20, 12:56 AM
Strings
[Link] Page 1 of 7
12/28/20, 12:56 AM
Strings
In computer science, sequences of characters are
referred to as strings. Strings can be any length and
can include any character such as letters, numbers,
symbols, and whitespace (spaces, tabs, new lines).
Escaping Characters
Backslashes ( \ ) are used to escape characters in a
Python string. txt = "She said \"Never let go\"."
For instance, to print a string with quotation marks, the print(txt) # She said "Never let go".
given code snippet can be used.
The in Syntax
The in syntax is used to determine if a letter or a
game = "Popular Nintendo Game: Mario
substring exists in a string. It returns True if a
Kart"
match is found, otherwise False is returned.
[Link] Page 2 of 7
12/28/20, 12:56 AM
Iterate String
To iterate through a string in Python, “for…in” notation
is used. str = "hello"
for c in str:
print(c)
# h
# e
# l
# l
# o
String Concatenation
To combine the content of two strings into a single
string, Python provides the + operator. This process x = 'One fish, '
of joining strings is called concatenation. y = 'two fish.'
z = x + y
print(z)
# Output: One fish, two fish.
[Link] Page 3 of 7
12/28/20, 12:56 AM
Immutable strings
Strings are immutable in Python. This means that once
a string has been de!ned, it can’t be changed.
There are no mutating methods for strings. This is
unlike data types like lists, which can be modi!ed once
they are created.
IndexError
When indexing into a string in Python, if you try to
access an index that doesn’t exist, an fruit = "Berry"
IndexError is generated. For example, the indx = fruit[6]
following code would create an IndexError :
print([Link]())
# Prints: welcome to chili's
[Link] Page 4 of 7
12/28/20, 12:56 AM
[Link] Page 5 of 7
12/28/20, 12:56 AM
String replace
The .replace() method is used to replace the
occurence of the !rst argument with the second fruit = "Strawberry"
argument within the string. print([Link]('r', 'R'))
The !rst argument is the old substring to be replaced,
and the second argument is the new substring that will # StRawbeRRy
replace every occurence of the !rst one within the
string.
print([Link]())
# Prints: T-REX
[Link] Page 6 of 7
12/28/20, 12:56 AM
[Link] Page 7 of 7
12/28/20, 12:56 AM
Modules
[Link] Page 1 of 4
12/28/20, 12:56 AM
time_13_48min_5sec
= [Link](hour=13, minute=48,
second=5)
time_13_48min_5sec
= [Link](13, 48, 5)
print(time_13_48min_5sec) #13:48:05
timestamp=
[Link](year=2019, month=2,
day=16, hour=13, minute=48, second=5)
timestamp = [Link](2019,
2, 16, 13, 48, 5)
print (timestamp) #2019-01-02
13:48:05
# Aliasing calendar as c
import calendar as c
print(c.month_name[1])
[Link] Page 2 of 4
12/28/20, 12:56 AM
# Third way
from module import *
function()
[Link] Page 3 of 4
12/28/20, 12:56 AM
Module importing
In Python, you can import and use the content of
another !le using import filename , provided # file1 content
that it is in the same folder as the current !le you are # def f1_function():
writing. # return "Hello World"
# file2
import file1
[Link] Page 4 of 4
12/28/20, 12:56 AM
Dictionaries
[Link] Page 1 of 4
12/28/20, 12:56 AM
[Link] Page 2 of 4
12/28/20, 12:56 AM
Python dictionaries
A python dictionary is an unordered collection of
items. It contains data as a set of key: value pairs. my_dictionary = {1: "L.A. Lakers", 2:
"Houston Rockets"}
ex_dict.items()
# [("a","anteater"),
("b","bumblebee"),("c","cheetah")]
[Link] Page 3 of 4
12/28/20, 12:56 AM
# with default
{"name": "Victor"}.get("nickname",
"nickname is not a key")
# returns "nickname is not a key"
[Link] Page 4 of 4
12/28/20, 12:57 AM
Files
[Link] Page 1 of 7
12/28/20, 12:57 AM
with open('[Link]') as
file_object:
print(file_object)
<_io.TextIOWrapper
name='[Link]' mode='r'
encoding='UTF-8'>
[Link] Page 2 of 7
12/28/20, 12:57 AM
with open('[Link]') as
story_object:
print(story_object.readline(
))
import json
with open('[Link]') as json_file:
python_dict = [Link](json_file)
print(python_dict.get('userId'))
# Prints 10
[Link] Page 3 of 7
12/28/20, 12:57 AM
with open('[Link]','w') as
diary:
[Link]('Special events
for today')
[Link] Page 4 of 7
12/28/20, 12:57 AM
with open('[Link]') as
file_object:
file_data
= file_object.readlines()
print(file_data)
outputs:
1. Learn Python.
2. Work hard.
3. Graduate.
[Link] Page 5 of 7
12/28/20, 12:57 AM
Class [Link]
In Python, the csv module implements classes to
read and write tabular data in CSV format. It has a # An example of [Link]
class DictWriter which operates like a regular import csv
writer but maps a dictionary onto output rows. The
keys of the dictionary are column names while values with open('[Link]', 'w') as
are actual data. csvfile:
The [Link] constructor takes two fieldnames = ['name', 'type']
arguments. The !rst is the open !le handler that the writer = [Link](csvfile,
CSV is being written to. The second named parameter, fieldnames=fieldnames)
fieldnames , is a list of !eld names that the CSV [Link]()
is going to handle. [Link]({'name':
'Codecademy', 'type': 'Learning'})
[Link]({'name': 'Google',
'type': 'Search'})
"""
After running the above code,
[Link] will contain the
following information:
name,type
Codecademy,Learning
Google,Search
"""
[Link] Page 6 of 7
12/28/20, 12:57 AM
with open('[Link]') as
text_file:
text_data = text_file.read()
print(text_data)
Mystery solved.
Congratulations!
[Link] Page 7 of 7
12/28/20, 12:57 AM
Classes
[Link] Page 1 of 9
12/28/20, 12:57 AM
def __repr__(self):
return [Link]
john = Employee('John')
print(john) # John
# Class Instantiation
ferrari = Car()
[Link] Page 2 of 9
12/28/20, 12:57 AM
print(x.class_variable) #I am a Class
Variable!
print(y.class_variable) #I am a Class
Variable!
dog = Animal('Woof')
print([Link]) # Output: Woof
[Link] Page 3 of 9
12/28/20, 12:57 AM
a = 1.1
print(type(a)) # <class 'float'>
a = 'b'
print(type(a)) # <class 'str'>
a = None
print(type(a)) # <class 'NoneType'>
Python class
In Python, a class is a template for a data type. A class
can be de!ned using the class keyword. # Defining a class
class Animal:
def __init__(self, name,
number_of_legs):
[Link] = name
self.number_of_legs
= number_of_legs
[Link] Page 4 of 9
12/28/20, 12:57 AM
print(dir())
# ['Employee', '__builtins__',
'__doc__', '__file__', '__name__',
'__package__', 'new_employee']
print(dir(Employee))
# ['__doc__', '__init__',
'__module__', 'print_name']
__main__ in Python
In Python, __main__ is an identi!er used to
reference the current !le context. When a module is
read from standard input, a script, or from an
interactive prompt, its __name__ is set equal to
__main__ .
Suppose we create an instance of a class called
CoolClass . Printing the type() of the
instance will result in:
<class '__main__.CoolClass'>
[Link] Page 5 of 9
12/28/20, 12:57 AM
class ChildClass(ParentClass):
def print_test(self):
print("Child Method")
# Calls the parent's version of
print_test()
super().print_test()
child_instance = ChildClass()
child_instance.print_test()
# Output:
# Child Method
# Parent Method
[Link] Page 6 of 9
12/28/20, 12:57 AM
Polymorphism in Python
When two Python classes o"er the same set of
methods with di"erent implementations, the classes class ParentClass:
are polymorphic and are said to have the same def print_self(self):
interface. An interface in this sense might involve a print('A')
common inherited class and a set of overridden
methods. This allows using the two objects in the same
class ChildClass(ParentClass):
way regardless of their individual types.
def print_self(self):
When a child class overrides a method of a parent
print('B')
class, then the type of the object determines the
version of the method to be called. If the object is an
instance of the child class, then the child class version obj_A = ParentClass()
of the overridden method will be called. On the other obj_B = ChildClass()
hand, if the object is an instance of the parent class,
then the parent class version of the method is called. obj_A.print_self() # A
obj_B.print_self() # B
[Link] Page 7 of 9
12/28/20, 12:57 AM
print(issubclass(Member, Family)) #
True
[Link] Page 8 of 9
12/28/20, 12:57 AM
Python Inheritance
Subclassing in Python, also known as “inheritance”,
allows classes to share the same attributes and class Animal:
methods from a parent or superclass. Inheritance in def __init__(self, name, legs):
Python can be accomplished by putting the superclass [Link] = name
name between parentheses after the subclass or child
[Link] = legs
class name.
In the example code block, the Dog class subclasses
class Dog(Animal):
the Animal class, inheriting all of its attributes. def sound(self):
print("Woof!")
Yoki = Dog("Yoki", 4)
print([Link]) # YOKI
print([Link]) # 4
[Link]() # Woof!
+ Operator
In Python, the + operation can be de!ned for a
user-de!ned class by giving that class an class A:
.__add()__ method. def __init__(self, a):
self.a = a
def __add__(self, other):
return self.a + other.a
obj1 = A(5)
obj2 = A(10)
print(obj1 + obj2) # 15
[Link] Page 9 of 9
12/28/20, 12:57 AM
Function Arguments
[Link] Page 1 of 4
12/28/20, 12:57 AM
greet("Ankit")
greet("Ankit", "How do you do?")
"""
this code will print the following
for both the calls -
`Hello Ankit, How do you do?`
"""
[Link] Page 2 of 4
12/28/20, 12:57 AM
print(my_function())
#Output
None
[Link] Page 3 of 4
12/28/20, 12:57 AM
func_with_args('First', 'Second')
# Prints:
# First Second
func_with_args(arg2='Second',
arg1='First')
# Prints
# First Second
[Link] Page 4 of 4
The isinstance() function in Python checks if an object is an instance or subclass of a class or a tuple of classes, returning True if it is. It examines the type hierarchy and helps in determining object types safely without triggering errors due to incorrect type assumptions. For example, using isinstance(cat, Animal) would return True if 'cat' is an instance of the 'Animal' class, ensuring proper type differentiation and supporting polymorphic behaviors in code .
In Python, the 'self' parameter is essential in class methods as it refers to the instance of the class itself. This allows access to the instance's attributes and other methods from within the class. Unlike conventional function parameters that are explicitly passed, 'self' is automatically handled during method calls on objects. This mechanism distinguishes instance method calls from ordinary function calls, providing encapsulation and allowing instances to maintain unique states .
The try-except block in Python facilitates error handling by allowing code that might cause exceptions to be attempted in the 'try' section while providing handling strategies in the 'except' block. When an error occurs during the execution of the 'try' block, the remaining lines are skipped, and execution moves to the 'except' block. This construct is essential for maintaining program stability, ensuring that Python handles errors gracefully without crashing, and allows for custom error-handling logic to be applied .
Polymorphism in Python allows different classes to be used interchangeably, as they share the same interface despite different implementations. This is enabled by inheritance, where classes share methods or attributes from a common parent class. For example, if two subclasses, Dog and Cat, inherit from a class Animal, both can implement a method sound(). Despite their different outputs for the same method, they facilitate the use of common code to handle instances that share the Animal interface, allowing method calls to be uniform across subclasses .
Dunder methods, short for “Double Under” methods, are special methods in Python surrounded by double underscores, used to implement certain functionalities, such as initialization with __init__, or operator overloading with __add__. They allow custom objects to exhibit behavior similar to Python's built-in types. By overriding dunder methods in a subclass, you can define specific object behaviors. For instance, the __add__ method could be overridden in a numerical subclass to change how addition works for its objects, allowing custom addition logic .
The 'or' operator in Python returns True if at least one of its operands evaluates to True. In the expression 'True or False', the operator evaluates to True because the first operand is True. Similarly, '1 < 2 or 3 < 1' evaluates to True since the first condition is True. If both operands are False, like in '3 < 1 or 1 > 6', the result is False. This operator is useful for checks where any of several conditions can trigger a True outcome .
Class variables in Python are defined outside of all methods and share the same value across all instances of the class. In contrast, instance variables are defined within methods, typically __init__, and are unique to each instance. For example, a class 'my_class' might have a class variable 'class_variable', set to "I am a Class Variable!", where every instance of 'my_class' would see the same value. However, if 'my_class' includes an instance variable 'voice', unique values can be assigned per instance, like 'Meow' for a 'cat' object .
Method overriding in Python occurs when a subclass defines a method with the same name as a method in its superclass, redefining it to suit the subclass’s needs. When the method is called on an instance of the subclass, the subclass's version executes, changing the behavior from the superclass's version. For instance, in a subclass 'Car', a method 'sound()' might override the method from superclass 'Vehicle', customizing the honk sound for cars, while a similar method in 'Truck' overrides with a different sound .
Python's 'elif' statement allows additional condition checks following an initial 'if' statement, acting as an intermediate check before an optional 'else'. Unlike 'else', 'elif' is accompanied by a condition, which is evaluated only if all previous conditions have been False. It enables sequential execution of conditional tests, offering multiple avenues for the code flow to diverge based on more than two potential outcomes. For example, different actions can be taken for distinct categories, like pet types, where each 'elif' addresses a different type .
CSV files in Python can be handled using the csv module, providing mechanisms to read from and write to CSV files. The DictWriter class is particularly useful for writing dictionaries to CSV, requiring a file object and a list of fieldnames. First, a header is written with writer.writeheader(), followed by data rows using writer.writerow(). For example, one could write company information into 'companies.csv' by specifying fieldnames like 'name' and 'type', and then writing rows with company data such as 'Codecademy' and 'Google' .