TABLE OF CONTENTS

BEFORE STARTING

FIRST PYTHON PROGRAM

VARIABLE, DATA TYPE, DATA INPUT

OPERATOR

COMMENT

STRING MANIPULATION

LIST

TUPLE

SET

DICTIONARY

CONDITIONAL LOGIC

LOOP

COMPREHENSION

FUNCTION

FILE

ERROR HANDLING

CLASS, OBJECT AND METHOD

INHERITANCE

ITERATOR AND GENERATOR

MAGIC METHOD

MODULE AND PACKAGE

DECORATOR

REGULAR EXPRESSION

Unit testing

Docstring

DEBUGGING AND LOGGING

DATA STRUCTURE AND ALGORITHM

GUI PROGRAMMING

CONCLUSION

BEFORE STARTING

Introduction

This course is an introduction to programming with Python for total beginners. Python is a dynamic programming language, which has won the heart of many developers. This includes thousands of engineers from many large organizations including Google, Dropbox, Instagram, Mozilla. Python is a language whose structure is unique in style and expression is fantastic. This Excellent language has spread so far - on the other hand - Web, desktop, mobile, system administration, scientific computing or machine learning - walk deeply in Python

To be more specific - if you want to develop web applications through the framework of Django, Flask, Tornado etc., you must know the most important programing language-Python. Again, the knowledge of Python programming can be used for software development with a desktop or graphical user interfaces, with packages like PyQT like Toolkit or Tkinter. The language is designed to be easy to read, which makes it a great language for beginners to learn.

In this course, we’ll be learning the basics of programming all that stuff of Python 3.

What is python?

Python means python, okay? But in this book, we are discussing that python, which is an object- oriented programming high -level language. Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands as a successor to the ABC language (itself inspired by SETL), capable of exception handling and interfacing with the Amoeba operating system.
Its implementation began in December 1989. This is not named on Python exactly; it has been named on Monty Python Flying Circus.

Sir Guido van Rossum told, 6 years ago from today, in 1989 at December, I was thinking about working on a programming language project. My office will be closed. And I have a computer in my home. But I have nothing to pass my time. So, I decided to make an interpreter for my own scripting language. The language will be just like the ABC programing. I am hopeful that the Unix/C hackers will be interested in this language. I named that language like Python. I am a huge fan of Monty Python Flying Circus, that is why I choose this name.

In other words, Python is a high-level, interpreted, interactive and object-oriented scripting language. We may know about C and C++; these are compiled language. When we run it, the compiler reads all the code, then complies it. As a result, if there is any error in the code, the whole code doesn’t run. Python is different from these problems. Python interpreter reads the code line by line and interprets it. Wherever it finds an error, the code doesn’t run only from that part.

Why python?

I estimate that Python makes our coders ten times more productive than Java programmers, and 100 times more than C programmers. - Curt Finch, CEO, Journyx

We will learn to programme. This is very good. But as a programing language, why python?

Why will we learn python?

Let's see those causes

Open-sourc
e

Python opensource. We can distribute the scripts which are written in Python. Even we can sell them for business purpose. This kindness made python great.

General-purpose language

Python is a general-purpose language. It means whatever you can do with any programing language that can be done using python also. And by using the right library and tool, you can do the work more easily.

Professionally, python is used in almost all section like programming, GUI-programing, network programming, system programming, big-data, data mining, data analysis, artificial intelligence, scientific computing etc.

Beginner friendly

Python is a beginner, friendly language. Python is designed in such a way that it can be understood very easily just by reading it. Reading a python code and paragraph is the same. It never feels as a programing language. So, writing python is another name of fun. When you add fun with your work, your brain catches that work so fast. That is why all the world the greatest universities in the world teaches python as the starting language of their programming. And in GitHub, a lot of projects is analysis for understanding. Python is the 3rd popular programing language.

Community Support

We will know what community support at that time is when we step in a programming world. We write code; we think all is ok. But when we run it, we’ll see some other stories. Maybe for fixing those problems we need to stay awake 2/3 nights. Programming's other name is taking help and helping. In this topic, python is in a very good position. Because python
has the largest stalk over the community. Python has World's largest community meet-up.

Carrier

Stack Overflow Developer Servey-2016 says Python is the 6th popular technology. Python is holding this position last for 4 year, and its popularity is increasing day by day. Not only this but also python is in the 3rd position in Most Wanted Technology. Python is in the 4th position in the highest technology list. Python is into the top ten at the top-paying technology list in several sectors.

Python is fast enough for our site and allows us to produce maintainable features in record times, with a minimum of developers. - Cuong Do, Software Architect, YouTube.com

Now we will see which the world’s best company uses Python. File hosting site Drop-Box uses python. The desktop client of the Drop-Box is created using python. The charming part is, Sir Guido van Rossum now works on Drop-Box. Instagram of Facebook uses python.

Disqus, Pinterest, Quora, Bit -bucket, Reddit, Dig everyone uses python. Besides, add -ons of Mozilla and support sites are created using python. And GOOGLE also uses python in a lot of ways. Python programmers are paid the highest average salary.

Python 2 or python 3..?

Python 2.x is legacy; Python 3.x is the present and future of the language. Until now, we came to know that. Python is sold one market in two versions. 1.Python-2 And 2. Python-3. All Pythonists are fluent in Python 2 and 3. But the happiness is, the difference between both pythons is very narrow. And the sad news is in 2020 there will be a farewell of Python-2. So, Python 3 is the present and future of Python. If
someone wants to start learning python language, he should go for Python-3. It will be the best choice. And as I told you the difference between those two are very narrow. As the Python-3 is the latest one so we should have no problem to learn it. So, we will learn about Python-3 in this E-book.

Windows , Mac OS or Linux Distro?

Platform choosing may be a problem. If we want, we can use any platform. In this book, we will use Linux Distro (Ubuntu). So, I will suggest that everyone should use Linux Distro (better Ubuntu 16.04). It is really easy to use python in Linux platform. But if you are windows or Mac user, you need not change the platform. You can program in your running platform also.

Up to this, we came to know that, Python is an interpreted language and we need python interpreter to run it. So, where will we find this interpreter?

If you visit the official website of python, we will find the interpreter. Windows, Mac and Linux, for all major platform you will find this interpreter for free. We will use the Python-3.x build. We should always use the latest one, but we are using 3.5.2 in this book.

Installation

Python in windows

If you are a Windows user, you should download .exe version of 32-bit or 64-bit as per your operating system. After downloading you should install it by double-clicking on it. When we see the setup window, we should check the “Add Python 3 to PATH” box. Then install it by usual rules.

After finishing the installation, we should open command prompt and type python –V to check the version

All Apps>Python 3> IDLE in this directory we will find IDLE. We will learn about IDLE very soon.

Python in Mac-O
S

For Mac-OS, you should download .pkg file with the version of 32-bit or 64-bit as per your operating system. And we should start installing the file. We can install it by following the instruction in the graphical interface on the screen. But if we want, we can install it using the terminal only. For this, we will install the Xcode application. For installing command line tools, we need to command this command.

Xcode-select –install

We will find a pop- up window after this. From that window, we will install command line tools. Then we will browser Homebrew. For this, we need this command->

/usr/bin/ruby -e "$(curl –fsSL

https://raw.githubusercontent.com/Homebrew/install/master/install)"

After finishing the installation, in this profile ~/.bash_profile we will add export PATH=/usr/local/bin:$PATH

Then we will restart the terminal. Now the terminal is ready to install python.

Brew install python3

After installation, we need to check the version.

Python3 –version

Python in Linux

In Linux python is installed by default. We will just give command “python3” by opening the terminal, and we will see an interactive python shell. If it doesn’t open, we need to give the following command to install python. For Ubuntu:

Sudo apt-get install python3 python3-dev python3-pip

After installation completion, we will try to open the interactive shell again. Then we will find this-

Where to write the code?

For Linux and Mac-OS we should open the terminal and command python3. Python interactive shell will start after the command. For windows, we need to open a command prompt(cmd) and to command “python”. Then we will see a very charming interactive shell. If we want to do coding in a nice place, we can use IDLE (Integrated Development and Learning Environment). This is python’s basic IDE (Integrated Development Environment). Right now, we have no need to use any huge IDE. By when we really need it then we can use Eclipse with PyDev plugin. Or we can use Zetbrain’s PyCharm. PyCharm has two versions. One is community addition, which is free in cost. And another one is the pro version; we need to pay to use this. But for a student, you will get 1 year of a free trial. A student can renew the trial subscription after it expires. And for code reader, we need to discuss Atom and Sublime Text. The first open source is free; we need to pay for the rest.

Suppose, in any code editor we wrote any code in the file name “test.py”. At the last of every python file, we need to write .py . Now, for running the test.py file (by giving the files directory) give

command ->

Python3 test.p
y

Then, the code which is written in this file will execute and will show us the Output.

We will use the command line and in the terminal interactive python shell at the beginning of this book. But one can use IDLE’s Python shell. But after several chapters when will use some larger codes then we will use IDLE . But not the shell this time. We need to go to New File from File. A new file will be opened. We will write code in this file. After the finishing, we need to save the file from File. If necessary, we need to check there is .py when saving the code. And at last from the run, we need to click on the Run Module. As a result, we will see a new window to show the output. We can close this new window whenever we want to close.

FIRST PYTHON PROGRAM

We will write our first Python code. We got the place to write the code in the previous chapter. So, without wasting time, let's get started. First, open the python shell.

Python 3.5.2 (default, Sep 10 2016, 08:21:44)

[GCC 5.4.0 20160609] on Linux

Type "help", "copyright", "credits" or "license" for more information.

>>>

can We see ? >>> this symbol. We need to write our codes one by one beside this symbol. We call every line of the code as a statement. Press Enter after writing print ("I am gonna be a Pythonist.") beside the >>> symbol. We will get the output at the next line I am gonna be a Pythonist.

Python 3.5.2 (default, Sep 10 2016, 08:21:44)

[GCC 5.4.0 20160609] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>> print("I am gonna be a Pythonist.") I am gonna be a Pythonist.

>>>

We just wrote a single line of code. Beside >>> symbol whichever code we have written, we got the Output at the next line.

Output means the result of the code. Watch it carefully, print("I am gonna be a Pythonist.")

In this line, there is two part:print() and “I am going to be pythonists.
”

The first part is a function; we can compare with a machine. As an example, if we put rice on this side and it gives us white rice. We will learn about function in future.

The last one is String. What is the string? In a word, whichever lies between single Quotation or double Quotation. That is a string. String means any text or any writing. We will know about the string at the time we discuss data type.

So, what have we learned? Whatever we will give inside the print() function that will be printed on the screen. Let’s write another Program.

>>> print("My name is dipta, and I am not a terrorist.")

>>>My name is dipta, and I am not a terrorist.

Fun, isn’t it? Let’s learn something more. This python shell can work as a calculator. Plus, Minus, Division, Multiplication, Modulus etc. small mathematics can be done at any time. Let’s do these using python.

>>> 3+2

5

>>> 10-4

6

>>> 6*7

42

>>> 48/3 16.0

>>> 10%3

1

>>> 5 + (9 * 3)

32

>>> -13 + 5

-8

Page

VARIABLE, DATA TYPE, DATA INPUT

Let’s do some math using python.

If a=5 and b=10. Then, ab=?

Given that,

a = 5

b = 10

So,

ab = 5 * 10

= 50

If the question comes, what is a and b in this program? Then we will reply these are variable. We all know about variables, more or less.

Variable is just like a box. We can keep anything in a box, just like that we can keep any values in a variable. There will be a = symbol every time between a value and a variable. Variable lies at the left side and values at the right. Whichever value we give at the right hand, that stores immediately at the variable which is at the left hand. This process is called an assignment. But the value stores at computer memory. Every variables memory address is different and unique.

>>> x = 5

>>> x

5

>>> x = 12

>>> x

12

>>> x = 10.34

>>> x

10.34

>>> x = 'Python
'

>>> x

'Python'

In this Program, we have added a lot of value in several statements into x. But when we entered a value, the previous one is replaced. It is called as re-assignment.

There are some rules in python how to write the variables. A variable can be started from any A-Z in capital form or any a-z in smaller form or _ underscore. We can use any letter, digit (0-9) or underscore. But we cannot use some symbols like @, $, %. And there is another restriction in python which is, we cannot use python’s reserved keyword. There is a table given below about the reserved keywords. No need to memorize. They’ll be memorized into your mind sub-consciously slowly.

Keywords

False

class

finally

is

return

None

continue

for

lambda

try

True

def

from

nonlocal

while

and

del

global

no
t

with

as

Elif

if

or

yield

assert

else

import

pass

break

except

in

raise

In python, every variable and identifier are case sensitive. That means in python, the smaller a and the capital A is not the same thing.

Data Type

Let’s get back in the previous example, where a=5 meant that inside a there is a 5. 5 is an integer type variable. If we say a=3.14169265, then which data type is our a now? Now, a is a float type variable. Now, will do the solution of the math using python.

>>> a = 5

>>> b = 10

>>> a * b

50

The same answer again. Meanwhile, we learned about print() machine or function. Now we will learn about another function. This new one is a type(). If we give any variable inside this then which data type will it be? Let’s see
:

>>> a = 5

>>> type(a) <class 'int'>

>>> b = 10

>>> type(b) <class 'int'>

>>> type(a * b)

<class 'int'>

We can see that, by running type(a) statement we got output <class ‘int’>We need not understand this output write now. We will just focus on int. This int is an integer. Now we will see the common data types of python in a look.

>>> a = 1

>>> type(a) <class 'int'>

>>> b = 3.1416

>>> type(b) <class 'float'>

>>> c = "Hello World!"

>>> type(c)

<class 'str'>

>>> d = True

>>> type(d) <class 'bool'>

- Int: Integer type variable. Ex: 1,2,100,501 etc.

- Float: Float type variable. Float means divided values. Ex: 3.1416, 20.0,876.769 etc.

- Str: String type variable. We learned about it. In a word, the things will be inside of any quotation.

- Bool: Boolean type variable. This is a fun topic. Its value will always be either true or false. In a simple word, by using this data type, we get to know truth or lie.

Generally, we use these 4 variables, but there are a lot of variables that we use also. Ex:

Long, complex, Unicode, list, tuple, set, dict etc.

Data Input

We solved a mathematic above. We discussed there that a is 5 and b is 10. So, we completed that math very easily. But if we want the use to
give the values? I mean, the user will give several data several times, and we will give output by the help of python.

That is why we will learn about a new function input(). This function takes data from the user and stores it with the variables. As an example:

>>> a = input()

10

>>> a

'10'

Now, by taking data from the user, we stored it with the variable. After that, we checked the output of a. Now, Let’s do that math again. But this time the user will provide the values.

>>> a = input()

10

>>> b = input()

40

>>> a* b

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: can't multiply sequence by non-int of type 'str' >>>

The result should come 400, but something fishy is coming here as output. Let’s try to find what are these shits.

Python threw an error here. When python reads any error, it throws several errors for the solution. So, we faced an error that is TypeError. When we do problems at typing. We face these problems. Let’s see the error message again. “can't multiply sequence by non-int of type ‘str’” what is meant by this language? In a very easy word, we cannot multiply two string type variables. But the user has put the integer data. Then where is the problem? Let’s investigate again..
.

>>> a = input()

10

>>> type(a) <class 'str'>

>>> b = input()

40

>>> type(b) <class 'str'>

>>> a* b

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: can't multiply sequence by non-int of type 'str'

What have we done? Interesting one. We gave the data input as integer and variables went inside as string.

Type Casting

There is a fun thing called Python typecasting. Actually, there is this feature in all programming languages. It uses a type of variable to be cast in another type. The cast is used to mean that the variable is actually what it was. And this type of casting is done with the help of several functions. We will look at some useful functions-

1. int() : It casts in integer

2. float() : It casts in floats

3. tuple() : It casts in tuples

4. set() : It casts in sets

5. list() : It casts in lists

6. str() : It casts in strings

7.dict() : It casts in dictionaries

Now see an example,

>>> a = 5

>>> type(a) <class 'int'>

>>> a = str(a)

>>> type(a) <class 'str'
>

Then we assigned an integer value 5 in variable a. Then we checked the type of a, which is int.Then, we send an into str() to cast it as a string. Then, we assigned that value intoan again. And at last, we again checked a’s type. That became str. So, now we have understood the casting. Let’s do the math.

>>> a = input()

10

>>> a = int(a)

>>> b = input()

40

>>> b = int(b)

>>> a * b

400

Page

Hmm, now we got our expected result. Let’s write it easily,

>>> a = int(input())

10

>>> b = int(input())

40

>>> a * b

400

Now, our program looks much smaller and easy. We exactly made our statement same of input and casting. If we want, we can give a and b’s value in a single line rather than two different line. But how? For that, we need to do two different work. One: we need to give space between input data to separate them. Second: split() function using. An example can make it clear:

>>> a, b = input().split() 10 40

>>> a

'10'

>>> b

'40
'

When we are learning python, we will try to solve several online problems to judge our self. Where we may need to take input of data in a single line. So, we learned it early.

OPERATOR

We worked on mathematics using operator. Like 10+15=25, here + and = are operator. In the other hand, 10, 15, 25 are operands. Python has a lot of operators. According to the type, we can classify them

Arithmetic operator.

It is part of several mathematical topics. We discussed the plus (+) sign; it is an arithmetical operator.

+ (Addition) :-
Adds values on either side of the operator.

- (Subtraction) :-
Subtracts right hand operand from the left-hand operand.

* (Multiplication) :-
Multiplies values on either side of the operator.

/ (Division) :-
Divides left hand operand by right-hand operand

