Professional Documents
Culture Documents
Python : Tokens
Can someone give a simple example for data,
information, knowledge and wisdom?
Data is a given fact or a set of qualitative or quantitative variables of a certain issue. These bits of pieces
values are still raw, and is insignificant unless they are collected and arranges in a certain manner which
will now give you information. Information then is a collection of data, which can be used to answer a
certain question or describe a concept.
Well knowledge and wisdom, are bit different from data and information, since knowledge is the
awareness or the conscious understanding of information or a concept. Thus, knowledge is more on the
intellectual or cognitive ability of a being to possess and interpret information.
While wisdom is usually defined as the application of knowledge. Wisdom is the used of knowledge to
formulate a judgment or to make sense of a certain situation or concept. It is also used for formulate
ideas, and the creation of new things.
Data: notice that they are raw and insignificant.
Ages of employees: 25; 29; 45; 23; 60; 51; 35 …
Names of employees: Ben; Anna: Mark; Kathy; Rose;
Jack; Jane …
Information: now we arrange the data to make sense
and create information.
Ages of Employees: Ben is 25 yrs old; Anna is 29 yrs
old; Mark is 45 yrs old; Kathy is 35 yrs old; Rose is 60
yrs old; while Jack is 51 yrs old…
Knowledge: so now we already have the knowledge of the ages of our employees,
so now we can connect that with our other knowledge, so we may have wisdom on
this situation.
Other knowledge: (for examples sake lets assume that we conducted a survey and
found out that:) Young people have still a lot to learn, and are inexperienced, and
are available for learning; and 35 yrs old is still young; And that older folks possess
a lot of knowledge regarding work processes; and has a lot of experience; and that
most of old folks today prefer to retire early; and say we would out that the usual
retirement age is 60, yet some employees would retire early at the age of 55.
So now we create Wisdom:
1. Our employees Ben, Anna, and Kathy are still young and they are prospective leaders of the firm.
2. They might want to earn a degree in a University and let’s offer them promotion to encourage them.
3. We know that Rose is retiring this year, so we might as well train someone to replace her in her
position. That might be Ben, Anna or Kathy, or Mark since he has more experience and has more
knowledge in our business processes already.
4. And since Jack is 51 yrs old already, we might want to prepare for his retirement. That will mean that
we might loss one or two employees in at least 4 years now.
Shall we hire more employees? (Further knowledge acquired) yes we might need more employees since
our business is growing and we need more manpower
Object Identity
In Python, every created object identifies uniquely in Python. Python provides the
guaranteed that no two objects will have the same identifier. The built-in id() function,
is used to identify the object identifier.
We assigned the b = a, a and b both point to the same object. When we checked by the
id() function it returned the same number. We reassign a to 500; then it referred to the
new object identifier.
Variable names can be any length can have uppercase, lowercase (A to Z, a to z), the
digit (0-9), and underscore character(_).
Python Variables
Variable is a name that is used to refer to memory location. Python variable is also
known as an identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a infer
language and smart enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to begin with
a letter or an underscore.
It is recommended to use lowercase letters for the variable name. Amit and amit both
are two different variables
Local Variables
Local variables, on the other hand, are variables declared inside a function. These
variables are known to have local scope. This means they can be accessed only within
the function in which they are declared.
In our code, we declared a function called printName(). Within that function, we defined
a variable called name. Because we declared this variable within a function, it is a local
variable.
At the end of our code, we called our function using printName(). In response, the
program executed the printName() function.
The name variable in this example is local to the printName() function. Therefore, we
cannot access that variable outside of our function
Global Variables
It is possible for a program to use the same variable name for both a local and a global variable. In
such a scenario, the local variable will be read in local scope, and the global variable will be read in
global scope.
First, we assigned the global variable score in our code. Then, in our calculateScore() function, we
created a local variable with the same name.
The value of our local score variable in the calculateScore() function is 10. So, when we call our
calculateScore() function, the message Final Score: 10 is printed to the console.
However, outside of our calculateScore() function, the value of the score variable is 5. This is
because we set the value of the score variable in global scope to 5. So, when we print out Initial
Score: , followed by the value of the score variable, the program displays the value 5.
Global variables are variables declared outside a function. Local variables are variables declared
inside a function.
While global variables cannot be directly changed in a function, you can use the global keyword to
create a function that will change the value of a global variable
Non local Variables
Nonlocal variables are used in nested functions whose local scope is not defined. This
means that the variable can be neither in the local nor the global scope.
there is a nested inner() function. We use nonlocal keywords to create a nonlocal
variable. The inner() function is defined in the scope of another function outer().
Python nonlocal keyword is used to reference a variable in the nearest scope.
The nonlocal keyword won’t work on local or global variables and therefore must be used
to reference variables in another scopes except the global and local one.
The nonlocal keyword is used in nested functions to reference a variable in the parent
function.
Internal working of Python
•Step 1: The python compiler reads a python source code or instruction. Then it verifies
that the instruction is well-formatted, i.e. it checks the syntax of each line. If it
encounters an error, it immediately halts the translation and shows an error message.
•Step 2: If there is no error, i.e. if the python instruction or source code is well-
formatted then the compiler translates it into its equivalent form in an intermediate
language called “Byte code”.
•Step 3: Byte code is then sent to the Python Virtual Machine(PVM) which is the python
interpreter. PVM converts the python byte code into machine-executable code. If an
error occurs during this interpretation then the conversion is halted with an error
message.
Interpreted Languages
• The kernel is the server that enables Python programmers to run cells within
Notebook.
• You typically see the kernel commands in a separate command or terminal window.
• Each entry shows the time the kernel executed the task, which application the
command executed, the task it performed, and any resources affected.
• In most cases, you don’t need to do anything with this window, but viewing it can be
helpful when you run into problems because you often see error messages that can
help you resolve an issue.
•Interrupt: Causes the kernel to stop performing the current task without actually shutting the
kernel down. You can use this option when you want to do something like stop processing a large
dataset.
•Restart: Stops the kernel and starts it again. This option causes you to lose all the variable data.
However, in some cases, this is precisely what you need to do when the environment has become
dirty with old data.
•Restart & Clear Output: Stops the kernel, starts it again, and clears all the existing cell outputs.
•Restart & Run All: Stops the kernel, starts it again, and then runs every cell starting from the top
cell and ending with the last cell. When Notebook reaches the bottom, it selects the last cell but
doesn’t insert a new one.
•Reconnect: Recreates the connection to the kernel. In some cases, environmental or other issues
could cause the application to lose its connection, so you use this option to reestablish the connection
without loss of variable data.
•Shutdown: Shuts the kernel down. You may perform this step in preparation for using a different
kernel.
•Change Kernel: Selects a different kernel from the list of kernels you have installed. For example,
you may want to test an application using various Python versions to ensure that it runs on all of
them.
Python Data Types
An item has a key and a corresponding value that is expressed as a pair (key: value).
While the values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.
Dictionaries
Dictionaries are mutable. We can add new items or change the value of existing items
using an assignment operator.
If the key is already present, then the existing value gets updated. In case the key is not
present, a new (key: value) pair is added to the dictionary.
We can remove a particular item in a dictionary by using the pop() method. This method
removes an item with the provided key and returns the value.
The popitem() method can be used to remove and return an arbitrary (key, value) item
pair from the dictionary. All the items can be removed at once, using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary
itself.
Dictionary Methods
Set
Python Set is the unordered collection of the data type.
It is iterable, mutable(can modify after creation), and has unique elements.
In set, the order of the elements is undefined; it may return the changed sequence
of the element.
The set is created by using a built-in function set(), or a sequence of elements is
passed in the curly braces and separated by the comma.
It can contain various types of values.
A set is an unordered collection of items. Every set element is unique (no duplicates)
and must be immutable (cannot be changed).
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union,
intersection, symmetric difference, etc.
Frozen Set
The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set. This is based on
a data structure known as a hash table. Since sets are unordered, we cannot access
items using indexes like we do in lists.
Frozen sets in Python are immutable objects that only support methods and operators
that produce a result without affecting the frozen set or sets to which they are applied. It
can be done with frozenset() method in Python.
While elements of a set can be modified at any time, elements of the frozen set remain
the same after creation.
A particular item can be removed from a set using the methods discard() and remove().
The only difference between the two is that the discard() function leaves a set
unchanged if the element is not present in the set.
On the other hand, the remove() function will raise an error in such a condition (if
element is not present in the set).
Modifying a set in Python
Sets are mutable. However, since they are unordered, indexing has no meaning.
We cannot access or change an element of a set using indexing or slicing. Set data type
does not support it.
We can add a single element using the add() method, and multiple elements using the
update() method. The update() method can take tuples, lists, strings or other sets as its
argument. In all cases, duplicates are avoided.
Sets
A set is created by placing all the items (elements) inside curly braces {}, separated by
comma, or by using the built-in set() function.
It can have any number of items and they may be of different types (integer, float,
tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries
as its elements.
List
Tuple
Set
Dictionary
Introduction to for Loop in Python
In Python, the for loop is often used to iterate over iterable objects such as lists, tuples,
or strings.
Traversal is the process of iterating across a series. If we have a section of code that we
would like to repeat a certain number of times, we employ for loops.
The for-loop is usually used on an iterable object such as a list or the in-built range
function.
The for statement in Python traverses through the elements of a series, running the
block of code each time.
The for statement is in opposition to the "while" loop, which is employed whenever a
condition requires to be verified each repetition or when a piece of code is to be repeated
indefinitely.
On each iteration, the value is the parameter that gets the element's value within the
iterable sequence.
If an expression statement is present in a sequence, it is processed first. The iterating
variable iterating_variable is then allocated to the first element in the sequence.
After that, the intended block is run. The statement block is performed until the whole
sequence is completed, and each element in the sequence is allocated to
iterating_variable.
The for loop's material is distinguished from the rest of the program using indentation.
The range() Function
The "range" function appears so frequently in for loops, we might mistakenly believe the
range is a component of the syntax of for loop.
It isn't: it's a Python built-in method that provides a series that follows a specified
pattern , fulfilling the criteria of giving a series for the for expression to run over.
There is no necessity to count because for can act straight on sequences most of the
time.
Another method of iterating through every item is to use an index offset within the
sequence
The len() built-in method that returns the total number of items in the list or tuple and
the built-in function range(), which returns the exact sequence to iterate over.
Print()
• We can generate a sequence of numbers using range() function. range(10) will
generate numbers from 0 to 9 (10 numbers).
• We can also define the start, stop and step size as range(start, stop, step_size).
• Step_size defaults to 1 if not provided.
• The range object is "lazy" in a sense because it doesn't generate every number that it
"contains" when we create it. However, it is not an iterator since it supports in, len
and __getitem__ operations.
• This function does not store all the values in memory; it would be inefficient. So it
remembers the start, stop, step size and generates the next number on the go.
• To force this function to output all the items, we can use the function list().
Using else Statement with for Loop
When the else clause is combined with a for loop, it is performed after the circuit has finished iterating
over the list.
The following instance shows how to use an otherwise statement in conjunction with a for expression
to find students' marks from the record.
A for loop can have an optional else block as well. The else part is executed if the items in the
sequence used in for loop exhausts.
The break keyword can be used to stop a for loop. In such cases, the else part is ignored.
A nested loop is a loop inside the body of the outer loop. The inner or outer loop can be any type,
such as a while loop or for loop. For example, the outer for loop can contain a while loop and vice
versa.
The outer loop can contain more than one inner loop. There is no limitation on the chaining of
loops.
In the nested loop, the number of iterations will be equal to the number of iterations in the outer
loop multiplied by the iterations in the inner loop.
In each iteration of the outer loop inner loop execute all its iteration. For each iteration of an
outer loop the inner loop re-start and completes its execution before the outer loop can continue
to its next iteration.
Nested loops are typically used for working with multidimensional data structures, such as
printing two-dimensional arrays, iterating a list that contains a nested list.
Patterns
The basic functionality of all the techniques is the same, although the syntax and
the amount of time required for checking the condition differ.
We can run a single statement or set of statements repeatedly using a loop
command.
Statements used to control loops and change the course of iteration are called control
statements. All the objects produced within the local scope of the loop are deleted
when execution is completed.
Use if Else in For Loop to create this pattern
Use If Else with in For Loop to print odd values
Continue Statement
It returns the control to the beginning of the loop.
String = “Python loops” Use continue to achieve this pattern in For Loop
Try with omitting 0 ,p ,t
Break Statement :It stops the execution of the loop when the break
statement is reached
String = “Python loops” Use break to achieve this pattern in For Loop
Try with omitting L
Pass statements are used to create empty loops. Pass statement is also
employed for classes, functions, and empty control statements.
Python Strings
• Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes.
• The computer does not understand the characters; internally, it stores manipulated
character as the combination of the 0's and 1's.
• Each character is encoded in the ASCII or Unicode character. So we can say that
Python strings are also called the collection of Unicode characters.
The format() method is the most flexible and useful method in formatting
strings.
The curly braces {} are used as the placeholder in the string and replaced by
the format() method argument.
Python String Formatting Using % Operator
Python allows us to use the format specifiers used in C's printf statement.
The format specifiers in Python are treated in the same way as they are treated in C.
However, Python provides an additional operator %, which is used as an interface
between the format specifiers and their values.
In other words, we can say that it binds the format specifiers to the values.
Difference between Pass and Continue
Functions in python
A function is defined by using the def keyword and giving it a name, specifying the
arguments that must be passed to the function, and structuring the code block.
After a function's fundamental framework is complete, we can call it from anywhere in
the program.
Pass by Reference vs. Value
In the Python programming language, all arguments are supplied by reference. It implies
that if we modify the value of an argument within a function, the change is also reflected
in the calling function.
Function Arguments
Function Arguments
The following are the types of arguments that we can use to call a function:
1.Default arguments
2.Keyword arguments
3.Required arguments
4.Variable-length arguments
Default Arguments
A default argument is a kind of parameter that takes as input a default value if no value
is supplied for the argument when the function is called. Default arguments are
demonstrated in the following instance.
Keyword Arguments
The arguments given to a function while calling in a pre-defined positional sequence are
required arguments.
The count of required arguments in the method call must be equal to the count of
arguments provided while defining the function.
We must send two arguments to the function function() in the correct order, or it will
return a syntax error.
Variable-Length Arguments
These types of Python functions are anonymous since we do not declare them, as we
declare usual functions, using the def keyword. We can use the lambda keyword to
define the short, single output, anonymous functions.
Lambda expressions can accept an unlimited number of arguments; however, they only
return one value as the result of the function. They can't have numerous expressions or
instructions in them. Since lambda needs an expression, an anonymous function cannot
be directly called to print.
Lambda functions contain their unique local domain, meaning they can only reference
variables in their argument list and the global domain name.
Although lambda expressions seem to be a one-line representation of a function, they
are not like inline expressions in C and C++, which pass function stack allocations at
execution for efficiency concerns.
Scope and Lifetime of Variables
Quite often, people wonder why should we use recursion when loops exist.
Everything can be coded without recursion.
The difference iteration and recursion is there is no sequential end to recursive code.
It tests on a base condition and can go on as long as that is satisfied. Recursion in
python is used when problems can be broken into simpler parts for easier
computation and more readable code.
For example, if you want to search for a student in a school, there would be two
ways to do so.
You could gather all the students in an auditorium and then search for her one by
one.
A more straightforward method would divide the school into sections until the
smallest section could be made to find the student, i.e., it would make more sense to
first search for the grade she is in, then the class, and then you'll be able to find her
location much more easily.
Although recursion is found to give results faster in some cases when properly
optimized, it can also add to memory usage.
Thus, recursion should be used only when needed.
Recursive function in Python has two parts:
(a) Base Case - This helps us to terminate the recursive function. It is a simple
case that can be answered directly and doesn't use recursion. If satisfied, it returns
the final computable answer. If this is omitted, the function will run till infinity.
Python interpreter limits the number of recursive calls for a function to 1000 by
giving a recursion error.
(b) General (Recursive) Case - This case uses recursion and is called unless the
base condition is satisfied.
A recursive function makes use of a call stack.
Every time the recursive function gets called,
that function gets added to the top of this stack.
Imagine opening up an onion and you place
every layer you peel near it.
So, each layer, peeled, would be placed at the
top of this peel stack. Now compare this to a
recursive function. Peeling each layer would be
a recursive function call.
When the first layer is peeled, the first peel()
would be added at the top of the stack, then the
next would be added above it and so on, until
the process is completed.
a) Tail Recursion - A recursive call is said to be tail-recursive
if it is the last statement to be executed inside the
function.
Example of a Tail Recursive Call
The following function prints natural numbers from n in
descending order.
It is done by traversing digits from n to 1 and returning
each digit at a call.
In this example, the position of the print statement holds
utmost significance.
The base case would be 0, where no value would be
returned to the call.
In the first invocation of the function, the print statement
causes 5 to be displayed on the screen and disp(4) is added
at the top of the stack. In the next invocation, 4 is printed
and disp(5) is added to the stack.
Similarly, 3, 2, and 1 are printed in the following
invocations. In the last call, the value of n becomes 0, and
thus the base case is satisfied, causing recursion to
terminate.
Example of a Call That is Not Tail-Recursive