% (Modulus) :-
Divides left hand operand by right-hand operand and returns the remainder

** (Exponent) :-
Performs exponential (power) calculation on operators

// (Floor Division) :-
The division of operands where the result is the quotient in which the digits after the decimal point are removed.

Some uses of Arithmetic Operator:

>>> 3+2

5

>>> 10-4

6

>>> 6*7

42

>>> 48/3 16.0

>>> 10%3

1

>>> 3 ** 2

9

>>> 5 + (9 * 3)

32

>>> -13 + 5

-8

>>> 1.0/2.0

0.5

>>> 1.0//2.0

0.0

P

Comparison operatorage

For comparing we use these operators.

== :- If the values of two operands are equal, then the condition becomes true.

!=
:- If the values of two operands are not equal, then condition becomes true.

<>
:- If values of two operands are not equal, then condition becomes true.

> :- If the value of the left operand is greater than the value of right operand, then condition becomes true.

< :- If the value of the left operand is less than the value of right operand, then condition becomes true.

>=
:- If the value of the left operand is greater than or equal to the value of right operand, then condition becomes true.

<=
:- If the value of the left operand is less than or equal to the value of right operand, then condition becomes true.

Boolean

The best thing about a Boolean is even if you are wrong, you are only off by a bit.

Now let’s see some Boolean expressions.

>>> 2 == 2 True

>>> 2 != 2 False

>>> 5 < 3

False

>>> 5 > 3 True

>>> 5 <= 3 False

>>> 5 >= 3 True

Assignment operato
r

The previous chapter, We had written an a=10 statement. Here = is an operator.

Lorem ipsum dolour sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua

= :-
Assigns values from right side operands to left side operand

+= :-
It adds right operand to the left operand and assigns the result to left operand

-= :-
It subtracts right operand from the left operand and assigns the result to left operand

*= :-
It multiplies right operand with the left operand and assigns the result to left operand

/= :-
It divides left operand with the right operand and assigns the result to left operand

%= :-
It takes modulus using two operands and assign the result to left operand

**= :-
Performs exponential (power) calculation on operators and assign value to the left operand

//= :-
It performs floor division on operators and assigns value to the left operand

Uses of assignment operators

>>> a = 5

>>> a

5

>>> a += 2

>>> a

7

>>> a -= 3

>>> a

4

>>> a *= 3

>>> a

12

>>> a /= 2

>>> a

6.
0

Logical operator

There are three logical operators in python.

And
- If both operands are true, then the condition is the truth.

Or
- If one of the operands is true.

Not
-If none of the operands is true.

With Boolean Expressions there are a lot of uses of logical operator. Example:

>>> 2 == 2 and 3 == 3 True

>>> 2 == 2 and 3 == 4 False

>>> 2 == 2 or 3 == 4 True

>>> 2 == 5 or 3 == 4 False

>>> 2 == 5

False

>>> not 2 == 5 True

Membership operator

There are two memberships operator in python.

In
- if we can find left hands operands into the right hand's operand, only then condition applied.

Not in
- if we can find right hands operands into the left hand's operand, only then condition applied.

Example of membership Operator:

>>> a = 'Bangladesh'

>>> b = 'desh'

>>> b in a

True

>>> a in b False

Identifier operator

Python has only two identity operators. They are->

is -> If the operands of both sides point to the same object, only then this condition is true.

is not -> If the operands of each side don’t point to the same object, only then this condition is true
.

Let’s see some examples of Identity Operator.

>>> a = 'Bangladesh'

>>> b = 12

>>> a is b

False

>>> a is not b True

We need to remember these six operators. For remembering these operators, we need not memorize by reading. We will do practices to store them in our brain permanently.

Page

COMMENT

This matter is very small. Very soon, its discussion will end. But its effects are very long-term. We will not restrict it to this only; Rather, we have to learn how to use comments in different fields. At first, we will know what the comments are? We have already written a few small programs. There were fewer variables. There is no major implementation of Python. When we hand over a big project, we should keep a comment on different things. What variables have been declared for? What functions do a function have? What is the need for a class? Etc. It should be noted that things are written down. As a result, when we go to work with the old program more than a long time, it will be easy to understand. Not only that, others can easily understand our program. Comments are never executed. The comments are actually some statements that the interpreter will not interpret.

The comment should be like a full sentence, but if you want to use the phrase can be used. Regardless, the comments should always start with upper case letters, unless there is an identifier at the beginning. If the comment is small, then at the end of it, it is not mandatory to give the punctuation. However, because block comment is the full sentence, it is recommended to have the punctuation at the end of it.

I apart from any line in Python, it is not executed if it # marks before any statement. Such as:

>>> a= 23

>>> #a is an int variable

…

>>>

Inline commen
t

With the statement, the comments in the same line are called inline comments. At least, inline comments with two spaces have to be separated from the statement.

>>> a=15 #a is a dividend

>>> b=3 #b is a divisor

>>> a/b

5.0

>>>

In the part of every line, # will get, since then that line will not be executed. What will be the output of the following line?

>>> print("I like the # symbol.")

Block Comment

Block comment means the multi-line comment. But there is nothing different for multi-line commenting in Python. # To make line-by-line comments. Each line of the block starts with a # symbol and then space. Such as:

>>> # a is an int variable

… # This is another comment

…

>>>

Document string

Python Docstring is the documentation string, which is a string literal, and it occurs in the class, module, function or method definition, and it is written as a first statement. Docstrings are accessible from the docattribute for any of the Python object and also with the built-in help() function can come in handy
.

Also, Docstrings are great for the understanding the functionality of the larger part of the code, i.e., the general purpose of any class, module or function whereas the comments are used for code, statement, and expressions which tend to be small. They are a descriptive text written by a programmer mainly for themselves to know what the line of code or expression does. It is an essential part that documenting your code is going to serve well enough for writing clean code and well-written programs. Though already mentioned, there are no standard and rules for doing so.

There are two forms of writing a Docstring: one-line Docstrings and multi-line Docstrings. These are the documentation that is used by Data Scientists/programmers in their projects.

>>> """

... a is an int variable.

... This is another comment.

... """

'\na is an int variable.\nThis is another comment.\n'

>>>

STRING MANIPULATION

We all know that, everything inside any quotation is a string. The string is a text. The string is in two parts. Single Quote and Double Quote. There are pros and cons to both.

>>> a = 'bangla'

>>> b = "desh"

>>> type(a) <class 'str'>

>>> type(b) <class 'str'>

In this example we saw both single and double quote. The single code has some cons. If we want to mark anything inside the single code with a quotation, then something fishy happens. Let’s see,

>>> c = 'Bangladesh is my 'motherland', I love her very much.' File "<stdin>", line 1

c = 'Bangladesh is my 'motherland', I love her very much.'

^

SyntaxError: invalid syntax

Why are we facing this problem? The main reason is when python finds ‘ symbol at first, it waits for the next ‘ . When it finds the next one it thinks as the end of the string. But, the string is not exactly ended. If python finds another ‘ later. It thinks there is an error and throws SyntaxError. To get rid of this kind of problem we can use double quotation symbol.

>>> c = "Bangladesh is my 'motherland', I love her very much."

>>> c

"Bangladesh is my 'motherland', I love her very much."

Ok, if we use double quote inside a double quote? Let's find out -
>

>>> c = "Bangladesh is my "motherland", I love her very much." File "<stdin>", line 1

c = "Bangladesh is my "motherland", I love her very much."

^

SyntaxError: invalid syntax

Again, the error of the syntax. So, we need a better solution, right? And that is \ backslash.

Backslash skips the next single or double quotation.

>>> c = "Bangladesh is my \"motherland\", I love her very much."

>>> c

'Bangladesh is my "motherland", I love her very much.'

Then can we solve the single quotation problem also with the help of backslash?

>>> c = 'Bangladesh is my \'motherland\', I love her very much.'

>>> c

"Bangladesh is my 'motherland', I love her very much."

Yes. Now, when we give two backslashes, one will be printed. Besides, in python we use \n for a new line and \t for tab.

>>> print('\')

File "<stdin>", line 1

print('\')

^

SyntaxError: EOL while scanning string literal

>>> print('\\')

\

>>> print('\\')

\

>>> print('\n')

>>> print('\t')

>>
>

Value access in string

Now, let’s get back to the first example. Here, how can we access the value of a and b, we assigned before? Easily ->

>>> a = 'bangla'

>>> b = "desh"

>>> a

'bangla'

>>> b 'desh'

We can access value generally. Ok, have we ever thought how the string stores with the variable? We assigned 6 characters word ‘bangla’ inside a variable. An index is like a huge building. The place is single but on every floor a lot of people can live. On that building we call the ground floor as zero. Then, the first floor is 1 and the second one is 2. Index idea is the same. String’s index is always starting from 0. So, for this six ‘bangla’ character what will be the indexing? Hmm, 0,1,2,3,4,5 just like this. 5 is the ending. Not 6. because we started counting from 0. Now, we should see how we can access the value in a string ->

>>> a = 'bangla'

>>> a[0]

'b'

>>> a[1]

'a'

>>> a[2]

'n'

>>> a[3]

'g'

>>> a[4]

'l'

>>> a[5]

'a'

>>> a[6]

Traceback (most recent call last):

File "<stdin>", line 1, in <module
>

IndexError: string index out of range

We all can understand that after variable to access value. we need to put an index number inside [] symbol. There is an error at the end, have you noticed? Why? We came to know earlier that, there are only 6 characters. So, up to 5 there will be indexing. There is nothing in 6, IndexError is being throwed for this reason by python.

We can access a limited range of index value. Ex:

>>> a[1:4]

'ang'

We have accessed from index 1 to 4 only. 4 means, 1,2,3 index. Not the 4th one. We can access the first 3 and last 2 indexes very easily.

>>> a[:1]

'b'

>>> a[:2]

'ba'

>>> a[:3]

'ban'

>>> a[2:]

'ngla'

>>> a[4:]

'la'

>>> a[-1]

'a'

>>> a[-2]

'l'

A[:2] can be used to access the first 2 value. On the other hand, a[2:] is used to discard the first two values. Just like that a[-2] will show the last two values. Isn’t it's fun?

Now, let’s try to update the values in the index on your own.

String formatting

We have learned about print() at the beginning of this book. We can print anything on the scree
n

>>> a = 'bangla'

>>> print(a) bangle

We have assigned ‘bangla’ in variable a. Now, we have printed a. Now, add some masala in this code.

>>> a = 'bangla'

>>> print(a) bangla

>>> print('My favorite language is:', a) My favorite language is: bangle

We have used one more statement than the previous one. We could use string formatting operator %. This function brought the power of the C language’s printf() function’s power in python. Let’s do the program again,

>>> print('My favorite language is: %s' %a)

My favorite language is: bangle

Nice, isn’t it? %s is the symbol of string format. For integer we used %d and for floar %f.

>>> number = 436.15757823658945

>>> print(number)

436.1575782365895

>>> print('%.2f' % number)

436.16

>>> print('%.4f' % number)

436.1576

>>> print('%.1f' % number)

436.2

>>> print('%.5f' % number)

436.15758

Now, see something hard now
.

>>> a = input()

Bangla

>>> b = input() English

>>> print('My favorite languages are:', a, 'and', b) My favorite languages are: Bangla and English

Here, we took the input of two languages name into a and b. Then we created a nice line and printed them. We can use string operating format to do the work also.

>>> a = input() Bangla

>>> b = input()English

>>> print('My favorite languages are: %s and %s' %(a, b)) My favorite languages are: Bangla and English

Join multiple strings

Now, we will play with the string. For this we need to declare two variables a and b.

>>> a = 'bangla'

>>> a

'bangla'

>>> b = 'desh'

>>> b

'desh'

Now, how can we combine a and b? Easy. The + operator will be used to join two strings. It is called concatenation.

>>> a = 'bangla'

>>> a

'bangla'

>>> b = 'desh'

>>> b

'desh
'

>>> a+b

'bangladesh'

Now, we will take three variables x,y,z. Their values will be ‘dhaka,’Khulna’,’sylhet’.

Now, we will join these three variables. But the condition is, we need to use – symbol this time.

>>> x = 'dhaka'

>>> x

'dhaka'

>>> y = 'Khulna'

>>> y

'Khulna'

>>> z = 'sylhet'

>>> z

'sylhet'

>>> x + '-' + y + '-' + z 'dhaka-Khulna-sylhet' ? join()

>>> x = 'dhaka'

>>> x

'dhaka'

>>> y = 'Khulna'

>>> y

'Khulna'

>>> z = 'sylhet'

>>> z

'sylhet'

>>> '-'.join((x, y, z)) 'dhaka-Khulna-sylhet'

Very easy, isn’t it? Have we noticed the format to use the function? Hmm, better if you notice it.

Capital and Smaller

Variable a’s value ‘bangla’ is in smaller font. Now, we will make it capital. For, this capitalization() function will be used. This function makes the first character capital of any string
.

>>> a.capitalize()

'Bangla'

To make each character capital we need to use the upper() function.

>>> a.upper()

'BANGLA'

We made a sentence: they’re bill’s friends from the UK. Now if we want to make every first character of the worlds to be capital then we need to use title() function.

>>> "bangladesh is my motherlans. i just love her.".title() 'Bangladesh Is My Motherlans. I Just Love Her.'

We made enough capital font. Now, we should try to make smaller ones.

>>> 'BANGLA'.lower()

'bangla'

>>> 'Bangla'.lower()

'bangla'

The same thing can be done by casefold() function.

>>> 'BANGLA'.casefold()

'bangla'

>>> 'Bangla'.casefold()

'bangla'

The casefold() method removes all case distinctions present in a string. It is used for caseless matching, i.e. ignores cases when comparing.

If we need to swap the capital fonts to smaller and the smaller ones to capital, we will use swapcase() function.

>>> 'Bangla'.swapcase()

'bANGLA
'

The string is the addition of several characters. We can access characters from strings following the index. To know how many characters are there in a string we use len() function. This function gives an output of the length and returns it.

>>> a

'bangla'

>>> len(a)

6

We can use count() function to know how many time some single character is repeated.

>>> a

'bangla'

>>> a.count('a')

Not cleared, right? We will see another example. Count() function is very smart.

>>> sentence = 'How can a clam cram in a clean cream can?'

>>> sentence.count('c')

6

>>> sentence.count('c', 5)

5

>>> sentence.count('c', 5, 9)

0

At the second statement we tried to know how many c’s there are is the sentence of the first statement. And at the last statement we wanted to know how many c’s from 5 to 9 index.

We will use find() function to know where there is a c in our sentence.

>>> sentence = 'How can a clam cram in a clean cream can?
'

>>> sentence.find('c')

4

We got the output as 4. But we should have got a lot of output. But no, this function will only find the first search result of all. Ok, we got a c in the 4th index, now try to find in the 5th.

>>> sentence.find('c', 5)

10

Page

LIST

In Python, the list is a smart data type. The reason for saying smart is because of its many practical uses. Those who can do C, C ++ or Java may notice that these languages have a thing in the array. But in Python, there is nothing in the array. Python can be done by an array list. But interestingly, the list is much smarter than the array.

Although the list is called as the data type, the list is actually included in Python's built-in data structure. The list is a data type, but the data structure is best said. The data structure is a special form of data storage and organizing. In this book, we will learn about Python's four types of data structure: list, tuple, set and dictionary.

In Python, creating a list is a very easy job. I cut the items off by commas and I put them inside [] symbol. Let's look at an example:

>>> a= []

>>> a

[]

>>> type (a) <type ‘list’>

>>> a = [‘onion’. ‘potato’, ‘ginger’, ‘cucumber’]

>>>a

[‘onion’. ‘potato’, ‘ginger’, ‘cucumber’]

>>> type(a)

<type ‘list’>

The data type of the list item can be anything. We have used the string in this list. But the integers, the float that could be used happily. I could also use list, tuple or dictionary if I wanted to. In fact, there is no restriction on the list of all the items in the same type of data, the mixed data type is acceptable

.>>> b = [‘onion’. ‘potato’, ‘ginger’, ‘cucumber’, 1, 3.1416]

>>> b

[‘onion’. ‘potato’, ‘ginger’, ‘cucumber’, 1, 3.1416
]

>>> type(b) <type ‘list’>

Access Item

Now we will access the list of items and values. List access and string access are the same. Index of the list is also starting from 0

>>> b = ['onion', 'potato', 'ginger', 'cucumber', 1, 3.1416]

>>> b[0]

'onion'

>>> b[1]

'potato'

>>> b[1:5]

['potato', 'ginger', 'cucumber', 1]

>>> b[:5]

['onion', 'potato', 'ginger', 'cucumber', 1]

>>> b[2:]

['ginger', 'cucumber', 1, 3.1416]

Same, isn’t it? Let’s check the data type of those items
.

>>> b = ['onion', 'potato', 'ginger', 'cucumber', 1, 3.1416]

>>> type(b[0])

<type 'str'>

>>> type(b[4])

<type 'int'>

>>> type(b[5]) <type 'float'>
Mixed data type’s list.

Update List

In python = is assignment operator. Now, we will use it to update our list. That means we will change the items of the index.

>>> b = ['onion', 'potato', 'ginger', 'cucumber', 1, 3.1416]

>>> b[0] = 'rice'

>>> b

['rice', 'potato', 'ginger', 'cucumber', 1, 3.1416]

>>> b[4] = 570

>>>
b

['rice', 'potato', 'ginger', 'cucumber', 570, 3.1416]

>>> b[5] = 23486.4678

>>> b

['rice', 'potato', 'ginger', 'cucumber', 570, 23486.4678]

You can ask if we need to change integer in the place of an integer. But no, we can change anything in the place of any data-type.

>>> b

['rice', 'potato', 'ginger', 'cucumber', 570, 3.1416]

>>> b[5] = 23486.4678

>>> b

['rice', 'potato', 'ginger', 'cucumber', 570, 23486.4678]

>>> b[2] = 343

>>> b

['rice', 'potato', 343, 'cucumber', 570, 23486.4678]

>>> b[4] = 'finger'

But if we want to insert a new item in the list? Will the previous method work?

>>> b

['rice', 'potato', 343, 'cucumber', 'finger', 23486.4678]

>>> b[6] = 'new'

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IndexError: list assignment index out of range

We wanted to assign an item ‘new’ in 6. But, python IndexError throwed and replied to us as it is not possible. We have append() function to solve this. We can insert any item in the list using this function.

>>> b

['rice', 'potato', 343, 'cucumber', 'finger', 23486.4678]

>>> b.append('new')

>>> b

['rice', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new'
]

The item ‘new’ has been added at last. If we insert anything with append(). Its alwasys be added at last. But if we want to add anything at the first index? Then we need to use insert() function. We can give the position where we want to add the index inside this function.

>>> b

['rice', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new']

>>> b.insert(1, 'python')

>>> b

['rice', 'python', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new']

We added a new item ‘python’ in the 1st index. But if we want to add more than one item inside any index? It is not possible with append(). It can only add only one item. We will use extend() function to insert more than one item. But you need to give all the item as a list inside extend() function. And they are not inserted into the index as a list. They will behave as a single item. Ex:

>>> b

['rice', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new']

>>> b.insert(1, 'python')

>>> b

['rice', 'python', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new']

>>> b.extend(['a', 'b', 'c'])

>>> b

['rice', 'python', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new', 'a','b', 'c']

We can also add list just like any simple addition
.

>>> b = ['rice', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new']

>>>
b

['rice', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new']

>>> b + ['a', 'b', 'c']

['rice', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new', 'a', 'b', 'c']

>>> b

['rice', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new']

>>> b = b + ['a', 'b', 'c']

>>> b

['rice', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new', 'a', 'b', 'c']

Remove Item

There are two ways to remove an item from the list. If we know the index number of the item, we can use del statement. And if we don’t know that, we will use remove() function.

>>> b = ['rice', 'python', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new', 'a', 'b', 'c']

>>> b

['rice', 'python', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new', 'a', 'b', 'c']

>>> del b[3]

>>> b

['rice', 'python', 'potato', 'cucumber', 'finger', 23486.4678, 'new', 'a', 'b', 'c']

>>> b.remove('python')

>>> b

Page
['rice', 'potato', 'cucumber', 'finger', 23486.4678, 'new', 'a', 'b', 'c'] But if we want to remove the last item from the index?

>>> b = ['rice', 'python', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new', 'a', 'b', 'c']

>>> b

['rice', 'python', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new', 'a', 'b', 'c']

>>> del b[-1]

>>>
b

['rice', 'python', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new', 'a', 'b']

If you don’t understand the del b[-1] statement, then listen carefully. It means the first one from the last. We can do this work more easily. For that we need to use a pop() function. It removes the last item and returns that->

>>> b

['rice', 'python', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new', 'a', 'b']

>
>> b.pop()

'b'

>>> b

['rice', 'python', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new', 'a']

>>> b.pop()

'a'

>>> b

['rice', 'python', 'potato', 343, 'cucumber', 'finger', 23486.4678, 'new']

>>> b.pop()

'new'

>>> b

['rice', 'python', 'potato', 343, 'cucumber', 'finger', 23486.4678]

Counting, Searching

If we want to know the amount of items on any list, we can take help from len() function.

>>> b

['rice', 'python', 'potato', 343, 'cucumber', 'finger', 23486.4678]

>>> len(b)

7

But if the question comes that how many ‘potato’ items is there inside that 7 items? We need to know how to use count() function to know the answer. If we give any item inside the function, we will know the answer

>>> b

['rice', 'python', 'potato', 343, 'cucumber', 'finger', 23486.4678]

>>> b.count('potato')

1

>>> c = ['potato', 'a', 'b', 'potato', 'potato']

>>> c.count('potato')

3

Reverse

If you want to reverse any list, we need to use the reverse() function

>>> b

['rice', 'python', 'potato', 343, 'cucumber', 'finger', 23486.4678]

>>> b.reverse()

>>> b

[23486.4678, 'finger', 'cucumber', 343, 'potato', 'python', 'rice']

Sorting

If we have only string or number then we can sort them very easily using sort() function.

>>> a = [8, 3, 5, 1, 6, 2, 9, 7, 0, 4]

>>> a

[8, 3, 5, 1, 6, 2, 9, 7, 0, 4]

>>> a.sort()

>>> a

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> b = ['b', 'c', 'a', ':', 'saha']

>>> b.sort()

>>> b

[':', 'a', 'b', 'c', 'saha']

Page

TUPLE

Python Tuple is used to store the sequence of immutable python objects. The tuple is like lists since the value of the items stored in the list can be changed whereas the tuple is immutable, and the value of the items stored in the tuple cannot be changed. Let’s get to know how to make tuples.

>>> a = ()

>>> a

()

>>> type(a) <class 'tuple'>

>>> a = ('onion', 'potato', 'ginger', 'cucumber')

>>> a

('onion', 'potato', 'ginger', 'cucumber')

>>> type(a) <class 'tuple'>

A=() is used to declare tuples. But inside this tuple there is no item. We have created another tuple

a = ('onion', 'potato', 'ginger', 'cucumber')

Where there are 4 items. There can be any data type in the tuple. We have used a string in this tuple. But we could use integer or float.

>>> b = ('onion', 'potato', 'ginger', 'cucumber', 1, 3.1416)

>>> b

('onion', 'potato', 'ginger', 'cucumber', 1, 3.1416)

>>> type(b) <type 'tuple'>

Tuples items can be mixed data type.

Access Item

Now, we will access the values of our tuple. Tuples index is also starting from 0
.

>>> b = ('onion', 'potato', 'ginger', 'cucumber', 1, 3.1416)

>>> b[0]

'onion'

>>> b[1]

'potato'

>>> b[1:5]

('potato', 'ginger', 'cucumber', 1)

>>> b[:5]

('onion', 'potato', 'ginger', 'cucumber', 1)

>>> b[2:]

('ginger', 'cucumber', 1, 3.1416)

Exactly the same, isn’t it? Let’s change the data types also.

>>> b = ('onion', 'potato', 'ginger', 'cucumber', 1, 3.1416)

>>> type(b[0])

<type 'str'>

>>> type(b[4])

<type 'int'>

>>> type(b[5]) <type 'float'>

Mixed data type tuple.

Tuple Changing, Extending and Appending

We all came to know before that tuples can not be changed, extend or append just like a list. Let’s confirm it.

>>> b

('onion', 'potato', 'ginger', 'cucumber', 1, 3.1416)

>>> b[0] = 'new'

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: 'tuple' object does not support item assignment

But python is throwing TypeError. That meansyou really cannot do like lists. But we can add a new tuple in an old tuple and make a new tuple.

>>>
b

('onion', 'potato', 'ginger', 'cucumber', 1, 3.1416)

>>> b + ('new',)

('onion', 'potato', 'ginger', 'cucumber', 1, 3.1416, 'new')

You cannot change tuple’s item.

Counting and Searching

We can again take help of len() function to know the amount of items in a tuple.

>>> b

('rice', 'python', 'potato', 343, 'cucumber', 'finger', 23486.4678)

>>> len(b)

7

But if the question comes that how many ‘potato’ items is there inside that 7 items? We need to know how to use count() function to know the answer. If we give any item inside the function, we will know the answer.

>>> b

('rice', 'python', 'potato', 343, 'cucumber', 'finger', 23486.4678)

>>> b.count('potato')

1

>>> c = ('potato', 'a', 'b', 'potato', 'potato')

>>> c.count('potato')

3

We need to practice more to be fluent in these topics.

SET

Mathematical Set

So, what does this have to do with mathematics? When we define a set, all we have to specify is a common characteristic. Who says we can't do so with numbers?

Set of even numbers: {..., -4, -2, 0, 2, 4, ...}

Set of odd numbers: {..., -3, -1, 1, 3, ...}

Set of prime numbers: {2, 3, 5, 7, 11, 13, 17, ...}

Positive multiples of 3 that are less than 10: {3, 6, 9}

And the list goes on. We can come up with all different types of sets.

There can also be sets of numbers that have no common property, they are just defined that way. For example:

{2, 3, 6, 828, 3839, 8827}

{4, 5, 6, 10, 21}

{2, 949, 48282, 42882959, 119484203}

Are all sets that I just randomly banged on my keyboard to produce

Sets in python

The set-in python can be defined as the unordered collection of various items enclosed within the curly braces. The elements of the set cannot be duplicate. The elements of the python set must be immutable.

Unlike other collections in python, there is no index attached to the elements of the set, i.e., we cannot directly access any element of the set
by the index. However, we can print them all together or we can get the list of elements by looping through the set.

Let’s make a set to make it clear.

>>> A = {'orange', 'banana', 'pear', 'apple'}

>>> A

{'apple', 'banana', 'pear', 'orange'}

>>> type(A) <class 'set'>

>>> A = set('orange', 'banana', 'pear', 'apple') Traceback (most recent call last):

File "<pyshell#3>", line 1, in <module> A = set('orange', 'banana', 'pear', 'apple')

TypeError: set expected at most 1 arguments, got 4

>>> A = set('abracadabra')

Page 44

Set

>>> A

{'b', 'r', 'c', 'a', 'd'}

>>> type(A) <class 'set'>

In the first statement we used {} symbols to make a set variable A. 3rd statement is used to check the type of A variable. We tried to make set by the help of set() function. But python is throwing TypeError. Because we can give only one thing inside the set. In a 5th statement we gave a string inside the set() function. In the 6th statement we can see that the string’s every character has been taken one time to build a set. Example:

>>> A = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

>>> A

{'banana', 'apple', 'pear', 'orange'}

We have given the ‘apple’ and ‘orange’ twice, but they are inside the set for a single time. Now, Let’s discuss the empty set ->

>>> A = set()

>>> type(A) <class 'set'>

>>>
A

set()

>>> A = {}

>>> A

{}

>>> type(A) <class 'dict'

We cannot create an empty set using {}. Then, we need set() function to make an empty set. This set() function is a class. But we still don’t know what class is. So, for understanding purpose we will suppose it as a machine or function

Access Item

Now, we will access the values and ingredients of the set.

>>> A = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

>>> A

{'pear', 'apple', 'orange', 'banana'}

>>> A[0]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: 'set' object does not support indexing

Damn! Python is throwing TypeError. In reality, set’s ingredients cannot be assigned by the index numbers..

Addition of the Ingredients

If we want, we can add new elements or ingredients in a set. For this we need to add() function. Whatever we will add into this function will be a set.

>>> A = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

>>> A

{'apple', 'orange', 'banana', 'pear'}

>>> A.add('pineapple')

>>> A

{'apple', 'orange', 'banana', 'pear', 'pineapple'
}

But, if we want to add several elements, we cannot use add(). We will use update() function for this job. We can give multiple values inside this function to add.

>>> A

{'apple', 'orange', 'banana', 'pear', 'pineapple'}

>>> A.update('berry', 'grape')

>>> A

{'r', 'apple', 'pineapple', 'b', 'orange', 'banana', 'y', 'g', 'a', 'p', 'e', 'pear'}

>>> A.update({'berry', 'grape'})

Page 46

Set

>>> A

{'r', 'apple', 'pineapple', 'b', 'orange', 'banana', 'y', 'g', 'a', 'p', 'berry','grape', 'e', 'pear'}

Discarding an element

Suppose we want to remove an element from set A. For this we need to use remove()

function. Example:

>>> A = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

>>> A

{'apple', 'orange', 'banana', 'pear'}

>>> A.remove('apple')

>>> A

{'orange', 'banana', 'pear'}

>>> A.remove('berry') Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'berry'

>>> A

{'orange', 'banana', 'pear'}

KeyError occurs if there is no item in the set on that name. If we don’t want this kind of error, we need to use discard() function. As an example
:

>>> A = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

>>> A

{'apple', 'orange', 'banana', 'pear'}

>>> A.discard('apple')

>>> A

{'orange', 'banana', 'pear'}

>>> A.discard('berry')

>>> A

{'orange', 'banana', 'pear'}

Suppose, we need only the first element from the set A. We want to remove it. For this job, we will take help of pop() function. This function removes the first element from a set and then returns it. Like,

>>> A = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

>>> A

{'pear', 'banana', 'apple', 'orange'}

>>> A.pop()

'pear'

>>> A.pop()

'banana'

>>> A.pop()

'apple'

If we want to remove all the elements from the set with a single statement, we will use the clear() function.

>>> A

{'r', 'apple', 'pineapple', 'b', 'orange', 'banana', 'y', 'g', 'a', 'p', 'berry', 'grape', 'e', 'pear'}

>>> A.clear()

>>> A

set()

Unio
n

Union of two sets means the creation of a new set, which will have the elements of both sets. A = {1, 2, 3, 4, 5} and B = {6, 7, 8} are two sets. So, the union of this two set will be C= {1,2,3,4,5,6,7,8,}. The same work if we want to do, we need to do it with the help of union() function. Example:

>>> A = {1, 2, 3, 4, 5}

>>> B = {6, 7, 8}

>>> A.union(B)

{1, 2, 3, 4, 5, 6, 7, 8}

Intersection

The & (intersection) operator is used to calculate the intersection of the two sets in python. The intersection of the two sets is given as the set of the elements that common in both sets.

Consider the following example.

>>> A = {1, 2, 3, 4, 5}

>>> B = {2, 3, 4, 5, 6, 7}

>>> A.intersection(B) {2, 3, 4, 5}

Difference

The difference of two sets can be calculated by using the subtraction (-) operator. The resulting set will be obtained by removing all the elements from set 1 that are present in set 2.

Consider the following example.

>>> A = {1, 2, 3, 4, 5, 6}

>>> B= {5, 6, 7, 8}

>>> A.difference(B) {1, 2, 3, 4}

DICTIONARY

Dictionary is the smartest data type in python. We can compare it with the list. There is some difference also. Dictionary is being declared with the {} symbol. Dictionary doesn’t have any Index. It uses a key. String, integer and tuples are used as the key. Every item in the dictionary is separated by comma (,) from each other. Every item has three part. First one is the key, the middle one is the : symbol as a separator and the last part will have the values. Every key of a dictionary will be unique. But the same values can be repeated.

>>> a = {}

>>> a

{}

>>> type(a) <class 'dict'>

>>> a = {'name' : 'Dipta Saha', 'nickname' : 'Saha', 'email' : 'diptasaha.lpu.cse@outlook.com', 'phone' : '918697771412'}

>>> a

{'name': 'Dipta Saha', 'nickname': 'Saha', 'email':

'diptasaha.lpu.cse@outlook.com', 'phone': '918697771412'}

>>> type(a) <class 'dict'> a = {}

>>> a = dict()

>>> a

{}

>>> type(a) <class 'dict'>

Access Item

Dictionaries item can be accessed just like list. Difference is we use key in dictionary instead of the index of the lists inside [] symbol. Let’s see an example:

>>> a = {'name' : 'Dipta Saha', 'nickname' : 'Saha', 'email' : 'diptasaha.lpu.cse@outlook.com', 'phone' : '918697771412'}

>>>
a

{'name': 'Dipta Saha', 'nickname': 'Saha', 'email':

'diptasaha.lpu.cse@outlook.com', 'phone': '918697771412'}

>>> a['name']

'Dipta Saha'

>>> a['nickname']

'Saha'

>>> a['email']

'diptasaha.lpu.cse@outlook.com'

>>> a['phone']

'918697771412'

Updated Dictionary

Updating inside a dictionary is the easiest part. Just assigned the new data inside the key.

Like:

>>> a = {'name' : 'Dipta Saha', 'nickname' : 'Saha', 'email' : 'diptasaha.lpu.cse@outlook.com', 'phone' : '918697771412'}

>>> a

{'name': 'Dipta Saha', 'nickname': 'Saha', 'email':

'diptasaha.lpu.cse@outlook.com', 'phone': '918697771412'}

>>> a['name'] = 'Dipta Saha'

>>> a

{'name': 'Dipta Saha', 'nickname': 'Saha', 'email':

'diptasaha.lpu.cse@outlook.com', 'phone': '918697771412'}

For adding a new item, just add a new key value pair. Consider this example:

>>> a = {'name' : 'Dipta Saha', 'nickname' : 'Saha', 'email' : 'diptasaha.lpu.cse@outlook.com', 'phone' : '918697771412'}

>>> a

{'name': 'Dipta Saha', 'nickname': 'Saha', 'email':

'diptasaha.lpu.cse@outlook.com', 'phone': '918697771412'}

>>> a['hometown'] = 'Khulna
'

>>> a

{'name': 'Dipta Saha', 'nickname': 'Saha', 'email':

'diptasaha.lpu.cse@outlook.com', 'hometown': 'Khulna', 'phone': '918697771412'}

We use update() function to add one dictionary all the item with another one. Which doctionary we want to, we just need to put into the other dictionary. Simple.

>>> a

{'name': 'Dipta Saha', 'nickname': 'Saha', 'email':

'diptasaha.lpu.cse@outlook.com', 'phone': '918697771412'}

>>> b = {'hometown' : 'Khulna', 'fav_poet' : 'Nazrul'}

>>> a.update(b)

>>> a

{'name': 'Dipta Saha', 'fav_poet': 'Nazrul', 'nickname': 'Saha',

'email': 'diptasaha.lpu.cse@outlook.com', 'hometown': 'Khulna', 'phone': '918697771412'} I hope you understood well.

Removing an item (Dictionary)

To delete an item from a dictionary we use del statement.

>>> a

{'name': 'Dipta Saha', 'nickname': 'Saha', 'email':

'diptasaha.lpu.cse@outlook.com', 'hometown': 'Khulna', 'phone': '918697771412'}

>>> del a['phone']

>>> a

{'name': 'Dipta Saha', 'nickname': 'Saha', 'email':

'diptasaha.lpu.cse@outlook.com', 'hometown': 'Khulna'}

To clear all the items from a dictionary with a single statement, we will use a clear() function.

>>>
a

{'name': 'Dipta Saha', 'nickname': 'Saha', 'email': 'diptasaha.lpu.cse@outlook.com', 'hometown': 'Khulna'} >>> a.clear()

>>> a

{}

Or if we want to delete whole the dictionary, we will use del statement.

>>> a = {'name' : 'Dipta Saha', 'nickname' : 'Saha', 'email' : 'diptasaha.lpu.cse@outlook.com', 'phone' : '918697771412'}

>>> a

{'name': 'Dipta Saha', 'nickname': 'Saha', 'email':

'diptasaha.lpu.cse@outlook.com', 'phone': '918697771412'}

>>> del a

>>> a

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'a' is not defined

For removing whole, the dictionary it is showing NameError. It wants to say that there is no dictionary variable named as a.

Applying some functions (Method)

Copy()

This function copies all a dictionary.

>>> a = {'name' : 'Dipta Saha', 'nickname' : 'Saha', 'email' : 'diptasaha.lpu.cse@outlook.com', 'phone' : '918697771412'}

>>> a

{'name': 'Dipta Saha', 'nickname': 'Saha', 'email':

'diptasaha.lpu.cse@outlook.com', 'phone': '918697771412'}

>>> a.copy()

{'name': 'Dipta Saha', 'nickname': 'Saha', 'email':

'diptasaha.lpu.cse@outlook.com', 'phone': '918697771412'
}

Get(key, default=None)

This function is used to search any key from a string to get the value. If the key is not in the dictionary, then it will return a default value. In the primary level this value is none means nothing. But if we want we can change it.

>>> a = {'name' : 'Dipta Saha', 'nickname' : 'Saha', 'email' : 'diptasaha.lpu.cse@outlook.com', 'phone' : '918697771412'}

>>> a

{'name': 'Dipta Saha', 'nickname': 'Saha', 'email':

'diptasaha.lpu.cse@outlook.com', 'phone': '918697771412'}

>>> a.get('name') 'Dipta Saha'

>>> a.get('home')

>>> a.get('home', 'kicu nai') 'kicu nai'

Has_key(key)

We use this function to examine if there are some specific key in a dictionary. It will return ‘true’ if it finds the key, or the result will be ‘false’. But the sad news is that it has been removed. A win can do this work with the help of ‘in’.

>>> a = {'name' : 'Dipta Saha', 'nickname' : 'Saha', 'email' : 'diptasaha.lpu.cse@outlook.com', 'phone' : '918697771412'}

>>> 'name' in a

True

>>> 'home' in a False
items()

This function returns a dictionary as a list. Every item inside a list reacts as a tuple. In every tuple, there is an index at 0 and value at 1.

>>> a = {'name' : 'Dipta Saha', 'nickname' : 'Saha', 'email' : 'diptasaha.lpu.cse@outlook.com', 'phone' : '918697771412'}

>>> a

{'name': 'Dipta Saha', 'nickname': 'Saha', 'email':

'diptasaha.lpu.cse@outlook.com', 'phone': '918697771412'
}

>>> a.items()

dict_items([('name', 'Dipta Saha'), ('nickname', 'Saha'),

('email', 'diptasaha.lpu.cse@outlook.com'), ('phone', '918697771412')])

keys()

This function returns every key list of a dictionary.

>>> a

{'name': 'Dipta Saha', 'nickname': 'Saha', 'email':

'diptasaha.lpu.cse@outlook.com', 'phone': '918697771412'}

>>> a.keys()

dict_keys(['name', 'nickname', 'email', 'phone'])

Values()

This function returns every value of a dictionary.

>>> a

{'name': 'Dipta Saha', 'nickname': 'Saha', 'email': 'diptasaha.lpu.cse@outlook.com', 'phone': '918697771412'} >>> a.values()

dict_values(['Dipta Saha', 'Saha', 'diptasaha.lpu.cse@outlook.com', '918697771412'])

Enough up to this, no you need to practice all the things we have discussed above.

CONDITIONAL LOGIC

Yes' and 'no' are two oldest and smallest. But these two things are the most to think. – Pythagoras

Conditional logic is very important in any programming language. In fact, the conditional logic of computer science is the basis of all things. Not only the computer, but the whole world is also running on conditional logic. We sometimes say, 'if the result is good, then we will go to London'. There is a point here. We'll go to London only when our results are good.

Let's now calculate the sentence from the point of view of programming. 'Result is good' This is logical expression or condition and 'going to London' is the action. The condition needs to be true for the action to take effect. And the condition will be true only when the result is good.

In Python we will get three conditional statements (loops are out of the calculation for the time being). Each has different meanings and jobs. Let's take a look

if: If this is true, then do that.

elif: If the condition is not true, it's true, but do that. Elif will always come after if. And if only its conditions are not true, then elif's condition will be able to execute.

Else: If none is true, then do that. else and elif will come later after if (actually at the end of all).

If Statemen
t

Let's think of a problem. We will assign 5 to a variable. Now, if the value of a variable is smaller than 10, then print a is less than 10 on the screen. How can it be done? Hmm, conditional logic should be used here.

>>> a = 5

>>> a

5

>>> if a < 10:

... print('a is less than 10.')

File "<stdin>", line 2

print('a is less than 10.')

^

IndentationError: expected an indented block

We wrote everything fairly well. But still Python has thrown an error. This is IndentationError. Indentation is mandatory in Python. So, whenever there is no indentation, then Python has such an error. Indentation After some special statements, the code is moved to the right, so that the text can be understood to include which block. In simple words, indentation is arranged by writing code. Python indentation can be done in many ways. But the standard is, indent code by pressing four spaces. However, if we want, we can work by pressing two or three spaces. Just keep in mind, everywhere the code is indented by pressing the same number of space. Oh, the code can be indented by pressing the tab. So let us indent code in our top program.

>>> if a < 10:

... print('a is less than 10.')

...

a is less than 10.

If … else Statemen
t

But there is a problem in the program above. If a is not smaller than 10, but no output will be shown. Do not believe? It is only possible to see the code.

>>> a = 15

>>> if a < 10:

... print('a is less than 10.')

Really, right? We did not get any output. This is because we only told the action to be true of the condition. But for some reason the condition is false, but the action will not tell. If I wanted to tell, then that action would have worked.

Let's think of a new problem. We will assign 5 to a variable. Now, if the value of a variable is smaller than 10, then print the int the screen that a is a less than 10. And if a is greater than 10 then we will print a is greater than 10. How can it be done? we have to try together!

>>> a = 5

>>> if a < 10:

... print('a is less than 10.')

... else:

... print('a is greater than 10.')

...

a is less than 10.

>>> a = 15

>>> if a < 10:

... print('a is less than 10.')

... else:

... print('a is greater than 10.')

...

a is greater than 10.

If...elif...else Statement

Let's think of a complex problem. We will take input from a user of a variable value. Now, if the value of a variable is 5 then we will print a is
equal to 5. On the screen. If the value of a is less than 5 then we will print a is less than 5. And if a is greater than 10 then we will print a is greater than 10. It is more complex than the previous problems. But we can.

At the beginning I said, in the first chapters we will write the code in Python Interactive Shell and then write the code from Python IDLE to the next chapters. Now that time is present. From now on we will start writing code in Python IDLE.

a = int(input())

if a == 5:

print('a is equal to 5.')

elif a < 5:

print('a is less than 5.')

elif a > 5 and a < 10:

print('a is inbetween 5 and 10.')

else:

print('a is greater than 10.')

Output:

5

a is equal to 5.

2

a is less than 5.

17

a is greater than 10.

Problem: Now
, we will take input from the user. Now, if the variable is 5 then ‘a is equal to 5’ will be printed. If a becomes smaller than 5 or greater than 10, then ‘a is smaller than 5’ and ‘a is greater than 10’ will be printed respectively.

Input:

a = int(input()
)

if a == 5:

print('a is equal to 5.')

elif a < 5:

print('a is less than 5.')

elif a > 5 and a < 10:

print('a is inbetween 5 and 10.')

else:

print('a is greater than 10.')

Output:

5

a is equal to 5.

2

a is less than 5.

17

a is greater than 10.

Nested if Syntax:

if(condition):

#Statements to execute if the condition is true

if(condition):

#Statements to execute if condition is true

#end of nested if

#end of if

The above syntax clearly says that the if block will contain another if block in it and so on.

If a block can contain ‘n' number of if block inside it.

Problem: User will give an input a. If the value is less than 10, then we will try to find if the value is even or not. If even we print less, yes, else we will print less, no. And If the value is greater than 10, then we will try to find if the value is dividable by 3. Then we will print if dividable greater, yes and if not then greater, no.

a = int(input())

if a < 10
:

if (a % 2) == 0:

print('less, yes')

else:

print('less, no')

else:

if (a % 3) == 0:

print('greater, yes')

else:

print('greater, no')

Output:

6

less, yes

12

greater, yes

5

less, no

17

greater, no

In python every non-zero and non-null value are true and every zero and a null value is false. Cosider the following example ->

>>> a = 5

>>> if a:

... print(True)

...else:

... print(False)

...

True

>>> a = 0

>>> if a:

... print(True)

... else:

... print(False)

...

False

>>> a = not Non
e

>>> if a:

... print(True)

... else:

... print(False)

...

True

>>> a = None

>>> if a:

... print(True)

... else:

... print(False)

...

False

Let’s see the following program to practice.

>>> a = 1

>>> b = 1

>>> b is a True

>>> a = 6000

>>> b = 6000

>>> b is a False

Let’s find out this strange problem solution on your own. Best of Luck

Conditional Logic - Problem Solving

We’ll now solve some problem using conditional logic. A problem can be solved in different ways. So, if you can find a solution in a different. Problem 1:

User will input
a number. Print if the number is positive or negative. If zero, print
Zero.d easiest way. Then, I will say ‘Good Job’.

print('Please, input the number:')

number = float(input())

if number > 0
:

print('Positive')

elif number < 0:

print('Negative')

else:

print('Zero')

Output:

0

Zero

2

Positive

-10

Negative

Problem 2:

User will input an integer number. Find if the number is even or odd.

print('Please, input the number:')

number = int(input())

if number % 2 == 0:

print('Even')

else:

print('Odd')

Output:

0

Even

14

Even

17

Odd

Problem 3:

User will give an input of a character. Print if the character is uppercase or lowercase. If the character is not from the alphabet print Nothing
.

print('Please, input the character:')

character = input()

if character >= 'a' and character <= 'z' :

print('Lower Case')

elif character >= 'A' and character <= 'Z' :

print('Upper Case')

else:

print('Nothing')

Output:

g

Lower Case

F

Upper Case

6

Nothing

Problem 4:

print('Please, input the character:')

character = input()

if character >= 'a' and character <= 'z' or character >= 'A' and character <= 'z':

if character in 'aeiouAEIOU':

print('Vowel')

else:

print('Consonant')

else:

print('Nothing')

Output:

a

Vowel

A

Vowel

z

Consonant

t

Consonant

9

Nothing

LOOP

Python provides a while loop and a for in loop, both of which have a more sophisticated syntax than the basics.

while Loops:

While the loop has two parts: the logical expression or the conditon and action. Only when the condition is true, the action part begins to execute only, and the action is being executed until the condition is true.

While the syntax of the loop is similar to it. After the condition of the colon: the sign is to give.

Indentation is mandatory in the action block. Let's review the example again:

n = 1

while n <= 10:

print(n)

n = n+1

We needed to print from 1 to 10. At first we assigned the value of n variable to 1. Then I started writing the while loop. As long as the condition is true, ie the value of n is equal to or equal to 10, the action will be executed, meaning the value of n will be printed. And after each print, the value of n will increase by 1. When the loop rotates for the first time, the value of n will be 1, so 1 will print. Then the value of n will be 1 to 2. 2 is less than 10, so the loop will rotate again, print the value of n 2, the value of n will be increased to 3 ... so that the value of n times is 10 times higher. 10 is equal to 10, so again the action of the loop will start getting executed. Now the print will be 10, then the value of n will increase to 11. 11, not equal to 10 or smaller. Then the condition will be
false, so that the loop will not rotate, that means the action will not be executed.

Let's think of a new problem. In our childhood we used to add century. Centuries have been added to add numbers from 1 to 100. Means to find out 1 + 2 + 3 + 4 + ... + 100 =? . Using the while loop, we will now do the solution.

n = 1

temp = 0

while n <= 100:

temp = temp + n

n = n + 1

print(temp)

Output:

5050

For loops:

With for loop, we can iterate these sequential items. Iterate means to read the item by item. The person who is to be iterated is called the Iterator object. List, tuple, set, dictionary, all can be iterated. In a chapter about the iterator we will get the details. For now, this little knowledge is enough.

The basic syntax is:

for var in list:

statement-1

statement-2

statement-N

Where,

1. var: var reads each element from the list starting from the first element.

2. list: the list is a Python list i.e. a list or a strin
g

Example:

a = ['onion', 'potato', 'ginger', 'cucumber']

print(type(a))

for an item in a:

print(item)

Output:

<class 'list'>

onion

potato

ginger

Cucumber

Here we have iterated a list, we read all the items of the list . for an item in a statement, once the values of a loop rotate, one has been assigned to item variables. Then we print the item.

Tactile, set, and decryption, the same way as the list

Loop Control Statement:

Loops always circles around. So, to control this circling we need a loop control statement.

Python has three loop control statements: break, continue, pass

Break:

The loop stops at the point where it finds this break statement. Ex:

for the number in range(1, 11):

if number == 5:

break

print(number)

Output:

1

2

3

4

Continue:..

The continue statement skips the remaining lines of code inside the loop and start with the next iteration. It is mainly used for a condition inside the loop so that we can skip some specific code for a condition. Ex:

for number in range(1. 11):

if number == 5:

continue

print(number)

Output:

1

2

3

4

5

6

7

8

9

10

When the number became 5, then the continue statement worked. So, it didn’t print the number.

Pass:

Pass statement is a null operation. It happens nothing when it executes.

for number in range(1, 11):

if number == 5:

pass

print(number)

Output:

1

2

3

4

5

6

7

8

9

1
0

Else with the loop:

When we use else with the while loop, when the expression of while loop becomes fall only then else will be executed

n = 1

while n <= 10:

print(n)

n = n + 1

else:

print('The loop is over.')

Output:

1

2

3

4

5

6

7

8

9

10

The loop is over
.

If we use else statement with the for loop, the else will be executed when the for-loop ends.

for n in range(0, 11):

print(n)

n = n + 1

else:

print('The loop is over.')

Output:

0

1

2

3

4

5

6

7

8

9

10.

The loop is over.

Infinite loop:

There are some loops available, if we run it, it’ll never stop. Ex:

i = 1

while i > 0:

i += 1

print(i)

Run it to know it better.

COMPREHENSION

There are a lot of systems in python to make iterator. In pythonic language it calls as comprehension. It has three parts.

1. Output expression

2. Input expression

3. Conditional logic (optional)

List Comprehension:

Consider this example:

>>> my_list = [i**2 for i in range(20) if i % 2 == 0]

>>> my_list

[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]

In this whole code we just need to understand ‘[i for i in range(20) if i % 2 == 0]’ this part.

Let’s divide it into some parts for understanding purpose.

Output expression: I**2

Input expression: for I in range(20)

Conditional logic: if i%2 == 0

Set comprehension:

Let's see an example of set comprehension:

>>> a_list = ['Dipta', 'Saha', 'Avek', 'a', 'b', 'c']

>>> my_set = {i for i in a_list if len(i) > 1}

>>> my_set

{'Avek', 'Saha', 'Dipta'}

Dictionary Comprehension:

Let's see an example of Dictionary comprehension:

>>> a_list = ['name', 'country', 'career']

>>> b_list = ['Dipta', 'Bangladesh', 'TeleTalk']

>>> my_dict = {i : j for i, j in zip(a_list, b_list)}

>>> my_dic
t

{'career': 'TeleTalk', 'country': 'Bangladesh', 'name': 'Dipta'} In here we used zip() function to iterate 2 list.

In this whole code we just need to understand ‘[i for i in range(20) if i % 2 == 0]’ this part.

Let’s divide it into some parts for understanding purpose.

Output expression: I**2

Input expression: for I in range(20)

Conditional logic: if i%2 == 0

Set comprehension:

Let's see an example of set comprehension:

>>> a_list = ['Dipta', 'Saha', 'Avek', 'a', 'b', 'c']

>>> my_set = {i for i in a_list if len(i) > 1}

>>> my_set

{'Avek', 'Saha', 'Dipta'}

Dictionary Comprehension:

Let's see an example of Dictionary comprehension:

>>> a_list = ['name', 'country', 'career']

>>> b_list = ['Dipta', 'Bangladesh', 'TeleTalk']

>>> my_dict = {i : j for i, j in zip(a_list, b_list)}

>>> my_dict

{'career': 'TeleTalk', 'country': 'Bangladesh', 'name': 'Dipta'} In here we used zip() function to iterate 2 list.

FUNCTION

We may do a lot of works using python, but it’ll return not more than one data. There are two kinds of function. 1. build -in 2. user-defined. The function we have used until now is a build-in function. Like, print(), input(), pop() . But the main power of any programing language is a user-defined function. This is the function, which is created by us.

Function creation and calling:

There are some rules to create any function.

· Function block will start from def. There will be a space between def and function name. Function's name will be just like a variable name. But you can write function name starting with (_) underscore.

· There will be a () first bracket couple with the function name. More than one parameter and arguments will be separated by a comma inside the brackets. There will be a colon (: ) after the bracket.

· All the statement of the function will be intended. In the first statement you can put a comment. There can be a small description of the function. It is not compulsory.

· The function will end with the return keyword. For returning any data, you should give a space after return then the data. EX:

def function(parameter):

#function

.............................

.............................

return anything

Function

Function parameter and argument
s

The parameter and arguments we are using in function, have four part.

Required argument

Example:

def add(a, b, c): return a+b+c temp = add(1, 2) print(temp)

Output:

Traceback (most recent call last):

File "/home/ugcoder/Desktop/test.py", line 3, in <module> temp = add(1, 2)TypeError: add() missing 1 required positional argument: 'c'

Python is throwing a TypeError. Because, the required argument is missing. Our function had use three parameters, but we used two. Here the third one is the required argument.

Keyword argument

Example:

def add(a, b, c):

return a+b+c

temp = add(b=2, c=3, a=1)

print(temp)

Output:

Now, we passed the value like, b=2, c=3 and a =1. Not positionally, we just wrote the value of the variables. We have used the keyword argument here. When we are doing a lot of arguments, we need not maintain one by one.

Default argument

Example
:

def add(a, b, c=3):

return a+b+c

temp = add(1, 2)

print(temp)

Output:

In the third line we have used two value as a parameter. But the function used three parameters. But why isn’t it throwing an error? Because we used the default value as 3.

Variable length argument

Now, we need to create such a function that will have a lot of arguments and will return the addition.

def add(*args):

print(type(args))

tmp = 0

for number in args:

tmp = tmp + number

return tmp

temp = add(1, 2, 22, 12, 17, 21, 98)

print(temp)

Output:

<class 'tuple'>

173

In function before any parameter, if you give a * symbol, that can hold unlimited value. You should know, that parameter creates a tuple to hold all the values. We can access all the value by using a ‘for loop’ after it. It is called, non- keyword variable length argument. If we wanted to pass the keyword argument, we would add two asterisk symbol (*) before the parameter. It is called as keyworded variable length argument. This parameter creates a dictionary to hold the values. Example:

def add(**kwargs)
:

print(type(kwargs))

tmp = 0

for key in kwargs:

tmp = tmp + kwargs[key]

return tmp

temp = add(a=1, b=2, c=3, d=4)

print(temp)

Output:

<class 'dict'>

10

All the function declared inside any function is called a local variable. They can access that function only. And the variables declared outside function is called a global variable. These can be accessed from anywhere of the program.

Recursion

If a function is called by itself, that is known as recursion. And that function is known as a recursive function. It means it calls itself inside the function.

def counter(num):

print(num)

num += 1

counter(num)

counter(1)

Here counter took 1 as a function parameter. Then increased the value by 1 by printing 1.

And it called itself and now it passed the value 2, which is increased as a parameter.

Now, we will write a program to calculate factorial program using python.

print('Please input your number:')

number = int(input()
)

temp = number

while number > 1:

number -= 1

temp = temp*number

if temp == 0:

print(1)

else:

print(temp)

Output:

0

1

5

120

We wrote a program by using a loop to find out recursion. Now, we will do the same work using a recursive function.

def factorial(number):

if number == 0:

return 1

else:

return number * factorial(number - 1)

print('Please input your number:')

number = int(input())

print(factorial(number))

Output:

0

1

5

120

Here, factorial() is a recursive function. Because, we called it again in its return part.

The function of one line (lambda
)

We write the argument by giving space after lambda. After that we need to use a colon (: ) to give arithmetic expression. For giving a name to the function, we can assign a variable. Lambda is used in the operator to write a function in a single line in python.

sum = lambda a, b : a + b

print(sum(10, 20))

print((lambda a, b : a + b)(10, 20))

Output:

30

30

This function can be called as anonymous function. Example:

def my_function(func, arg1, arg2):

return func(arg1, arg2)

print(my_function(lambda a, b : a + b, 10, 20))

Output:

30

Here, my_function() took a function and two value as an argument. We, as a function, passed one lambda function and as a value 10, 20. Then, my_function() returned lambda function. The values are used as the argument of the lambda function.

map()

This is a build-in function. It takes two arguments to work. 1.function and 2. iterator object. It actually applies function, which takes arguments on every item of the iterator.

Example:

my_list = [2, 3, 4, 5, 6, 7]

def square(x):

return x *
x

new_list = map(square, my_list)

print(new_list)

print(list(new_list))

Output:

<map object at 0x7f37c8e7df28>

[4, 9, 16, 25, 36, 49]

my_list = [2, 3, 4, 5, 6, 7]

def square(x):

return x * x

new_list = map(square, my_list)

print(new_list)

print(list(new_list))

Output:

<map object at 0x7f37c8e7df28>

[4, 9, 16, 25, 36, 49]

Here, we applied a square() function on every item of my list. After that we casted it and printed as a list. We just applied a user defined function. Now we will play with build-in function.

>>> a, b = map(int, input().split()) 10 20

>>> type(a)

<class 'int'>

>>> type(b) <class 'int'>

>>> a + b

30

Hope you understood.

filter()

It is almost like the map function. But this functions duty is filtering. It applies function, which takes arguments on every item of the iterator. And it will reject that item from the iterator object, for which the program returned False. Consider this example:

my_list = [2, 3, 4, 5, 6, 7]

def is_even(x):

if (x % 2) == 0
:

return True

else:

return False

new_list = filter(is_even, my_list)

print(new_list)

print(list(new_list))

Output:

<filter object at 0x7f5d35eecef0>

[2, 4, 6]

Here, is_even() function is applied on every item of my_list(). A map object is stored inside the my_list() function. After that we casted it as a list and then printed it.

Up to this, it was function. Now, we need a lot of practice at home by ourself.

FILE

A file is some information or data which stays in the computer storage devices. You already know about different kinds of file, like your music files, video files, text files. Python gives you easy ways to manipulate these files. Generally, we divide files in two categories, text file and binary file.

Here, we will learn three things. File opening, reading that and to write a file our self.

Firstly, we will learn how to open a file. Open() function is used to open a file. There are three parameters which are used by this function.

1. Name of the file:
If our script and the file lie in the same directory, then only the name of the file will be taken as a string. If the file is in a different directory, then the whole path will be a string.

2. Access mode:
The second parameter is the access mode. We can open the file for several purposes by it. The mode to open the files are.

r :

Open a file for reading Mode only. The file pointer is placed at the beginning / front of the file. This is a default mode.

rb :

Open a file for reading Mode only in the binary format. The file pointer is placed at the beginning / front of the file. This is a default mode.

r+ :

Open a file for both reading and writing mode. The file pointer is placed at the beginning / front of the file
.

rb+ :

Open a file for both reading and writing mode in the binary format. The file pointer is placed at the beginning / front of the file.

w :

Open a file for writing mode only.if the file exists,Overwrites the file. If the file does not exist, creates a new file for writing.

wb :

Open a file for writing mode only in binary format. if the file exists,Overwrites the file. If the file does not exist, creates a new file for writing.

w+ :

Open a file for both writing and reading mode. if the file exists,Overwrites the existing file .

If the file does not exist, creates a new file for reading and writing.

wb+ :

Open a file for both writing and reading mode in binary format.if the file exists, Overwrites the existing file . If the file does not exist, creates a new file for reading and writing.

a :

Open a file for appending mode. if the file exists,The file pointer is at the end of the file. That is called, the file is in the append mode. If the file does not exist, it creates a new file for writing.

ab
:

Open a file for appending mode in binary format. if the file exists,The file pointer is at the end of the file. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

a+ :

Open a file for both appending and reading mode.if the file exists,The file pointer is at the end of the file . The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

ab+ :

Open a file for both appending and reading in binary format. if the file exists,The file pointer is at the end of the file. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing

3 . Buffering:
Third one is buffering. This is a high-term subject. We will know about it later.

Examples:.

my_file = open('test.txt', 'r')

content = my_file.read()

print(content)

my_file.close()

Output:

The name of my country is Bangladesh.

Here, at the first line, we opened the file in reading mode. At the second line, using read() function (method) we read the file, we assigned the data content variable

.

ERROR HANDLING

Now we will see some standard exception and when they are raised.

StopIteration

It raises when the next() method doesn’t point any object.

KeyError

It raises, in the dictionary, when the specified key is not found.

ZeroDivisionError

It raises, when we try to divide any value by Zero.

ImportError

It raises when an import statement fails.

NameError

It raises when an identifier is not found in the local or global namespace.

UnboundLocalError

It raises when trying to access a local variable in a function or method but no value has been assigned to it.

IndentationError

It raises when indentation is not specified properly.

KeyboardInterrupt

It raises when a user interrupts any program execution by pressing Ctrl+c.

IndexError

It raises when in a sequence, the index cannot be found
.

RuntimeError

It raises when a generated error does not fall into any category.

TypeError

It raises when an operation or function is attempted that is invalid for the specified data type.

SyntaxError

It raises when there is an error in Python syntax.

ValueError

It raises when the built- in function for a data type has the valid type of arguments, but the arguments have invalid values specified.

SystemError

It raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.

There are a lot of errors like these. We have shown the most common raised errors

What is an exception?

In a word, Exception is an incident. It raises at the time of running the program, if any problem appears. We will run the last program again, but after deleting the test.txt file from that place.

Example:

with open('test.txt', 'r') as my_file:

content = my_file.read()

print(content)

Output:

Traceback (most recent call last)
:

File "/home/ugcoder/Desktop/test.py", line 1, in <module> with open('test.txt', 'r') as my_file:

FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

Here, for not finding the text.txt file, python throwed the FileNotFoundError. Then the execution of the program has ended. That is why the problem which has no error after that statement has not executed also.

For this handling this kind of exception, we use exception handling.

try ... except

Now we will try to figure out our previous problem.

try:

with open('test.txt', 'r') as my_file:

content = my_file.read()

print(content)

except:

print('The file does not exist.')

print('Made by Dipta.')

Output:

The file does not exist.

Made by Dipta.

Didn’t we handle the problem so easily? Chill.

Raise Expression:

try:

raise NameError('Hey! It is a custom error message.')

except NameError as e:

print(e)

Output:

Hey! It is a custom error message
.

To raise expression, we use the raise statement. After raise we give the name of any build-in expression and add text inside the bracket after it to pass message string.

CLASS, OBJECT AND METHOD

The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death. - Guido van Rossum

We know from the beginning that python is an Object-Oriented Programming Language. Now, we will know why ->

What is a class?

A class is a code template for creating objects. Objects have member variables and have behavior associated with them. In python a class is created by the keyword class. An object is created using the constructor of the class. This object will then be called the instance of the class.

Example:

class WaltonUsta:

"""Our new car class"""

def driving(self):

run_the_car

def music(self):

run_the_music

def fuel(self):

load_the_fuel

def horn(self):

make_sound_pollution

Here, WaltonUsta is a class. And driving(), music(), fuel() and horn() these are the functions.

Self

·

Self is a conventional name

.

·

Self is a reference of an instance. At the time of declaration of instance, we use self as a reference. An instance variable is unique in every instance, where the class variable is shared in every instance.

What is Object?

Whatever we can see and feel in the real world are the objects. In python, the variables we used in simple programming, are called as an object when we use it in Object oriented programming.

our_car = WaltonUsta()

her_car = WaltonUsta()

your_car = WaltonUsta()

Here, our_car, her_car, your_car are the objects. WaltonUsta() is the object of the class.

And every object can access all the functions of the class.

What is Method?

A method is a function that takes a class instance as its first parameter. Methods are members of classes.

class C:

def method(self, possibly, other, arguments):

pass # do something here.

Not cleared? Let’s consider a good example:

We will make a class for a calculator. There will be methods of plus, minus, multiplication and division.

class Calculator:

"""Do addition, subtraction, multiplication and division."""

def addition(self, a, b):

return a+b

def subtraction(self, a, b):

return a-b

def multiplication(self, a, b):

return a*
b

def division(self, a, b):

try:

return a/b

except ZeroDivisionError:

return 'It is impossible to divide by zero.'

my_calculator = Calculator()

temp = my_calculator.addition(12, 78)

print(temp)

temp = my_calculator.subtraction(50, 23)

print(temp)

temp = my_calculator.multiplication(9, 19)

print(temp)

temp = my_calculator.division(400, 5)

print(temp)

temp = my_calculator.division(43, 0)

print(temp)

Output:

90

27

171

80.0

It is impossible to divide by zero.

When we want to pass value inside a class and we want to use that value inside the method, then at the start of the class we use __init__ as a method. In the programing language, it is known as class constructor.

Another Example:

class Calculator:

"""Do addition, subtraction, multiplication and division."""

def __init__(self, a, b):

self.a = a

self.b = b

def addition(self):

return self.a + self.
b

def subtraction(self):

return self.a - self.b

def multiplication(self):

return self.a * self.b

def division(self):

try:

return self.a / self.b

except ZeroDivisionError:

return 'It is impossible to divide by zero.'

my_calculator = Calculator(45, 3)

temp = my_calculator.addition()

print(temp)

temp = my_calculator.subtraction()

print(temp)

temp = my_calculator.multiplication()

print(temp)

temp = my_calculator.division()

print(temp)

Output:

48

42

135

15.0Page

INHERITANCE

Classes can inherit the functionality of other classes. If an object is created using a class that inherits from a superclass, the object will contain the methods of both the class and the superclass. The same holds true for variables of both the superclass and the class that inherits from the super class.

Python supports inheritance from multiple classes, unlike other popular programming languages.

We define a basic class named User:

class User:

name = ""

def __init__(self, name):

self.name = name

def printName(self):

print("Name = " + self.name)

brian = User("brian")

brian.printName()

This creates one instance called brian which outputs its given name. We create another class called Programmer.

class Programmer(User):

def __init__(self, name):

self.name = name

def doPython(self):

print("Programming Python")

This looks very much like a standard class except than User is given in the parameters.

This means all functionality of the class User is accessible in the Programmer class.

Inheritance example
:

full example of python inheritance:

class User:

name = ""

def __init__(self, name):

self.name = name

def printName(self):

print("Name = " + self.name)

class Programmer(User):

def __init__(self, name):

self.name = name

def doPython(self):

print("Programming Python")

brian = User("brian")

brian.printName()

diana = Programmer("Diana")

diana.printName()

diana.doPython()

Output:

Name = brian

Name = Diana

Programming Python

Brian is an instance of User and can only access the method printName. Diana is an instance of a Programmer, a class with an inheritance from User, and can access both the methods in Programmer and User.

Method Overriding

This is a wonderful thing. In child class, we override the methods of the parent class.

Example:

class Calculator:

"""Do addition, subtraction, multiplication and division."""

def addition(self, a, b):

return a + b

def subtraction(self, a, b)
:

return a - b

def multiplication(self, a, b):

return a * b

def division(self, a, b):

try:

return a / b

except ZeroDivisionError:

return 'It is impossible to divide by zero.'

class SuperCalculator(Calculator):

"""Do addition, subtraction, multiplication, division, square and cube."""

def addition(self, a, b, c):

return a + b + c

def square(self, a):

return a * a

def cube(self, a):

return a * a * a

my_calculator = SuperCalculator()

temp = my_calculator.addition(23, 47, 12)

print(temp)

temp = my_calculator.subtraction(87, 54)

print(temp)

temp = my_calculator.multiplication(65, 56)

print(temp)

temp = my_calculator.division(852, 76)

print(temp)

temp = my_calculator.square(7)

print(temp)

temp = my_calculator.cube(3)

print(temp)

Output:

82

33

3640

11.210526315789474

49

27

Here, we have override addition() function.

ITERATOR AND GENERATOR

In this part of the Python tutorial, we work with iterators and generators. An iterator is an object which allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation.

In Python, an iterator is an object which implements the iterator protocol. The iterator protocol consists of two methods. The __iter__() method, which must return the iterator object, and the next() method, which returns the next element from a sequence.

Iterators have several advantages:

Cleaner code

Iterators can work with infinite sequences

Iterators save resources

Python has several built-in objects, which implement the iterator protocol. For example, lists, tuples, strings, dictionaries or files.

Generator:

This a function. This is a function used to use yield statement to create a sequence. From this angle, the generator is also an iterator.

Example:

def revrange(n):

while n >= 0:

yield n

n = n - 1

for a temp in revrange(5):

print(temp)

Output:

5

4

3

2

1

0

When one generator function is called then before executing the code of function it returned one generator object. When, first time __next__() method is called, then the code of the function is started to be executed.

MAGIC METHOD

When we were reading about class, we have learned about some methods like __init __(), __iter__(), __next__(). There are some more double underscored methods in python. They are known as a magic method. If we give two underscores on both sides of a method, they are known as dunder. So, we can say dunder unit rather than saying ‘underscore underscore init underscore underscore’. We can know more

In Python's Official Doc (
https://docs.python.org/3/reference/datamodel.html
),

we can learn more about Magic Method. But here we will learn about some important magic methods.

Constructor and destructor magic method

__init__(self, [...])
>> Constructor the class

__del__(self)
>>Destructor the class

To implement this two, let’s do an example:

class MyClass:

"""A custom class for nothing"""

def __init__(self, var):

self.var = var

def __del__(self):

del self.var

Comparison magic method:

__cmp__(self, other)
> Father of all comparison

__eq__(self, other)
> Work for == operator

__ne__(self, other)
> Work for != operator

__lt__(self, other)
> Work for < operator

__gt__(self, other)
> Work for > operato
r

__le__(self, other)
> Work for <= operator

__ge__(self, other)
> Work for >= operator

Let’s see some implementation of comparison magic method:

class MyClass:

"""A custom class for nothing"""

def __init__(self, var):

self.var = var

def __del__(self):

del self.var

def __gt__(self, other):

return len(other) > len(self.var)

def __lt__(self, other):

return len(other) < len(self.var)

def __ge__(self, other):

return len(other) >= len(self.var)

def __le__(self, other):

return len(other) <= len(self.var)

Arithmetic Magic method

__add__(self, other)

__sub__(self, other)

__mul__(self, other)

__div__(self, other)

__mod__(self, other)

__pow__

__floordiv__(self, other)

> Work for + operator

> Work for - operator

> Work for * operato
r

> Work for / operator

> Work for % operator

> Work for ** operator

> Work for == operator

Type conversion magic method

__int__(self) >Convert in Integer

__float__(self) >Convert in float

__str__(self) >Convert in human readable string __repr__(
>Convert in machine readable string

Some more magic mathod

__len__(self)
>return container length

__iter__(self)
>return iterator for container

__contains__(self, item)
>checking the item is a member of the container or not Implementation of these methods

class MyClass:

"""A custom class for nothing"""

def __init__(self, var):

self.var = var

def __del__(self):

del self.var

def __len__(self):

return len(self.var)

def __iter__(self):

return iter(self.var)

.

MODULE AND PACKAGE

Module

We will now create a file named fibo.py in a specific directory or folder. Now we will type the code to find the Fibonacci section.

def fib(n):

series = []

a, b = 0, 1

while b < n:

series.append(b)

a, b = b, a+b

return series

if __name__ == "__main__":

temp = fib(100)

print(temp)

Output:

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Now we go back to our old test.py. There we will print the list of a Fibonacchi series by e-etre with the for a loop.

import fibo

series = fibo.fib(100)

for an item in series:

print(item)

Output:

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

1

1

2

3

5

8

13

21

34

55

8
9

We've used the fib () function written in fibo.py again. This function is the biggest advantage of the module, not writing it again or without copying. Modules are the way to organize the logical code. In Pythonic language, the module is a file that contains Python definitions and statements. This file is the name of the module, except the .py part.

If we want, we can import a specific attribute directly from a module. For this we have to use the from ... import ... statement

from fibo import fib

series = fib(100)

for an item in series:

print(item)

Output:

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

1

1

2

3

5

8

13

21

34

55

8
9

All the attributes of a module, we can use the ... import * statement to import once.

from fibo import *

series = fib(100)

for an item in series:

print(item)

Output:

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

1

1

2

3

5

8

13

21

34

55

89

Now come, if __name__ == "__main__" in the story. When we run a script directly, and only

then it's equal to __name__, & zwj; __ main__ "and this block code gets the chance to run.

Each script in Python is one module. When going to work, the whole script will run in the

background and create the output. But we do not need it. This is why if __name__ ==

"__main__" is used. In order to import modules, the code under if __name__ == "__main__
"

will not run in that module. Because then __name__ no longer "__main__" is not equal. For

this reason, the best way to write a Python script is to:

def my_function():

# do something def your_function():

# do something def

main():

# call all functions here

my_function()

# play with them

your_function()

if __name__ == "__main__":

# now call main function

main()

Page

Module search path

When we import the fibo modules, then we searched for a build in function in the interpreter named as fibo. If we don’t find it, we will search for a file ‘fibo.py’ in several directories. The list of the variables can be found in sys.path variable. It will throw ImportError if cannot return any search result.

Example:

from omuk import tomuk

Output:

Traceback (most recent call last):

File "/home/ugcoder/Desktop/test.py", line 1, in <module>

from omuk import tomuk

ImportError: No module named 'omuk'

Standard Librar
y

The modules, which remain in python by default, we call them as the standard library. It is also called as standard module. Example: time is a standard module. By using the build in function dir(), we will see all the valid attributes

>>> import time

>>> dir(time)

['CLOCK_MONOTONIC', 'CLOCK_MONOTONIC_RAW', 'CLOCK_PROCESS_CPUTIME_ID', 'CLOCK_REALTIME', 'CLOCK_THREAD_CPUTIME_ID', '_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime',

'clock', 'clock_getres', 'clock_gettime', 'clock_settime', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'perf_counter', 'process_time', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname', 'tzset']

Into this function, if we don’t pass any argument, that will return every variable, module and function list in the present runtime.

>>> dir()

['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'requests', 'sys', 'time']

Package

The package is a way to do the module structure. A package is created with module, sub-package, sub-sub-package etc. We will see an example from the official doc of python->

sound/ Top-level package

__init__.py Initialize the sound package

formats/ Subpackage for file format conversions

__init__.py

wavread.py

wavwrite.py

Aiffread.py

aiffwrite.p
y

auread.py

auwrite.py

...

effects/ Subpackage for sound effects

__init__.py

echo.py

surround.py

reverse.py

...

filters/ Subpackage for filters

__init__.py

equalizer.py

vocoder.py

karaoke.py

We will import the echo model from the upper package. And will use echo sub-package's function echofilter().

import sound.effects.echo

sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

We can import in a different way.

from sound.effects import echo

echo.echofilter(input, output, delay=0.7, atten=4)

There is another way,

from sound.effects.echo import echofilter

echofilter(input, output, delay=0.7, atten=4)

Python package index

pypi is a python package repository. There are 91259 pieces of packages. The original developers didn’t create these packages. This package has been created by the developers like us. It doesn’t come by default. We need to install them separately. These packages are the power of python. For installing this thing, we need the installer pip
.

For installing in ubuntu we need to enter given command-> sudo apt-get install python3-pip

Suppose, we will install a request package from repo. For this we need to enter the following command into ubuntu terminal.

sudo pip3 install requests

Not only in ubuntu. pip supports on Mac-OS and windows also. After installing it we can use them as a normal package.

>>> import requests

>>> r = requests.get('https://api.github.com/events')

>>> r.status_code

200

Now, we will right something interesting in a python shell.

>>> import this

The Zen of Python, by Tim Peters

Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

The complex is better than complicated.

The flat is better than nested.

Sparse is better than dense.

Readability counts.

Special cases aren't special enough to break the rules.

Although practicality beats purity.

Errors should never pass silently.

Unless explicitly silenced.

In the face of ambiguity, refuse the temptation to guess.

There should be one-- and preferably only one --obvious way to do it.

Although that way may not be obvious at first unless you're Dutch.

Now is better than never.

Although never is often better than *right* now
.

If the implementation is hard to explain, it's a bad idea.

If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!

We need to keep in mind the importing and exporting systems. Hope we understood.

DECORATOR

In python function is a first class object. This means that we can pass function just like normal value or variable and can use as parameter or argument. Consider the following

example:

def get_int_as_str(number):

return str(number)

def print_int(my_function, number):

print(my_function(number))

return

print_int(get_int_as_str, 130)

Output:

130

In here, we passed get_init_as_str() function into print_init() function as an argument.

After that we did coding on this topic. What if we want to return the function in this case?

Everything possible by python.

Example:

def get_int_as_str(number):

print(str(number))

retur
n

def print_int(my_function, number):

return my_function(number)

print_int(get_int_as_str, 130)

Output:

130

In here, we passed get_init_as _str() function into print_init() function and an integer value, as an argument. We returned get_init_as_str() in the return part of print_init() function. But at that moment, get_int_as _str() function started to be executed during return part. So, all the rest, get_int_as_str() returns the same thing as print_init() function. But we could also define get_int_as_str() funtion into print_init() function.

def print_int(number):

def get_int_as_str(number):

print(str(number))

return

get_int_as_str(number)

return

print_int(130)\

Output:

130

We can make this program look good after the following modification.

def print_int(number):

def get_int_as_str(number):

print(str(number))

return

return get_int_as_str(number)

print_int(130)

Output:

13
0

We wrote a decoder without knowing it. For this, print_int() is a decorator. In python, the decorator is a function which can extend without any modification of other function’s work- limit. The syntax to write decorator is @decorator_name. Now, we can write the same program which is discussed above like this:

def print_int(my_function):

def any_function():

return my_function

return any_function()

@print_int

def get_int_as_str(number):

print(str(number))

return

get_int_as_str(130)

Output

130

Now, we need to know the advantages of the decorator. That is why, we will look for another example. We will write a program that will show us the time a program will take to be executed. we will take help from the python standard module time’s time() function, in this case.

from time import time

def timer(any_function):

def count_time():

start = time()

any_function()

stop = time()

print(stop-start, 'seconds')

return

return count_time

@timer

def hello():

print('Hello World!')

retur
n

@timer

def another_function():

for item in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:

print(item)

return

hello()

another_function()

Output:

Hello World!

0.006817340850830078 seconds

1

2

3

4

5

6

7

8

9

10

0.041167497634887695 seconds

Now, we need some practice on the decorator.

.

REGULAR EXPRESSION

By using the special character sequence, if we find any specific pattern or sequence from a huge amount of string that special character sequence is known as a regular expression. Sometimes, we call it as a regex. Regexp or in a short case RE. Wikipedia says,

In theoretical computer science and formal language theory, a regular expression (sometimes called a rational expression) is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. "find and replace"-like operations.

Now, see the following string

purple alice@google.com, blah monkey bob@abc.com blah dishwasher

There are two email addresses. We will use the standard module name as re to find these two emails.

import re

my_string = "purple alice@google.com, blah monkey bob@abc.com blah dishwasher"

temp = my_string.split(',')

for phrase in temp:

result = re.search("([\w\.-]+)@([\w\.-]+)", phrase)

print(result.group())

Output:

alice@google.com

bob@abc.com

Hmmm, we found those emails. Let’s see the part -> ‘re.search("([\w\.-]+)@([\w\.-]+)", phrase)’ . This function’s (re.search(pattern, string
,

flags=0)) first argument is pattern and second is string and the third one is not a important topic right now. Now, let’s learn the basic pattern to match some single character.

A, a, 0
= alpha numaric character..which is match itself.

= Matches any single character except a newline. Using m option allows it to match newline as well.

^ = Matches beginning of the line.

$ = Matches end of the line.

* = Any number of occurrences (including 0 occurrences).

+ = One ore more occurrences.

? = Matches zero or one occurrence.

/
= skip special character

[]
= character set.

\A
= Matches the beginning of the string.

\b
= Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets.

\B
= Matches nonword boundaries.

\d
= Matches digits. Equivalent to [0-9].

\D
= Matches nondigits.

\s
= Matches whitespace. Equivalent to [\t\n\r\f].

\S
= Matches nonwhitespace.

\w
= Matches word characters.

\W
= Matches nonword characters.

\Z
= Matches the end of the string. If a newline exists, it matches just before the newline.

\t,\n,\r
=
Matches newlines, carriage returns, tabs, etc.

We memorize all these things by practicing hard. Now, we will see some interesting examples of search patterns and uses some re module’s functions.

re.match(pattern, string, flags=0)

Now, we need to know what flags are. flags, some modifier function, creates regex’s changing effects
.

Now, see rematch() function. This function returns an object at the start of regex function, if it finds a match of zero or more than that. If it doesn’t find any match, then it returns non. We can get values in several ways from an object by using group() or group(num) method.

import re

my_string = "purple alice@google.com, blah monkey bob@abc.com blah dishwasher"

temp = my_string.split(',')

for phrase in temp:

result = re.match("([\w\.-]+)@([\w\.-]+)", phrase)

print(result)

Output:

None

None

Python returned none. Because, match() function only search at the start of the string to find a match. But the search function searches all the string to find the matching string. For this we didn’t get the expected result like the first program.

re.sub(pattern, repl, string, count=0, flags=0)

This function, if any part of string matches with the pattern, replaces with repl. Nothing happens if they don’t match.

>>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE) 'Baked Beans & Spam'

For understanding this more, we can visit the official doc of python

- https://docs.python.org/3/library/re.html

Unit testing

Programming and unit tasting are related very deeply. Unit tasting is a way in programming to test several functions automatically. For this, we need to write code in every function.

Example:

def add(a, b):

return a + b

def is_even(number):

if (number % 2) == 0:

return True

else:

return False

For testing this function, we will write code ‘test.py’ in the same directory.

import unittest

from hijibiji import add, is_even

class MyTest(unittest.TestCase):

def test_add(self):

self.assertEqual(add(2, 3), 5)

def test_is_even(self):

self.assertTrue(is_even(2))

if __name__ == '__main__':

unittest.main()

Output:

..

----------------------------------------------------------------------

Ran 2 tests in 0.010s

O
K

Here, add() function added two value. So, we have tested that in add() function if we pass 1,3 then if it returns 5 or not. And is_even() checks if the number is even or not. If even, it returns true and vice-versa.

So, to learn more about this, you can visit the official doc

(
https://docs.python.org/3.5/library/unittest.html
) of python.

pytest

Pytest is a matured, full-featured third -party python testing tool. It is better and full-featured than unittest. For installing it we will use the following command.

sudo pip3 install -U pytest

pytest install successfull..we have to re-write our test code which is test.py

from hijibiji import add, is_even

def test_add():

assert add(2, 3) == 5

def test_is_even():

assert is_even(2) == True

Now, in the terminal we need to use this

pytest test.py

Output:

===================== test session starts ======================

platform linux -- Python 3.5.2, pytest-3.0.3, py-1.4.31, pluggy-0.4.0 rootdir: /home/ugcoder/Desktop, inifile: collected 2 items

test.py ..

==================== 2 passed in 0.03 seconds ================
=

It is an easier test than the previous one. We may visit the official doc

(
https://docs.pytest.org/en/latest/index.html
) to know more about pytest.

Some more rules of testing

· One test unit will focus on one small functionality and we need to prove it.

· Every test unit will be independent. That means they can run on their own.

· We need to code such a way that it runs faster.

· We need to learn to run a single test unit.

· Every in any project time we need to test those units before and after running the codes.

Docstring

What is Docstring?

Docstring is a string which is the first statement in a module, function or class. This type of string is known as __doc__ in that object. Docstring should be as small as a phrase and will finish in every period. Effects in function or method will be as a command not description. There are two forms in docstring-> one-line docstring and multi-line docstring.

One-line docstring

This docstring will be in a single line and not more than 79 characters. There will be no blanks near it. But after the class docstring there should be a blank.

def kos_root():

"""Return the pathname of the KOS root directory."""

global _kos_root

if _kos_root: return _kos_root

…

Multi-line docstring

Docstring will be written in multiple lines. It is generally used in class. At first there will be a description and then argument’s description. For every argument there will be some different lines.

def complex(real=0.0, imag=0.0):

"""Form a complex number.

Keyword arguments:

real -- the real part (default 0.0)

imag -- the imaginary part (default 0.0)

"""

if imag == 0.0 and real == 0.0:

return complex_zero

DEBUGGING AND LOGGING

Debugging

When we write a program, there are usually two types of errors. These are syntax errors and logical errors.

The syntax error program is easily captured. But the logical error is a bit difficult to catch. The logical error is detected by unit testing. However, the logical error is very difficult to catch. I will look at all the time to write programs all the way, but the output is not coming. This problem, we call it to a bug in the programming language. The way to break this bug is debugging. The bug that killed bugs is called Debugger.

Python has a great built-in debugger. Its name is pdb (pdb) or full name when Python Debugger (Python Debugger). We can work with this debugger in three ways.

1. PDB is basically a module. So, we can start debugging it by importing it into our program and then doing some of the relevant things.

2. Can debug in Python IDLE (IDLE).

3. Can debugging in terminal or command line

The last is the smartest solution. So, we will learn this now. However, a small program will be written in the test.py file before, just for debugging.

Def square(x):

Temp=x**2

Print(temp)

Return

def main()

For i in range(1,11):

Square(I)

If __name__ =”__main__”:

Main(
)

Now, we will give the command in terminal

python3 -m pdb test.py

The debugger will be started in the terminal if you command this command. Of course, instead of writing such a big command, we can give even a small command.

pdb3 test.py

When debugger starts (pdb) we can debug with different commands on the right

Now we will learn some important debugging commands:

a or args
>> print all argument and their value

b or break lineno
>> pause the exe where given the line no.

c or continue
>> exe is running while finding next breakpoint.

n or next
>> exe is running while finding the next line of the current function.

p expression
>> print value after execution

q quit
>> debugger off

restart
>> debugger restart

w where
>> for seeing which line is executing now

There are many more. But for now, knowingly we can go to work. There is no official dock option for more information.

There are many more. But for now, knowingly we can go to work. There is no official dock option for more information.

Logging

When a program runs, there are many events happening. These events are tracked by logging and recording. While running the program it works differently, it can cause various types of errors which are handled
through expression; these events are recorded in the logs of the message. So that the program has the advantage of debugging.

Python's standard library has a very strong logging module. By using that we will now create a simple logger.

For this we will write some code in our test.py:

Import logging

logging.basicConfig(filename=test.log', level=logging.INFO)

logging.debug('This is a debug message.')

logging.info('This is an informational message.')

logging.error('This is an error message.')

I made a simple logger. But how did it happen? Let's explain.

logging.basicConfig(**kwargs)
function creates a stream handler object with the default format. Then add it to the root logger and create the basic configuration of our logging system. Mainly, what is the initial structure of our logging system? However, when running the above program, we will see another file called test.log created in the same folder as test.py. There are two messages in info and error. But there is no debug message. Because we set our logger's message level INFO. So, it will only save info, warning, critical and error messages.

Now, Let’s try:

Import logging

Logging.basicConfig(filename=’test.log’, level=logging.INFO)

a =10 b =0 try:

temp = a/b print(temp)

Except ZeroDivisionError as e: logging.exception(e)

Now we used Logger on a real-life issue. We already know that if a number is divisible by zero, then the Python ZeroDivisionError throws it out. We have saved the entire error message in this Exemption with the logging.exception () function. Another thing to note is that both of the messages in our previous example are remaining. The reason is that
everything is appended to the file. We can also use the file in write mode. For this, logging.basicConfig (** kwargs) will have to set filemode = 'w'.

We will now see another example. But before that we will write the function to test in the hijibiji.py that we can add or is there any even integer or not.

def add (a, b):

return a + b

def is_even(number):

if (number % 2==0):

return True

else

return False

Code is written. Now let's put the logging in it. For this, we will write the code in test.py:

Import logging

From hijibiji import add, is_even

logging.basicConfig(filename='test.log',level=logging.INFO)

logging.info('We are calling our add function.')

temp = add(12,78)

print(temp)

logging.info('add function executed, task completed.')

logging.info('We are calling our is_even funcion.')

temp = is_even(2)

print(temp)

logging.info('is_even function executed, task completed.')

If you run the program, you will see that some more informative messages have been added to the file. But the messages are unacceptable. Let's make them a little spicy. For this, we will write the code in test.py:

Import logging

From hijibiji import add, is_eve
n

logging.basicConfig(filename='test.log', format='%(asctime)s - %(name)s - %(levelname)s - (message)s',level=logging.INFO)

logging.info('We are calling our add function.')

temp = add(12,78)

print(temp)

logging.info('add function executed, task completed.')

logging.info('We are calling our is_even funcion.')

temp = is_even(2)

print(temp)

logging.info('is_even function executed, task completed.')

DATA STRUCTURE AND ALGORITHM

In easy language, we have learned a lot from Python & nbsp; (at least learned the basics), we now have to sit down to think & nbsp; after reading the book. How much knowledge we could get? There is an easy way to understand it. The solution is to try to solve various mathematical problems through programming. But the problem is so much problem where and we will find out the solution that is really the right solution, how to understand? Do not be afraid! There are online judges.

An online judge is an online system where a program is automatically tested against a problem that is found to be 100% correct. Various programming problems (called common programming phenomena) are available in various online judges. If the solution is resolved by submitting the answer to the specific place, then Jazz will tell us whether our solution is correct. Some popular online judges that support Python are:

HackerRank

HackerEarth

URI

UVA

SPOJ

Codeforces

TopCode
r

Contest platforms are the first and the last, which means that there are various online competitions with programming in these places so that everyone can participate. Although there is a conservative platform, there are many such problems of solvent problems (called the practice problem). But our question is, what will we start with so much online judge crowd?

In the beginning we can use HackerRank, HackerEarth and URI. Bigener, data structure, algorithms, such as HackerEarth and URI, is divided into different sections of the problem.

& Nbsp; However, it is best to start with Python & nbsp; HackerRank. Because, in the Problem section of Python, there are different problems for each topic of Python. When we are finished learning the basics of programming, we can try to solve all the topic topics. The topic of which will be more difficult to solve the problem, we will be able to understand that we are weak. For this reason, opening books / official documentation and understanding the agenda of that topic again. If you do not understand, you will get help from the big ones. Nowadays there are different groups of programming languages on Facebook, where there is a quick solution to its problems.

Data structure

Data structures are specializing in the data collection and storage of data, so that these data can be best restored and used for various purposes. But how important is the data structure for us?

We usually do three types of data on a computer - (1) data input, (2) data processing and (3) data output. And the purpose of the data structure is to help or optimize these three types of work. Suppose we put 10 thousand books in our personal library. If we put books on the shelf without
following a specific pattern or any method, then we will have to pass our whole life to find out the book. To get rid of these troubles, we need to know the data structure.

The list, tuple, set, the dictionary was Python's built-in data structure. But in addition to these, we need to know more about some data structures.

· Stack

· Queue

· Linked list

· Binary search tree

· Heaps

· Avl tree

· B tree

· B+ tree

· Binary indexed tree

· Trie

· Disjoint-set

· Segment tree

Algorithm

The algorithm is the number of operation sets. To be more precise, it is called the algorithm of any problem that can be solved by the best solution. These are the methods proven by mathematics. If a problem is solved by applying common intelligence, it is as effective as it is, it is more effective if the algorithm is solved using the algorithm.

Common algorithms are:

Bubble Sort

Insertion sort

Selection sort

Quick sort

Heap sort

Depth first search (DFS
)

Breadth first search (BFS)

A* Search

Hill Climbing

Data Structure: Stack

Talking about the data structure does not mean talking about the stack at all. I heard the word from a friend of mine first, the incident was quite funny. I was sitting in a boring class. I thought it could be some kind of entertainment by pushing the next friend with a pen. And I did it.

But he did not respond much. I thought there could be two reasons for not responding. One, he is the most concentrated students in the class and two, they have Rhinoceros’s genes. To make sure that the test was done more quickly than ever before, I pinched him again. Now the descendant of the great Rhinoceros has a terrible response. He turned back and looked at me to threaten me -

Pinch once again and I will stack all your bones.

When I came home and saw the dictionary to find the meaning of stack.

In short, the stack is the stack. More specifically, the stack is a structured collection of items where the new item is added (push) or the old item is removed (pop) at the same end of the archive. It was not understood, is not it? No matter. If I give an example, the matter will be clear.

Let's imagine a stack of five food plates. If we want to add a new plate (push) to this stack, then the sixth plate will be placed at the top of the stack. Now we have a stack of six plates. Now if you want to remove a plate from this stack (pop), then the fifth plate will be removed. If we notice, we can give a name for the same thing that is done at the top - top. And on the other side, it can be called bottom or base
.

Those who are very intelligent in us may have realized that this is a Last-in-First-Out (LIFO) data structure. The reason is that we're putting the item at the end of the last one, but it's the first thing to do (pop). I mean, the end of the meeting is the end of all but the first time out. what fun!

Operation

At a glance we will now see all the operations of the stack. These operations are performed with the usual five types of functions or methods.

push(item)

This function or method is used to add new items to the top of the stack. Although it accepts the item as an argument or parameter, it does not return anything.

pop()

Although this function or method does not accept anything as an argument or parameter, return the item at the top of the stack. Along with that, remove the item from the stack.

peek()

This function or method is very similar to pop (). The only difference is that it does not remove (remove) items from the stack like pop ().

is_empty()

This is a boolean function (or method). Check whether the stack is empty or true or false return. There are also no parameters.

size()

This function (or method) does not accept any arguments or parameters and returns the number of items in the stack
.

Do we understand the operations? Two-one may not fully understand There is nothing to worry about it. While studying several times and at the time of stack implants, the basics will become clearer.

Implementation

We can implement the stack in any structured or object-oriented programming language. Just be aware that all the operations of the stack can be done in the program. To store stack items, we need something like an array or an array. I like the array because I have no arrays in Python but there is an array (like advanced array) list. However, at the array or list index zero will be the stack's base and the maximum index will be the top of the stack. When the head and tail index is the same, there is nothing inside the queue, that should be empty. Then the above four types of functions (or methods) should be implemented.

Data Structure: Queue

Similar to the Stack, another linear data structure is a queue. Linear data structure means that the items are consistent, such as: stack, queue, linked list.

The queue is a series of items where the collection of new items is enclosed at the end of the archive, and the dequeue of the old item is at the opposite end. For the sake of understanding, we can say rear or tail on the edge of the new item at the end. And at the edge of the old item that is removed, we can say front or head. It's a bit confusing, is not it? There is no reason to worry. It becomes clear when you tell an example. The Queue is when you stand in a line to do something. You can’t finish the work before the men who are in front of you. And the people whoever are behind you cannot finish the work before you
.

The queue is a first-in-first-out (FIFO) data structure. Because, first, the person who is entering before is coming out first.

Operation

At a glance we will now see all the operations of the Queues. These operations are usually executed with four types of functions or methods.

enqueue(item)

This function or method is used to add new items to the queue rear or tail. Although it accepts the item as an argument or parameter, it does not return anything.

dequeue()

If this function or method does not accept anything as an argument or parameter, return the item to the head of the Queues. Besides, remove the item from the queue.

is_empty()

This is a Boolean function (or method). Check whether the queue is empty or not and returns true or false. There are also no parameters.

size()

This function (or method) does not accept any arguments or parameters and returns the total number of queue items

Implementation

We can implement any structured or object-oriented programming language on a stack-like queue. Just be aware that all the operations of the QA can be done in the program. To store queue items, we need an array or a list (there are list in Python instead of an array).However, in the array or list index 0 will be the front or head of the queue and the maximum index will be the rear or tail of the queue. When the head and
tail index is the same, there is nothing inside the queue that should be empty. Then the above four types of functions (or methods) should be implemented.

Data Structure: Singly linked list

In the previous examples we have come to see Python's built-in data structure - list usage. We can call the linked list as a special form of that list. The reason for the special saying is that there are some special issues on this list.

There are almost four types of linked lists: Simple or Singly Linked List, Doubly Linked List, Multiply Linked List and Circular Linked List. Today we will try to find out the Singly Linked List.

Simply, the Singly Linked List is the number of nodes in the chain. In a little more book's language, a single linked list is a series of collections of data elements or collections of nodes. That means it is a Linear Sequence! Here, nodes are actually a basic unit. Each node has two fields. The first field contains the data item and the last field is the pointer or the next node link.

To understand the matter, we can go back to childhood. Do we remember the days of the school shirk? Especially, ten-fifteen students standing side-by- side by holding hands. If you remember it, we will continue. When we stood ten times with ten hands, we used to hold both of them with our hands. The left hand of one person's hold the right-hand of another, his right hand and the next man's left hand in the left hand. In this way we would have formed a human chain so we could We can imagine each person as a node in this chain. The data item of that node is our body and the right arm is the pointer
.

From the first node, the beginnings of the Singly Linked List started. The first value remains at the first node's data item. The pointer portion of the first node points to the second node. This continues. The termination of a list is mainly indicated by the null reference. Many times, none means the conclusion. Termination means that there is no other node after this node.

Operation

At a glance we will now see all the operations of the Singly Linked List. These operations are usually performed with nine types of functions or methods.

appendleft(item)

This function or method is used to add new data items by adding a new node at the beginning of the list. It does not return anything as accepted by the data item as the argument or parameter

append(item)

This function or method is used to add new data items by adding a new node at the end of the list. It does not return anything as accepted by the data item as the argument or parameter

insert(position, item)

This function or method is used to add new data items by adding a new node to a specified position. It also does not return any of the positions and parameters as the arguments or parameters.

remove(item)

This function or method is used to remove specific data items and associated nodes from the beginning of the list. It receives an item as an
argument or a parameter but does not return anything. (Assumed the item is on the list)

pop()

Generally, this function or method removes the last data item and the corresponding node in the list and returns data items. (Assumed, there is at least one item in the list)

is_empty()

This is a Boolean function (or method). Checks whether the list is empty or not and returns true or false. There are no parameters.

size()

This function (or method) returns the total item (node) or a number of the linked list. There are also no parameters.

search(item)

This is a Boolean function (or method). Receive an item as an argument or a parameter and search for whether it is in the linked list and returns True or False.

index(item)

This function or method accepts an item as an argument or parameter. Then it returns the position of the search on the linked list and returns it. (Assumed the item is on the list)

printlist()

This function or method will print all the items in the list. (Assumed, there is at least one item in the list)

Implementatio
n

Implementation of singly-linked lists like stack, queue or deck is not a simple nature. If it is a bit complicated, but if in Python (3.x) you have some good ideas, then it is not difficult to implement. Actually, there is no such thing as implementing data structures or algorithms. If there is a clear idea about what is going on or what is going to be written easily.

Data Structure: Circular linked list

If you have a clear idea about the Singly Linked List, it is easy to understand the Circular Linked List. If you forget then there is no problem. We will go to Flashbay.

Singly Linked List is the number of node chains or combinations. Each node has two fields. The first field contains the data item and the last field contains the pointer or the next node's link or reference. The termination of the node chain is mainly indicated by the null reference. Many times, none means the termination. Termination means that there is no other node after this node.

The difference between Circular Linked List with Singly Linked List is basically this null reference. There is no null reference in the circular linked list. Rather, the last node has a link or reference to the first node. Consequently, the circular linked list can be compared to the circular bengaline ring.

Let's go back to school in those days. Do we remember the events of the sports competition? Do you remember the cock-fight? Many of us were standing round and round in the arms, and there was competition between them. Our friends pushed each other in a jump like a cock. When someone falls down, he's out then the circle was reduced to a little. Have lost those days from Mindset
?

Now let's consider this standing right in front of the circle. Every human can be imagined as a node in this human chain. It is possible to imagine that our object is the data item of the node and the right arm is the link or reference of the next node.

Suppose, the circular linked list has started from the first node. The first value remains at the first node’s data item. The pointer portion of the first node points to the second node. This continues. And the fourth node's pointers point to the first node. This is the circular linked list.

Operation

At a glance we will now see all operations of the Circular Linked List. These operations are usually performed with ten types of functions or methods.

appendleft(item)

This function or method is used to add new data items by adding a new node at the beginning of the list. It does not return anything as accepted by the data item as the argument or parameter.

append(item)

This function or method is used to add new data items by adding a new node at the end of the list. It does not return anything as accepted by the data item as the argument or parameter.

insert(position, item)

This function or method is used to add new data items by adding a new node to a specified position (position) . It takes data automatically as the argument or parameter item, but it does not return anything.

remove(item
)

This function or method is used to remove specific data items and associated nodes from the beginning of the list. It receives an item as an argument or a parameter but does not return anything. (Assumed the item is on the list)

popleft()

Generally, this function or method removes the list’s first data item and related nodes and return data items. (Assumed, there is at least one item in the list)

pop()

Generally, this function or method removes the last data item and the corresponding node in the list and returns data items. (Assumed, there is at least one item in the list)

is_empty()

This is a Boolean function (or method). Check whether the list is empty or not and resturns true or false. There are no parameters.

size()

This function (or method) returns the total item number of the linked list. There are also no parameters.

search(item)

This is a Boolean function (or method). Receive an item as an argument or a parameter and search for whether it is in the linked list and returns True or False.

index(item)

This function or method accepts an item as an argument or parameter. Then it returns the position of the search on the linked list. (Assumed the item is on the list
)

printlist()

This function or method will print all the items in the list. (Assumed, there is at least one item in the list.)

Implementation

We now know that the Circular Linked List is the number of node chains. To maintain each node, we need to create a Node() class.

class Node():

def __init__(self, item=None, next_node=None):

self.item = item

self.next_node = next_node

The arguments in this class are two: item and next_node. item is used to mean data item. And next _node is basically a pointer to contain the next node reference. Initially, the values of the two arguments are none.

Now we will create 10 methods for conducting the Circular Linked List operations. These methods will be under the CircularLinkedList () class.

class CircularLinkedList():

def __init__(self, head=None):

self.head = head

The arguments in this class are only one: head. The head list indicates the first node. Initially the head's value is None.

Let's first consider the appendleft(item) method.

def appendleft(self, item):

new_node = Node(item)

new_node.next_node = self.head

current = self.head

if self.head is not None:

while current.next_node is not self.head
:

current = current.next_node

current.next_node = new_node

else:

new_node.next_node = new_node

self.head = new_node

This method will always add a head item (actually node). So, we first created a new node through the node class. The new head of the list means that the current head will go in the second position. So we have given the node reference in the self.head (class variable) in the next_node variable of the new node. Now the event is that there may be something on self.head in the list or not. There is nothing to mean that only the nodes we add to the list are there. This node will point itself to its next_node variable in its own right. And if there is a node at self.head it’ll be weird. In that case, the last node of the list will point us to this new node. This is The Circular Linked List

Now we will think about the append method. This method will always add new items (actually nodes) at the end of the list. But this is a lot easier. Create a new node. At present, the node at the end of the list will point to this new node. And the new node will point to the head

def append(self, item):

new_node = Node(item)

current = self.head

if current:

while True:

if current.next_node is self.head:

current.next_node = new_node

new_node.next_node = self.head

break

else:

current = current.next_node

else: self.head = new_node

new_node.next_node = new_nod
e

insert (position, item) method is quite interesting In order to add the last position of the list to the head of the list (zero position) or in the list, appendleft and item order can be done by calling the method. But if we want to add a node in the middle of the two nodes, we have to make a little trouble.

def insert(self, position, item):

if position == 0:

self.appendleft(item)

print(item, "inserted to position", position)

elif position == self.size():

self.append(item)

print(item, "inserted to position", position)

elif position > self.size():

print("Index out of range")

else:

current = self.head index = 0

while current:

if index != position:

previous = current

current = current.next_node

index += 1

else:

new_node = Node(item, current)

previous.next_node = new_node

current = False

print(item, "inserted to position", position)

Suppose we add a new node to the number four. At present, the node in the number four position will be moved to the number five position, the node in the number five position goes to the six -number position.So, by creating a new node, we will now point to the node in the number four position with its next_node variable. And next_node variable of a node in number position will point to the new node. Done
.

The is_empty () method is quite simple. If there is at least one node in the list, there will be its reference in self.head. Just check whether the head is empty (none). If empty, the True Return will be done, otherwise False returns.

def is_empty(self):

if self.head == None:

return True

else:

return False

The size () method is as simple as the is_empty () method. we just need to make a while loop for node counting.And whenever the head is referenced in next_node's reference of a node, the loop must be stopped. The listed size can be found, when the total number of times of the loop is calculated.

def size(self):

current = self.head

count = 0 w

hile current:

count += 1

if current.next_node is self.head:

current = False

else:

current = current.next_node

return count

If you understand the implementation of the above size () method, it is easy to implement the index method. We know that the work of this method is to return the index position of an item. We assume that the Index system of the Circular Linked List is similar to the typical Python list. This means that it will start from Zero.

while current
:

if current.item == item:

return index

elif current.next_node is self.head:

break

else:

current = current.next_node

index += 1

return None

That's why we started searching for items from the head. If you do not find, then go to the next node. And whenever I went to the next node, I incremented the index value by 1. When the desired data item has been found in any node, then we terminate the loop. In this way we got the index number of our desired data item (actually node).

The search (item) method is similar to the previous index (item) method. The only difference is that if this method finds the desired item, then it will return true. Otherwise False will be returned.

def search(self, item):

current = self.head

found = False

while current and not found:

if current.item == item:

found = True

elif current.next_node is self.head:

current = False

else:

current = current.next_node

if the current is None:

print("Item not found")

return found

The work of popleft () method is the opposite of the appendleft (item) method. That means, removing the first node in the list and returning its item
.

def popleft(self):

if self.is_empty():

print("Empty list")

else:

current = self.head

temp = current.item

if current.next_node is self.head:

self.head = None

else:

self.head = current.next_node

next_node = self.head

while next_node.next_node is not current:

next_node = next_node.next_node

next_node.next_node = self.head

del current

return temp

Since self-header is the first node in the list, so we will remove it. After removing it, the next node will be heading. And next_node variable of the last node in the list will point to this new head. To find out the last node after the removal of the node which will be the head, from this head will start the looping. We wanted to see the next_node variable of the node pointing to the removing node. This is the turn to remove the first node. Before removing, the item of a node is placed in a temp variable so that the item can be returned after removing the node.

The job of the pop () method is the opposite of the append (item) method. That means, removing the last node in the list and returning its item.

def pop(self):

if self.is_empty():

print("Empty list")

else:

current = self.head

previous = Non
e

while current.next_node is not self.head:

previous = current

current = current.next_node

if current == self.head:

self.head = None

else:

previous.next_node = self.head

temp = current.item

del current

return temp

Our first job is to find the last node. How to do it? We have already learned. The node that next_ node points to the variable head, that's the last node. That's why we found the last node in a loop. Before removing, the item of the node is placed in a temp variable so that the item can be returned after removing the node.

The remove method may seem a little difficult. So be a little careful now.

def remove(self, item):

if self.is_empty():

print("Empty list")

else:

current = self.head

previous = None

found = False

while current and not found:

if current.item == item:

found = True

elif current.next_node is self.head:

current = None

else:

previous = current

current = current.next_node

if the current is None:

print("Item not found")

elif previous is None:

self.popleft(
)

print(item, "removed")

else:

temp = current.next_node

del current

print(item, "removed")

previous.next_node = temp

As we remove any item, so first of all to check that there is no node in the list. That is why we have taken the help of is_empty () method. If the list is not empty, then the item that needs to be removed, turned it into a while loop and searched it. If the desired data item is in the head, it is enough to call popleft () method. Otherwise, the node that holds the desired data item, as a current node. The next_ node variable of the current node has been assigned to the next_node variable of the node just before its reference node. Then delete the current node.

The fact that printlist () method is not really difficult. By a looping, discover all the nodes.

Then print the node's data item.

def printlist(self):

if self.is_empty():

print("Empty list")

else:

current = self.head

print(current.item)

while current.next_node:

current = current.next_node

if the current is self.head:

break

else:

print(current.item)

From the above discussion it is clear that the operation and implementation of the circular linked list are very similar to the Singly Linked List
.

Data Structure: Doubly link list

In the meantime, we have tried to get a small idea about the Singly Linked List and the Circular Linked List. In its continuation, we will now know the doubly linked list.

Dual Linked List, like the Singly Linked List, also has several nodes chains or combinations. But the difference is, in the field number of nodes. Each node in the Singly Linked List contains two fields. But there are three fields on each node in the doubly linked list. In the first field, there is a previous pointer or link to the previous node, the data item in the middle field and the last field contains the next pointer or the next node's link. Since each node has two pointers, so this node chain has two edges. The end result of the node chain is marked by the null reference on both ends. Many times, the termination is also understood by none. Termination means that there is no other node after this node.

Let’s create a human chain bye holding each other's hand of some friends. Every human can be imagined as a node in this human chain. Our left hand is called the Previous Pointer, the object's data item and the right hand as the next pointer. In this, two hands on both sides of the chain are empty. If someone else wants to join this chain, then he needs to hold one of those empty hands.

Suppose, the first node has started the doubly linked list. The first node's previous pointer is null, because there is no node before it. This node has the first value in the data item portion. The next pointer to the first node points to the second node. This continues. And the next pointer to the third node is null, because there is no node after it. This is the doubly linked list.

Operatio
n

At a glance we will now see all operations of the doubly linked list. These operations are usually performed with ten types of functions or methods.

appendleft(item)

This function or method is used to add new data items by adding a new node at the beginning of the list. It does not return anything as accepted by the data item as the argument or parameter.

append(item)

This function or method is used to add new data items by adding a new node at the end of the list. It does not return anything as accepted by the data item as the argument or parameter.

insert(position, item)

This function or method is used to add new data items by adding a new node to a specified position (position) . It takes data automatically as the argument or parameter item, but it does not return anything.

remove(item)

This function or method is used to remove specific data items and associated nodes from the beginning of the list. It receives an item as an argument or a parameter but does not return anything. (Assumed the item is on the list)

popleft()

Generally, this function or method removes the list’s first data item and related nodes and return data items. (Assumed, there is at least one item in the list)

pop(
)

Generally, this function or method removes the last data item and the corresponding node in the list and returns data items. (Assumed, there is at least one item in the list)

is_empty()

This is a Boolean function (or method). Check whether the list is empty or not and resturns true or false. There are no parameters.

size()

This function (or method) returns the total item number of the linked list. There are also no parameters.

search(item)

This is a Boolean function (or method). Receive an item as an argument or a parameter and search for whether it is in the linked list and returns True or False.

index(item)

This function or method accepts an item as an argument or parameter. Then it returns the position of the search on the linked list. (Assumed the item is on the list)

printlist()

This function or method will print all the items in the list. (Assumed, there is at least one item in the list.

Implementation

We now know that the doubly linked list is the number of node chains. To maintain each node, we need to create a Node () class.

class Node():

def __init__(self, item=None, previous_node=None, next_node=None)
:

self.item = item

self.previous_node = previous_node

self.next_node = next_node

The arguments in this class three: item, previous_node and next_node. The data item is being used by the item. And previous_node is the references to the previous node mentioned above and next_node is the reference to the next node. Initially, the value of arguments three is none.

We will create ten methods for conducting the operations of the doubly linked list. These methods will be under the DoublyLinkedList () class

class DoublyLinkedList():

def __init__(self, head=None, tail=None):

self.head = head

self.tail = tail

The arguments of this class are two: head and tail. The head list indicates the first node.

And tail indicates the last node in the list. Initially their value is None.

Let's first consider the appendleft(item) method.

def appendleft(self, item):

new_node = Node(item)

new_node.previous_node = None

new_node.next_node = self.head

if self.head is None:

self.tail = new_node

else: self.head.previous_

node = new_node

self.head = new_node

This method will always add the head item (actually node). So, we first created a new node through the node class. The new head of the list means that the current head will be left in the second position. So we
have given the node reference in the self.head (class variable) in the next_node variable of the new node. And since this new node does not have any nodes, so none is assigned at the previous_node variables. Now the event is that there may be some lists on self.head in the list or not. There is nothing to mean that only the nodes we add to the list are there. This node is the first and last node in the list. So at self.tail we gave the new node reference. And if there is any node in self.head, then the reference to the new node must be given in the previous_node variable. Finally, we gave our new node reference to self.head (class variables).

Now we will think about the append method. This method will always add new items (actually nodes) at the end of the list. But this is a lot easier. Create a new node. At the end of the list (at self.tail) the next_node variable of the node points to this new node. And the previous_node variable of the new node will point to the node at self.tail.

def append(self, item):

new_node = Node(item)

if self.head is None:

self.head = self.tail = new_node

else:

new_node.previous_node = self.tail

new_node.next_node = None

self.tail.next_node = new_node

self.tail = new_node

insert (position, item) method is quite interesting. In order to add the last column of the list to the head of the list (zero position) or the bottom of the list, you can fill the job by calling appendleft(item) and append(item) method. But if we want to add a node in the middle of the two nodes, we have to make a little trouble.

def insert(self, position, item)
:

if position == 0:

self.appendleft(item)

print(item, "inserted to position", position)

elif position == self.size():

self.append(item)

print(item, "inserted to position", position)

elif position > self.size():

print("Index out of range")

else:

current = self.head

index = 0

while current:

if index != position:

previous = current

current = current.next_node

index += 1

else:

new_node = Node(item, previous, current)

previous.next_node = new_node

current.previous_node = new_node

current = False

print(item, "inserted to position", position)

Suppose we add a new node to the number four. At present, the node in the number four position will be moved to the number five position, the node in the number five position goes to the six -number position.So, by creating a new node, we will now point to the node in the number four position with its next_node variable. And next_node variable of the node in number position will point to the new node. Done.

The is_empty () method is quite simple. If there is at least one node in the list, there will be its reference in self.head. Just check whether the head is empty (none). If empty, the True Return will be done, otherwise False returns
.

def is_empty(self):

if self.head is None:

return True

else:

return False

The size () method is as simple as the is_empty () method. we just need to make a while loop for node counting.And whenever the head is referenced in next_node's reference of a node, the loop must be stopped. The listed size can be found, when the total number of times of the loop is calculated

def size(self):

current = self.head

count = 0

while current:

count += 1

current = current.next_node

return count

If you understand the implementation of the above size () method, it is easy to implement the index method. We know that the work of this method is to return the index position of an item. We assume that the Index system of the Circular Linked List is similar to the typical Python list. This means that it will start from Zero.

def index(self, item):

current = self.head

index = 0

while current:

if current.item == item:

return index

else:

current = current.next_node

index += 1

return Non
e

That's why we started searching for items from the head. If you do not find, then go to the next node. And whenever I went to the next node, I incremented the index value by 1. When the desired data item has been found in any node, then we terminate the loop. In this way we got the index number of our desired data item (actually node).

The search (item) method is similar to the previous index (item) method. The only difference is that if this method finds the desired item, then it will return true. Otherwise False will be returned.

def search(self, item):

current = self.head

found = False

while current and not found:

if current.item == item:

found = True

else:

current = current.next_node

if the current is None:

print("Item not found")

return found

The work of popleft () method is the opposite of the appendleft (item) method. That means, removing the first node in the list and returning its item.

def popleft(self):

if self.is_empty():

print("Empty list")

else:

current = self.head

next_node = current.next_node

if next_node is None:

temp = current.item

del current

self.head = self.tail = Non
e

return temp

else:

temp = current.item

del current

next_node.previous_node = None

self.head = next_node

return temp

Since self-header is the first node in the list, so we will remove it. After removing it, the next node will be heading. And next_node variable of the last node in the list will point to this new head. To find out the last node after the removal of the node which will be the head, from this head will start the looping. We wanted to see the next_node variable of the node pointing to the removing node. This is the turn to remove the first node. Before removing, the item of a node is placed in a temp variable so that the item can be returned after removing the node.

The job of the pop () method is the opposite of the append (item) method. That means, removing the last node in the list and returning its item.

def pop(self):

if self.is_empty():

print("Empty list")

else:

current = self.tail

previous = current.previous_node

if previous is None:

temp = current.item

del current

self.head = self.tail = None

return temp

else:

temp = current.item

del current

previous.next_node = Non
e

self.tail = previous

return temp
Page

Our first job is to find the last node. How to do it? We have already learned. The node that next_ node points to the variable head, that's the last node. That's why we found the last node in a loop. Before removing, the item of the node is placed in a temp variable so that the item can be returned after removing the node.

The remove method may seem a little difficult. So be a little careful now.

def remove(self, item):

if self.is_empty():

print("Empty list")

else:

current = self.head

previous = None

found = False

while current and not found:

if current.item == item:

found = True

else:

previous = current

current = current.next_node

if the current is None:

print("Item not found")

elif previous is None:

self.popleft()

print(item, "removed")

else:

temp = current.next_node

del current

print(item, "removed")

previous.next_node = temp

temp.previous_node = previou
s

As we remove any item, so first of all to check that there is no node in the list. That is why we have taken the help of is_empty () method. If the list is not empty, then the item that needs to be removed, turned it into a while loop and searched it. If the desired data item is in the head, it is enough to call popleft () method. Otherwise, the node that holds the desired data item, as a current node. The next_ node variable of the current node has been assigned to the next_node variable of the node just before its reference node. Then delete the current node.

The fact that printlist () method is not really difficult. By a looping, discover all the nodes.

Then print the node's data item.

def printlist(self):

if self.is_empty():

print("Empty list")

else:

current = self.head

while current:

print(current.item)

current = current.next_node

Hopefully, if you try a little link list can be made now.

GUI PROGRAMMING

GUI – Graphical User Interface. Wikipedia says- Gui is a user interface, where user can interact by the help of graphical icon and visual indicator.

Python is a very charming framework for GUI programing. And most of them are for cross platform. That means by changing a little bit you can run it ins any Operating System. Now we will know about some GUI framework.

PyQt

The Python binding of the Qt Framework is PyQt, cross-platform framework (supports Windows, Linux, MacOS and Android). The latest version is PyQt5 which supports Qt v5. It can be used under the GNU GPL v3 license. Under this license, we can create free software from PyQt and it's free to distribute. But if you want to distribute some close-source software commercially, we will have to buy PyQt's commercial version under Riverbank Commercial License. Official website of: https://riverbankcomputing.com/software/pyqt/intro

And

http://pyqt.sourceforge.net/Docs/PyQt5/introduction.html

PyGTK

The Python binding of GTK + Framework is PyGTK, cross-platform framework (supports Windows, Linux and MacOS) but is more popular in Linux. The latest version is PyGTK3 which supports GTK + 3 via PyGObject. It can be used under the GNU LGPL license. Under this
license we can distribute our software commercially, excluding few restrictions. Official Website: http://www.pygtk.org/" and official tutorial: https://python-gtk-3-tutorial.readthedocs.io/en/latest/

PySide

Another Python binding of the Qt Framework is PySide, cross-platform framework (supports Windows, Linux, MacOS and Android) . The latest version is PySide v1.2.4, which supports Qt v4.8. But PySide2's development is in progress, which supports Qt v5 (website: https://wiki.qt.io/PySide2)%E0%A5%A4 PySide can be used under the GNU LGPL license. Under this license we can distribute our software commercially, excluding few restrictions. Official Website: https://wiki.qt.io/PySide

WxPython

The Python binding of wxWidgets C ++ library is wxPython, cross-platform framework (supports Windows, Linux and MacOS). Website: https://www.wxpython.org/

KIVY

OpenSource Cross-Platform Python Nui (NUI - Natural User Interface) library. Simultaneously Windows, Linux, MacOS, Android and iOS support. The best Python library for developing multi-touch apps Official website: https://kivy.org/

Tkinter

Python is part of the Standard Library, cross-platform (supports Windows, Linux and MacOS). It is a bit ugly to see, it has a great reputation. But there is a great lightweight reputation. Official Website: https://docs.python.org/3/library/tk.htm
l

Now we will look at an example of gigi using PyGTK3. For this, first of all we need to install the PyGObject package. For Debian or Ubuntu, we can install the package by executing the following command in the terminal.

sudo apt install python3-gi

Once installed, create a file called app.py and write the code as follows:

Import gi

Gi.require_version(‘Gtk’,’3.0)

From gi.repository import Gtk

Win=Gtk.Window()

Win.connect(“delete-event”,Gtk.main_q

Win.show_all()

Gtk.main()

Now run a script and see a window. What's so nice? PyQt5 can also create such a beautiful user interface. However, these frameworks were not so widely available in this short-range book.

CONCLUSION

Programming is an artistic affair, another name for entertainment. But bizarre academic life has made programming bitter forever in the world. On the other hand, the paracetamol of village-doctors has made programming like a spherical millennium.

Learning programming should be simple, straightforward and joyful. When joy is added to a job, that task can take our brain much faster. In general, Python is a very straightforward programming language. But the medium of learning also needs to be fun. In this book, the most emphasis is given in this book. This is not a text book, it is a mystery for Python about Python.

Whoever is confident enough that they won’t be able to learn python in their whole life

The one who knows programing but not python.

Whoever wants to learn python.

The one who knows python2 but wants to migrate to python 3.

Popular as a scripting language.

Popular as a general-purpose language.

Open sourced.

Interesting from a program language perspective.

Easy to learn and use, so being used in many CS 101 courses.

For whom is this book?

The one who doesn’t know a word about programing.

The book is not for whom?

The one who doesn’t know the use of a computer.

Whoever doesn’t want to learn python 3, but python 2.

The one who knows everything about python 3
.

How to use the book?

When reading the book, we will read every topic, not need to memorize. We will continue to read the chapters of the book in advance and not continuously. For the sake of understanding, many things have been skipped in the early pressers and later the details are explained. Programming is the thing to do in hand. So, we will see each example run by itself.

Programming is something to practice. So, every issue will be used by itself.

Copyright

All rights reserved in this book are preserved; Except for the written permission of the author, the publication of the book or any part of the book is absolutely prohibited and legally punished
.