theories of this language and the second volume includes exercises of this...

110

Transcript of theories of this language and the second volume includes exercises of this...

Page 1: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications
Page 2: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

The present book is a book on teaching Python programming that has two volumes, the first volume includes

theories of this language and the second volume includes exercises of this language.

This book uses Android software, the link of which is placed below

https://play.google.com/store/apps/details?id=com.apkzube.learnpython

Python Tutorial

Python tutorial provides basic and advanced concepts of Python. Our Python tutorial is designed for beginners and professionals.Python is a simple, easy to learn, powerful, high level and object-oriented programming language. Python is an interpreted scripting language also. Guido Van Rossum is known as the founder of python programming. Our Python tutorial includes all topics of Python Programming such as installation, control statements, Strings, Lists, Tuples, Dictionary, Modules, Exceptions, Date and Time, File I/O, Programs, etc. There are also given Python interview questions to help you better understand the Python Programming.

• Prerequisite - Before learning Python, you must have the basic knowledge of programming concepts.

• Audience - Our Python tutorial is designed to help beginners and professionals. • Problem - We assure that you will not find any problem in this Python tutorial. But if there is

any mistake, please post the problem in contact on [email protected]

Python Introduction

1. Python is a general purpose, dynamic, high level and interpreted programming language. It supports Object Oriented programming approach to develop applications. It is simple and easy to learn and provides lots of high-level data structures.

2. Python is easy to learn yet powerful and versatile scripting language which makes it attractive for Application Development.

3. Python's syntax and dynamic typing with its interpreted nature, makes it an ideal language for scripting and rapid application development.

4. Python supports multiple programming pattern, including object oriented, imperative and functional or procedural programming styles.

5. Python is not intended to work on special area such as web programming. That is why it is known as multipurpose because it can be used with web, enterprise, 3D CAD etc.

6. We don't need to use data types to declare variable because it is dynamically typed so we can write a=10 to assign an integer value in an integer variable.

Page 3: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

7. Python makes the development and debugging fast because there is no compilation step included in python development and edit-test-debug cycle is very fast.

Python 2 vs. Python 3

In most of the programming languages, whenever a new version releases, it supports the features and syntax of the existing version of the language, therefore, it is easier for the projects to switch in the newer version. However, in the case of Python, the two versions Python 2 and Python 3 are very much different from each other.

A list of differences between Python 2 and Python 3 are given below:

• In Python 2 uses print as a statement and used as print "something" to print some string on the console. On the other hand, Python 3 uses print as a function and used as print("something") to print something on the console.

• Python 2 uses the functionraw_input() to accept the user's input. It returns the string representing the value, which is typed by the user. To convert it into the integer, we need to use the int() function in Python. On the other hand, Python 3 uses input() function which automatically interpreted the type of input entered by the user. However, we can cast this value to any type by using primitive functions (int(), str(), etc.).

• In Python 2, the implicit string type is ASCII, whereas, in Python 3, the implicit string type is Unicode

• Python 3 doesn't contain thexrange() function of Python 2. The xrange() is the variant of range()function which returns a xrange object that works similar to Java iterator. The range() returns a list for example the function range(0,3) contains 0, 1, 2.

• There is also a small change made in Exception handling in Python 3. It defines a keyword as which is necessary to be used. We will discuss it in Exception handling section of Python programming tutorial.

Our Online Python Compiler

You do not need to install Python on your computer to follow this tutorial. However, we recommend you to run Python programs in Online Python Compilersection.

Python Features

Python provides lots of features that are listed below.

1. Easy to Learn and Use - Python is easy to learn and use. It is developer-friendly and high level programming language.

2. Expressive Language - Python language is more expressive means that it is more understandable and readable.

3. UNIQUE STYLES - Python is an interpreted language i.e. interpreter executes the code line by line at a time. This makes debugging easy and thus suitable for beginners.

4. Cross-platform Language - Python can run equally on different platforms such as Windows, Linux, Unix and Macintosh etc. So, we can say that Python is a portable language.

Page 4: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

5. Free and Open Source - Python language is freely available at offical web address (https://www.python.org/).The source-code is also available. Therefore it is open source.

6. Object-Oriented Language -Python supports object oriented language and concepts of classes and objects come into existence.

7. Extensible - It implies that other languages such as C/C++ can be used to compile the code and thus it can be used further in our python code.

8. Large Standard Library - Python has a large and broad library and prvides rich set of module and functions for rapid application development.

9. GUI Programming Support - Graphical user interfaces can be developed using Python. 10. Integrated - It can be easily integrated with languages like C, C++, JAVA etc.

Python History

1

Python laid its foundation in the late 1980s.

2

The implementation of Python was started in the December 1989 by Guido Van Rossum at CWI in Netherland.

3

In February 1991, van Rossum published the code (labeled version 0.9.0) to alt.sources.

4

In 1994, Python 1.0 was released with new features like: lambda, map, filter, and reduce.

5

Python 2.0 added new features like: list comprehensions, garbage collection system.

6

On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify fundamental flaw of the language.

7

ABC programming language is said to be the predecessor of Python language which was capable of Exception Handling and interfacing with Amoeba Operating System.

8

Python is influenced by following programming languages: (1) ABC language. (2) ABC language.

Python Version

Page 5: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Lets start off by looking at Python history. Python was developed at a time when many other dynamic and open-sourceprogramming languages like Tcl, Perl, Ruby etc. were also being actively developed and gaining popularity.

1

Python 1.0

In January 1994, the first version of Python 1.0 was released. This version 1 includes the major new features like the functional programming tools filter, reduce, map, and lambda etc.

2

Python 2.0

After Six and a half years later, Python 2.0 was introduced in October 2000. In this release, a full garbage collector, list comprehensions were included, and it also supports Unicode.

3

Python 3.0

then after 8 years, the next major release was made. This release wasPython 3.0 also known as”Py3K” or “Python 3000”.

The major changes in Python 3.0 are:

• In this version, Print is a Python function • Instead of lists, in this version, we have Views and iterators. • In this version, we have more simplified rules for ordering comparisons. For example, we

cannot sort a heterogeneous list, because each element of a Python List must be comparable to other elements.

• In this python version, int. long is also an int as there is only one integer type. • In this python version, when we divide two integers it resultant returns is a float instead of an

integer. We can use “//” to have the “old” behavior. • In this python version, Instead of Unicode Vs. 8-bit we have Text Vs. Data • The one drawback of Python 3.0 is that it is not backward compatiblewith Python 2.x.

Python Latest version:

The Python latest version is 3.7.0. This stable version was released on 27 June. The current latest (as of Winter 2019) is Python 3.7.2. The Python 3.7 version is aimed at making complex tasks simple, and It is currently in production release. The improvements to Python 3.7 version include:

• Data classes that reduce boilerplate when working with data in classes. • A “development mode” for the interpreter. • A new built-in for triggering the debugger. • UTF-8 mode that uses UTF-8encoding by default in the environment.

Page 6: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

• A potentially backward-incompatible change involving the handling of exceptions in generators.

• Nanosecond-resolution time objects .

Python Applications Area

Python is known for its general purpose nature that makes it applicable in almost each domain of software development. Python as a whole can be used in any sphere of development. Here, we are specifing applications areas where python can be applied.

1. Web Applications - We can use Python to develop web applications. It provides libraries to handle internet protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser etc. It also provides Frameworks such as Django, Pyramid, Flask etc to design and delelop web based applications. Some important developments are: PythonWikiEngines, Pocoo, PythonBlogSoftware etc.

2. AI & Machine Learning - Python has Prebuilt Libraries like Numpy for scientific computation, Scipy for advanced computing and Pybrain for machine learning (Python Machine Learning) making it one of the best languages For AI.

3. Desktop GUI Applications - Python provides Tk GUI library to develop user interface in python based application. Some other useful toolkits wxWidgets, Kivy, pyqt that are useable on several platforms. The Kivy is popular for writing multitouch applications.

4. Software Development - Python is helpful for software development process. It works as a support language and can be used for build control and management, testing etc.

5. Scientific and Numeric - Python is popular and widely used in scientific and numeric computing. Some useful library and package are SciPy, Pandas, IPython etc. SciPy is group of packages of engineering, science and mathematics.

6. Business Applications - Python is used to build Bussiness applications like ERP and e-commerce systems. Tryton is a high level application platform.

7. Console Based Application - We can use Python to develop console based applications. For example: IPython.

8. Audio or Video based Applications - Python is awesome to perform multiple tasks and can be used to develop multimedia applications. Some of real applications are: TimPlayer, cplay etc.

9. 3D CAD Applications - To create CAD application Fandango is a real application which provides full features of CAD.

10. Enterprise Applications - Python can be used to create applications which can be used within an Enterprise or an Organization. Some real time applications are: OpenErp, Tryton, Picalo etc.

11. Applications for Images - Using Python several application can be developed for image. Applications developed are: VPython, Gogh, imgSeek etc.

12. Games and 3D Graphics - PyGame, PyKyra are two frameworks for game-development with Python. Apart from these, we also get a variety of 3D-rendering libraries. If you’re one of those game-developers, you can check out PyWeek, a semi-annual game programming contest.

Page 7: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

HOW TO INSTALL PYTHON

Python 3 Major Version Installation (Wondows)

1

Download the latest Python 3.x version. At the time of writing this article latest version was Python 3.7.4 (July 8, 2019). Download Windows x86 – 64 executable file only as installer will automatically install 32 or 64 bit of Python according to the system configuration.

2

Open the executable file and Check the Add Python 3.7 to PATH. Then click the Install Now button. It will show the installation progress.

3

When the installation progress is completed, you will see the Disable path length limit. Now you must be thinking what is it and whats will happen if I will disable it. The answer is clear, it will remove the limitations on MAX_PATH variable. It will allow to use long path names for the Python. We recommend you to not disable this option as it will remove any path related issues while working in Windows. Therefore click on the close button to finish the installation.

4

Now, the Python 3.7.4 is installed. You can check it either it is properly installed or not. You can do it through Command Prompt. Open the command prompt and type the following command -" python -v ". It will output the version of the Python.

5

Congratulation, you have successfully installed Python 3 version. you can read the next tutorial to Python Programming a complete guide for beginners.

Python 3 Major Version Installation (Linux)

Linux is an open source Operating System. There are many Linux based operating systems. Popular are Ubuntu, Fedora, Linux Mint, Debian. In this section you will learn how to do python installation for both Python 3 and Python 2 versions. Fedora Linux OS used for Installation of python. Most of the newer Linux based Operating system have already installed Python. You will check it is installed or not by the typing the following commands in terminal. For Python3 $ python3 --version For Python2 $ python2 --version You will see the python versions as output like in the below screenshot. But if you are not seeing then , you have to install Python . Follow the following steps for successful install.

Page 8: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

If you are using Ubuntu 16.0 or newer version, then you can easily install Python 3.6 or Python 2.7 by typing the following commands $ sudo apt-get update $ sudo apt-get install python3.7

Python 3 Major Version Installation (MacOS)

MacOs is an operating system developed by the Apple Inc. It is just like Windows Operating System and other operating system. Most of the newer versions of MacOS have pre-installed python. You can check python is installed or not by the following commands. python --version Download the Python 3 or 2 new version. At the time of writing this post , Python 3.7.4 - July 8, 2019 was the newer version. Download the Mac OS X 64-bit/32-bit (https://www.python.org/downloads/mac-osx/) installer. Run the package and following the installation steps to install the python packages After the successful installation , you can check the python version by using the same command. python --version

SETTING PATH IN PYTHON

If you’ve installed Python in Windows using the default installation options, the path to the Python executable wasn’t added to the Windows Path variable. The Path variable lists the directories that will be searched for executables when you type a command in the command prompt. By adding the path to the Python executable, you will be able to accesspython.exe by typing the python keyword (you won’t need to specify the full path to the program).

C:\>python

'python' is not recognized as an internal or external command, operable program or batch file

As you can see from the output above, the command was not found. To run python.exe, you need to specify the full path to the executable:

C:\>C:\Python34\python --version

Python 3.4.3.

To add the path to the python.exe file to the Path variable, start the Run box and enter sysdm.cpl

This should open up the System Properties window. Go to the Advanced tab and click the Environment Variables button:

Page 9: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

In the System variable window, find the Path variable and click Edit:

Position your cursor at the end of the Variable value line and add the path to the python.exe file, preceeded with the semicolon character (;). In our example, we have added the following value: C:\Python34

Close all windows. Now you can run python.exe without specifying the full path to the file:

NOTE : If you get the ‘python’ is not re

Python Hello, World

Python is easy to learn and code and can be execute with python interpreter. We can also use Python interactive shell to test python code immediately. A simple hello world example is given below. Write below code in a file and save with .pyextension. Python source file has .pyextension.

Writing the “Hello, World!” Program

To write the “Hello, World!” program, let’s open up a command-line text editor such as nano and create a new file: hello.py Once the text file opens up in the terminal window we’ll type out our program :

print("Hello, World!")

Let’s break down the different components of the code.

1

print() is a function that tells the computer to perform an action. We know it is a function because it uses parentheses. print() tells Python to display or output whatever we put in the parentheses. By default, this will output to the current terminal window.

2

Some functions, like the print() function, are built-in functions included in Python by default. These built-in functions are always available for us to use in programs that we create. We can also define our own functions that we construct ourselves through other elements.

3

Inside the parentheses of the print()function is a sequence of characters — Hello, World! — that is enclosed in quotation marks. Any characters that are inside of quotation marks are called a string.

4

Once we are done writing our program, save the file and we can exit notepad.

Once you exit out of notpad you’ll return to your shell or cmd.

Page 10: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Running the “Hello, World!” Program

The hello.py program that you just created will cause your terminal to produce the following output:

Hello, World!

Congratulations! You have written the “Hello, World!” program in Python 3 . Since the program ran, you can now confirm that Python 3 is properly installed and that the program is syntactically correct. s an internal or external command, operable program or batch file. error, there is something wrong

with your Path variable. Note also that you will have to reopen all command prompt windows in

order for changes to

Python Variables

Variable is a name which is used to refer memory location. Variable also known as identifier and used to hold value.In Python, we don't need to specify the type of variable because Python is a type infer language and smart enough to get variable type. Variable names can be a group of bothletters and digits, but they have to begin with a letter or an underscore.It is recomended to use lowercase letters for variable name. Rahul and rahul both are two different variables.

Variable Assignment

Think of a variable as a name attached to a particular object. In Python, variables need not be declared or defined in advance, as is the case in many other programming languages. To create a variable, you just assign it a value and then start using it. Assignment is done with a single equals sign (=):

>>>n=300

This is read or interpreted as “n is assigned the value 300.” Once this is done, n can be used in a statement or expression, and its value will be substituted:

>>> print(n)

300

Just as a literal value can be displayed directly from the interpreter prompt in a REPL session without the need for print(), so can a variable:

>>>n

300

Later, if you change the value of n and use it again, the new value will be substituted instead

>>> n = 1000

>>> print(n)

Page 11: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

1000

>>> n

1000

Python also allows chained assignment, which makes it possible to assign the same value to several variables simultaneously:

>>> a = b = c = 300

>>> print(a, b, c)

300 300 300

The chained assignment above assigns 300 to the variables a, b, and c simultaneously.

Variable Types in Python

In many programming languages, variables are statically typed. That means a variable is initially declared to have a specific data type, and any value assigned to it during its lifetime must always have that type. Variables in Python are not subject to this restriction. In Python, a variable may be assigned a value of one type and then later re-assigned a value of a different type:

>>> var = 23.5

>>> print(var)

23.5

>>> var = "Now I'm a string"

>>> print(var)

Now I'm a string

Object References

What is actually happening when you make a variable assignment? This is an important question in Python, because the answer differs some what from what you’d find in many other programming languages. Python is a highly object-oriented language. In fact, virtually every item of data in a Python program is an object of a specific type or class. (This point will be reiterated many times over the course of these tutorials.) Consider this code:

>>> print(300)

300

When presented with the statement print(300), the interpreter does the following:

Page 12: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

• Creates an integer object • Gives it the value 300 • Displays it to the console

You can see that an integer object is created using the built-in type() function:

>>>type(300)

< class 'int'>

A Python variable is a symbolic name that is a reference or pointer to an object. Once an object is assigned to a variable, you can refer to the object by that name. But the data itself is still contained within the object. For example:

>>>n = 300

This assignment creates an integer object with the value 300 and assigns the variable n to point to that object.

The following code verifies that n points to an integer object:

>>> print(n)

300

>>> type(n)

< class 'int'>

Now consider the following statement:

m=n

What happens when it is executed? Python does not create another object. It simply creates a new symbolic name or reference, m, which points to the same object that n points to.

Next, suppose you do this:

>>>m=400

Now Python creates a new integer object with the value 400, and m becomes a reference to it.

Lastly, suppose this statement is executed next:

>>>n="foo"

Now Python creates a string object with the value "foo" and makes n reference that.

There is no longer any reference to the integer object 300. It is orphaned, and there is no way to access it.

Page 13: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

When the number of references to an object drops to zero, it is no longer accessible. At that point, its lifetime is over. Python will eventually notice that it is inaccessible and reclaim the allocated memory so it can be used for something else. In computer lingo, this process is referred to as garbage collection.

Variable Names

The examples you have seen so far have used short, terse variable names like m and n. But variable names can be more verbose. In fact, it is usually beneficial if they are because it makes the purpose of the variable more evident at first glance. Officially, variable names in Python can be any length and can consist of uppercase and lowercase letters (A-Z, a-z), digits (0-9), and the underscore character (_). An additional restriction is that, although a variable name can contain digits, the first character of a variable name cannot be a digit.

• Note: One of the additions to Python 3 was full Unicode support, which allows for Unicode characters in a variable name as well. You will learn about Unicode in greater depth in a future tutorial.

For example, all of the following are valid variable names:

>>> name = "Bob"

>>> Age = 54

>>> has_W2 = True

>>> print(name, Age, has_W2)

Bob 54 True

But this one is not, because a variable name can’t begin with a digit:

>>> 1099_filed = False

SyntaxError: invalid token

Note that case is significant. Lowercase and uppercase letters are not the same. Use of the underscore character is significant as well. Each of the following defines a different variable:

>>> age = 1

>>> Age = 2

>>> aGe = 3

>>> AGE = 4

>>> a_g_e = 5

>>> _age = 6

>>> age_ = 7

>>> _AGE_ = 8

>>> print(age, Age, aGe, AGE, a_g_e, _age, age_, _AGE_)

1 2 3 4 5 6 7 8

Page 14: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

There is nothing stopping you from creating two different variables in the same program called age and Age, or for that matter agE. But it is probably ill-advised. It would certainly be likely to confuse anyone trying to read your code, and even you yourself, after you’d been away from it awhile.

le take effect.

Python Keywords

There is one more restriction on identifier names. The Python language reserves a small set of keywords that designate special language functionality. No object can have the same name as a reserved word. In Python 3.6, there are 33 reserved keywords

You can see this list any time by typing help("keywords") to the Python interpreter. Reserved words are case-sensitive and must be used exactly as shown. They are all entirely lowercase, except for False, None, and True. Trying to create a variable with the same name as any reserved word results in an error:

>>> for = 3

SyntaxError: invalid syntax

Page 15: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Python Identifiers

An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one entity from another.

Rules for writing identifiers

• Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _. Names like myClass, var_1 and print_this_to_screen, all are valid example.

• An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine. • Keywords cannot be used as identifiers

>>> global = 1

File "< interactive input >", line 1

global = 1

^

SyntaxError: invalid syntax

• We cannot use special symbols like !, @, #, $, % etc. in our identifier.

>>> a@ = 0

File "< interactive input >", line 1

a@ = 0

^

SyntaxError: invalid syntax

• Identifier can be of any length.

Python Literals

Literal is a raw data given in a variable or constant. In Python, there are various types of literals they are as follows:

Numeric Literals

Page 16: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Numeric Literals are immutable (unchangeable). Numeric literals can belong to 3 different numerical types Integer, Float and Complex.

Example : How to use Numeric literals in Python?

a = 0b1010 #Binary Literals

b = 100 #Decimal Literal

c = 0o310 #Octal Literal

d = 0x12c #Hexadecimal Literal

#Float Literal

float_1 = 10.5

float_2 = 1.5e2

#Complex Literal

x = 3.14j

print(a, b, c, d)

print(float_1, float_2)

print(x, x.imag, x.real)

When you run the program, the output will be:

10 100 200 300

10.5 150.0

3.14j 3.14 0.0

In the above program

• We assigned integer literals into different variables. Here, a is binary literal, b is a decimal literal, c is an octal literal and d is a hexadecimal literal.

• When we print the variables, all the literals are converted into decimal values. • 10.5 and 1.5e2 are floating point literals. 1.5e2 is expressed with exponential and

is equivalent to 1.5 * 10^2. • We assigned a complex literal i.e 3.14j in variable x. Then we use imaginary literal (x.imag)

and realliteral (x.real) to create imaginary and real part of complex number.

String literals

Page 17: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

A string literal is a sequence of characters surrounded by quotes. We can use both single, double or triple quotes for a string. And, a character literal is a single character surrounded by single or double quotes.

Example : How to use string literals in Python?

strings = "This is Python"

char = "C"

multiline_str = """This is a multiline string with more than one line code."""

unicode = u"\u00dcnic\u00f6de"

raw_str = r"raw \n string"

print(strings)

print(char)

print(multiline_str)

print(unicode)

print(raw_str)

When you run the program, the output will be:

This is Python

C

This is a multiline string with more than one line code.

Ünicöde

raw \n string

In the above program, This is Python is a string literal and C is a character literal. The value with triple-quote """ assigned in the multiline_str is multi-line string literal. The u"\u00dcnic\u00f6de" is a unicode literal which supports characters other than English and r"raw \n string" is a raw string literal.

Boolean literals

A Boolean literal can have any of the two values: True or False.

Example : How to use boolean literals in Python?

x = (1 == True)

y = (1 == False)

a = True + 4

b = False + 10

print("x is", x)

print("y is", y)

Page 18: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

print("a:", a)

print("b:", b)

When you run the program, the output will be:

x is True

y is False

a: 5

b: 10

In the above program, we use boolean literal True and False. In Python, True represents the value as 1 and False as 0. The value of x is True because 1 is equal to True. And, the value of y is False because 1 is not equal to False.

Similarly, we can use the True and False in numeric expressions as the value. The value of a is 5 because we add True which has value of 1 with 4. Similarly, b is 10 because we add the False having value of 0 with 10.

Special literals

Python contains one special literal i.e. None. We use it to specify to that field that is not created.

Example : How to use special literals in Python?

drink = "Available"

food = None

def menu(x):

if x == drink:

print(drink)

else:

print(food)

menu(drink)

menu(food)

When you run the program, the output will be:

Available

None

In the above program, we define a menu function. Inside menu, when we set parameter as drink then, it displays Available. And, when the parameter is food, it displays None.

Literal Collections

Page 19: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

There are four different literal collections List literals, Tuple literals, Dict literals,and Set literals.

Example : How to use literals collections in Python?

fruits = ["apple", "mango", "orange"] #list

numbers = (1, 2, 3) #tuple

alphabets = {'a':'apple', 'b':'ball', 'c':'cat'} #dictionary

vowels = {'a', 'e', 'i' , 'o', 'u'} #set

print(fruits)

print(numbers)

print(alphabets)

print(vowels)

When you run the program, the output will be

['apple', 'mango', 'orange']

(1, 2, 3)

{'a': 'apple', 'b': 'ball', 'c': 'cat'}

{'e', 'a', 'o', 'i', 'u'}

In the above program, we created a list of fruits, tuple of numbers, dictionary dict having values with keys desginated to each value and set of vowels.

We will learn more about literal collections in Advance Tutorial.

Python Operators

What are operators in python?

Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.

For example:

>>>2+3

5

Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the operation.

Arithmetic operators

Page 20: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc.

Arithmetic operators in Python

Op. Meaning Example

+ Add two operands or unary plus.

x + y +2

- Subtract right operand from the left or unary minus

x - y -2

* Multiply two operands x * y

/ Divide left operand by the right one (always results into float)

x / y

% Modulus - remainder of the division of left operand by the right

x % y (remainder of x/y)

// Floor division - division that results into whole number adjusted to the left in the number line

x // y

** Exponent - left operand raised to the power of right

x**y (x to the power y)

Example : Arithmetic operators in Python

x = 15

y = 4

# Output: x + y = 19

print('x + y =',x+y)

# Output: x - y = 11

print('x - y =',x-y)

# Output: x * y = 60

print('x * y =',x*y)

# Output: x / y = 3.75

print('x / y =',x/y)

Page 21: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

# Output: x // y = 3

print('x // y =',x//y)

When you run the program, the output will be:

x + y = 19

x - y = 11

x * y = 60

x / y = 3.75

x // y = 3

x ** y = 50625

Comparison operators

Comparison operators are used to compare values. It either returns True or False according to the condition.

Comparision operators in Python

Op. Meaning Exp

> Greater that - True if left operand is greater than the right

x>y

< Less that - True if left operand is less than the right

x<y

== Equal to - True if both operands are equal

x==y

!= Not equal to - True if operands are not equal

x!=y

>= Greater than or equal to - True if left operand is greater than or equal to the right

x>=y

<= Less than or equal to - True if left operand is less than or equal to the right

x<=y

Example : Comparison operators in Python

x = 10

y = 12

# Output: x > y is False

print('x > y is',x>y)

# Output: x < y is True

Page 22: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

print('x < y is',x= y is False

print('x >= y is',x>=y)

# Output: x <= y is True

print('x <= y is',x<=y)

Logical operators

Logical operators are the and, or, notoperators.

Logical operators in Python

Op. Meaning Exp.

and True if both the operands are true x and y

or True if either of the operands is true

x or y

not True if operand is false (complements the operand)

not x

Example : Logical Operators in Python

x = True

y = False

# Output: x and y is False

print('x and y is',x and y)

# Output: x or y is True

print('x or y is',x or y)

# Output: not x is False

print('not x is',not x)

Bitwise operators

Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name.

For example, 2 is 10 in binary and 7 is 111.

In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Bitwise operators in Python

Page 23: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Op. Meaning Exp.

& Bitwise AND x& y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x>> 2 = 2 (0000 0010)

<< Bitwise left shift x<< 2 = 40 (0010 1000)

Assignment operators

Assignment operators are used in Python to assign values to variables.

a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left.

There are various compound operators in Python like a += 5 that adds to the variable and later assigns the same. It is equivalent to a = a + 5.

Assignment operators in Python

Identity operators

is and is not are the identity operators in Python. They are used to check if two values (or variables) are located on the same part of the memory. Two variables that are equal does not imply that they are identical.

Identity operators in Python

Op. Meaning Exp.

is True if the operands are identical (refer to the same object)

x is True

is not

True if the operands are not identical (do not refer to the same object)

x is not True

Example : Identity operators in Python

x1 = 5

y1 = 5

x2 = 'Hello'

y2 = 'Hello'

x3 = [1,2,3]

y3 = [1,2,3]

Page 24: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

# Output: False

print(x1 is not y1)

# Output: True

print(x2 is y2)

# Output: False

print(x3 is y3)

Here, we see that x1 and y1 are integers of same values, so they are equal as well as identical. Same is the case with x2 andy2 (strings).

But x3 and y3 are list. They are equal but not identical. It is because interpreter locates them separately in memory although they are equal.

Membership operators

in and not in are the membership operators in Python. They are used to test whether a value or variable is found in a sequence (string, list, tuple, set and dictionary).

In a dictionary we can only test for presence of key, not the value.

Membership operators in Python

Op. Meaning Exp.

in True if value/variable is found in the sequence

5 in x

not in True if value/variable is not found in the sequence

5 not in x

Example : Membership operators in Python

x = 'Hello world'

y = {1:'a',2:'b'}

# Output: True

print('H' in x)

# Output: True

print('hello' not in x)

# Output: True

print(1 in y)

Page 25: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

# Output: False

print('a' in y)

Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive). Similary, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.

Python Comments

Comments in Python begin with a hash mark (#) and whitespace character and continue to the end of the line.

Generally, comments will look something like this:

#This is a Comment

Because comments do not execute, when you run a program you will not see any indication of the comment there. Comments are in the source code for humans to read, not for computers to execute.

1) Single lined comment:

In case user wants to specify a single line comment, then comment must start with #.

# This is single line comment.

2) Multi lined Comment:

Multi lined comment can be given inside triple quotes.

#single line comment

print "Hello Python"

'''''This is

multiline comment'''

3) inline comments

If a comment is placed on the same line as a statement, it is called an inline comment. Similar to the block comment, an inline comment begins with a single hash (#) sign and followed by a space and comment.

It is recommended that an inline comment should separate from the statement at least two spaces. The following example demonstrates an inline comment

n+=1 #increase n by 1

Python if statement

Page 26: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

The Python if statement is a statement which is used to test specified condition. We can use if statement to perform conditional operations in our Python application. The if statement executes only when specified condition is true. We can pass any valid expression into the if parentheses.

There are various types of if statements in Python.

1. if statement 2. if-else statement 3. Else if statement 4. nested if statement

If Statement Syntax

if statement, which will evaluate whether a statement is true or false, and run code only in the case that the statement is true.

if(condition):

statements

Page 27: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Example of if statement :

grade = 70

if grade >= 65:

print("Passing grade")

With this code, we have the variable grade and are giving it the integer value of 70. We are then using the if statement to evaluate whether or not the variable grade is greater than or equal ( >= ) to 65. If it does meet this condition, we are telling the program to print out the string Passing grade.

output of above example :

Passing grade

Again, if we change the grade to 50 or a < 65 number, we will receive no output.

Python If Else Statements

It is likely that we will want the program to do something even when an if statement evaluates to false. In our grade example of previous tutorial, we will want output whether the grade is passing or failing.

Python If Else Syntax :

if condition:

statement

else:

statement

To do this, we will add an else statement to the grade condition above that is constructed like this:

grade = 60

if grade >= 65:

print("Passing grade")

else:

print("Failing grade")

Since the grade variable above has the value of 60, the if statement evaluates as false, so the program will not print out Passing grade. The else statement that follows tells the program to do something anyway.

When we save and run the program, we’ll receive the following output:

Failing grade

Page 28: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

If we then rewrite the program to give the grade a value of 65 or higher, we will instead receive the output Passing grade.

Python Else if statement

So far, we have presented a Boolean option for conditional statements, with each if statement evaluating to either true or false. In many cases, we will want a program that evaluates more than two possible outcomes. For this, we will use an else if statement, which is written in Python as elif. The elif or else if statement looks like the if statement and will evaluate another condition.

Python Nested If Else Syntax :

If condition :

statements

elif condition:

statements

else:

statements

Python Nested If Else Example :

if grade >= 90:

print("A grade")

elif grade >=80:

print("B grade")

elif grade >=70:

print("C grade")

elif grade >= 65:

print("D grade")

else:

print("Failing grade")

Since elif statements will evaluate in order, we can keep our statements pretty basic. This program is completing the following steps:

1

If the grade is greater than 90, the program will print A grade, if the grade is less than 90, the program will continue to the next statement...

2

If the grade is greater than or equal to 80, the program will print B grade, if the grade is 79 or less, the program will continue to the next statement...

3

Page 29: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

If the grade is greater than or equal to 70, the program will print C grade, if the grade is 69 or less, the program will continue to the next statement...

4

If the grade is greater than or equal to 65, the program will print D grade, if the grade is 64 or less, the program will continue to the next statement...

5

The program will print Failing grade because all of the above conditions were not met.

Python Nested If Statement

We can use nested if statements for situations where we want to check for a secondary condition if the first condition executes as true. For this, we can have an if-else statement inside of another if-else statement. Let’s look at the syntax of a nested if statement:

if expression1:

statement(s)

if expression2:

statement(s)

elif expression3:

statement(s)

elif expression4:

statement(s)

else:

statement(s)

else:

statement(s)

lets run the following example :

a=10

if a>=20:

print "Condition is True"

else:

if a>=15:

print "Checking second value"

else:

print "All Conditions are false"

output of above example :

All Conditions are false.

Page 30: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Python For Loop

Python for loop is used to iterate the elements of a collection in the order that they appear. This collection can be a sequence(list or string).

Python For Loop Syntax :

for [variable] in [sequence]:

1

Firstly, the first value will be assigned in the variable.

2

Secondly all the statements in the body of the loop are executed with the same value.

3

Thirdly, once step second is completed then variable is assigned the next value in the sequence and step second is repeated.

4

Finally, it continues till all the values in the sequence are assigned in the variable and processed.

Python For Loop Simple Example :

num=2

for a in range (1,6):

print num * a

output of above example :

2

4

6

8

10

Python Example to Find Sum of 10 Numbers :

sum=0

for n in range(1,11):

sum+=n

print sum

Page 31: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

output of above example :

55

Python Nested For Loops

Example of Nested for loop :

for i in range(1,6):

for j in range (1,i+1):

print i,

print

output of above example :

1

2 2

3 3 3

4 4 4 4

5 5 5 5 5

For each value of Outer loop the whole inner loop is executed.

For each value of inner loop the Body is executed each time.

lets see one more example of patter program :

for i in range (1,6):

for j in range (5,i-1,-1):

print "*",

print

output of above example :

* * * * *

* * * *

* * *

* *

*

Python While Loop

In Python, while loop is used to execute number of statements or body till the specified condition is true. Once the condition is false, the control will come out of the loop.

Page 32: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

while loops are constructed like so :

while [a condition is True]:

[do something]

Here, loop Body will execute till the expression passed is true. The Body may be a single statement or multiple statement.

Python While Loop Example :

a=10

while a>0:

print "Value of a is",a

a=a-2

print "Loop is Completed"

output of above example :

Value of a is 10

Value of a is 8

Value of a is 6

Value of a is 4

Value of a is 2

Loop is Completed

Explanation:

1

Firstly, the value in the variable is initialized.

2

Secondly, the condition/expression in the while is evaluated. Consequently if condition is true, the control enters in the body and executes all the statements . If the condition/expression passed results in false then the control exists the body and straight away control goes to next instruction after body of while.

3

Thirdly, in case condition was true having completed all the statements, the variable is incremented or decremented. Having changed the value of variable step second is followed. This process continues till the expression/condition becomes false.

4

Finally Rest of code after body is executed.

Python While Loop Example 2 :

n=153

sum=0

Page 33: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

while n>0:

r=n%10

sum+=r

n=n/10

print sum

output of above example :

9

An infinite loop occurs when a program keeps executing within one loop, never leaving it. To exit out of infinite loops on the command line, press CTRL + C.

This tutorial went over how while loops work in Python and how to construct them. While loops continue to loop through a block of code provided that the condition set in the while statement is True.

Python Break Statement

In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You’ll put the break statement within the block of code under your loop statement, usually after a conditional if statement.

Flowchart of break statement :

Page 34: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications
Page 35: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Let’s look at an example that uses the break statement in a for loop:

number = 0

for number in range(10):

number = number + 1

if number == 5:

break # break here

print('Number is ' + str(number))

print('Out of loop')

Explanation:

1

In this small program, the variable number is initialized at 0. Then a for statement constructs the loop as long as the variable number is less than 10.

2

Within the for loop, the number increases incrementally by 1 with each pass because of the line number = number + 1.

3

Then, there is an if statement that presents the condition that if the variable number is equivalent to the integer 5, then the loop will break.

4

Within the loop is also a print() statement that will execute with each iteration of the for loop until the loop breaks, since it is after the break statement.

5

To see when we are out of the loop, we have included a final print() statement outside of the for loop.

output of above example :

Number is 1

Number is 2

Number is 3

Number is 4

Out of loop

This shows that once the integer number is evaluated as equivalent to 5, the loop breaks, as the program is told to do so with the break statement.

Page 36: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

The break statement causes a program to break out of a loop.

Python Continue Statement Python Continue Statement is a jump statement which is used to skip execution of current iteration.

After skipping, loop continue with next iteration. We can use continue statement with for as well as while

loop in Python

Continue Statement :

Python Continue Statement Example :

a=0

while a<=5:

Page 37: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

a=a+1

if a%2==0:

continue

print a

print "End of Loop"

output of above example :

1

3

5

End of Loop

You can use the continue statement to avoid deeply nested conditional code, or to optimize a loop by

eliminating frequently occurring cases that you would like to reject.

The continue statement causes a program to skip certain factors that come up within a loop, but then

continue through the rest of the loop.

Python Pass Statement In Python, pass keyword is used to execute nothing; it means, when we don't want to execute code, the

pass can be used to execute empty. It is same as the name refers to. It just makes the control to pass by

without executing any code. If we want to bypass any code pass statement can be used.

Python pass Example :

number = 0

for number in range(10):

number = number + 1

if number == 5:

pass # pass here

print('Number is ' + str(number))

print('Out of loop')

output of above example :

Number is 1

Number is 2

Number is 3

Number is 4

Number is 5

Page 38: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Number is 6

Number is 7

Number is 8

Number is 9

Number is 10

Out of loop

By using the pass statement in this program, we notice that the program runs exactly as it would if there

were no conditional statement in the program. The pass statement tells the program to disregard that

condition and continue to run the program as usual.

Python Strings

Python string is a built-in type text sequence. It is used to handle textual data in python. Python Strings are immutable sequences of Unicode points. Creating Strings are simplest and easy to use in Python.

We can simply create Python String by enclosing a text in single as well as double quotes. Python treat both single and double quotes statements same.

Example :

a = "Hello"

b= 'ApkZube'

print(a+" "+b)

output of above example :

Hello ApkZube

Accessing Python Strings

• In Python, Strings are stored as individual characters in a contiguous memory location. • The benefit of using String is that it can be accessed from both the directions (forward and

backward). • Both forward as well as backward indexing are provided using Strings in Python. • Forward indexing starts with 0,1,2,3,.... • Backward indexing starts with -1,-2,-3,-4,....

str[0]='P'=str[-6] ,

str[1]='Y' = str[-5] ,

str[2] = 'T' = str[-4] ,

str[3] = 'H' = str[-3] ,

str[4] = 'O' = str[-2] ,

str[5] = 'N' = str[-1].

Page 39: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Python String Example

Here, we are creating a simple program to retrieve String in reverse as well as normal form.

name="Rajat"

length=len(name)

i=0

for n in range(-1,(-length-1),-1):

print(name[i],"\t",name[n])

i+=1

output :

R t

a a

j j

a a

t R

Python Strings Operators

To perform operation on string, Python provides basically 3 types of Operators that are given below.

• Basic Operators. • Membership Operators. • Relational Operators.

1. Basic Operators

There are two types of basic operators in String + and *.

String Concatenation Operator (+)

str1="apk"

str2="Zube"

print(str1+str2)

Output :

apkZube

Page 40: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

String Concatenation Operator (+)

Expression Output

"10"+"50" "1050"

"apk"+"007" "apk007"

"apk97"+"zube97" "apk97zube97"

NOTE: Both the operands passed for concatenation must be of same type, else it will show an error.

for example :

print("apkZube"+97)

output :

Traceback (most recent call last):

File "main.py", line 1, in

print("apkZube"+97)

TypeError: Can't convert 'int' object to str implicitly

Python String Replication Operator (*)

Replication operator uses two parameters for operation, One is the integer value and the other one is the String argument.

The Replication operator is used to repeat a string number of times. The string will be repeated the number of times which is given by the integer value.

For Example :

print("ApkZube" * 5)

print(3 * "Python")

output :

ApkZubeApkZubeApkZubeApkZubeApkZube

PythonPythonPython

Python String Replication Operator (*)

Expression Output

"ArcX" * 2 "ArcXArcX"

3 * '5' '555'

'@' * 5 '@@@@@'

NOTE: We can use Replication operator in any way i.e., int * string or string * int. Both the parameters passed cannot be of same type.

Page 41: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

2 . Python String Membership Operators

Membership Operators are already discussed in the Operators section. Let see with context of String.

There are two types of Membership operators :

1. in - "in" operator returns true if a character or the entire substring is present in the specified string, otherwise false.

2. not in - "not in" operator returns true if a character or entire substring does not exist in the specified string, otherwise false.

lets see the example :

str1="ApkZube"

str2="Apk"

str3="Zube"

str4="Dev"

print('Exmple of in operator ::')

print(str2 in str1)

print(str3 in str1)

print(str4 in str1)

print()

print(str2 not in str1)

print(str3 not in str1)

print(str4 not in str1)

output :

Exmple of in operator ::

True

True

False

False

False

True

3. Python Relational Operators

Page 42: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

All the comparison (relational) operators i.e., (<,><=,>=,==,!=,<>) are also applicable for strings. The Strings are compared based on the ASCII value or Unicode(i.e., dictionary Order).

Example :

print("ApkZube"=="ApkZube")

print("apkZube">="ApkZube")

print("A"<"a")

output :

True

True

True

Explanation:

The ASCII value of a is 97, b is 98, c is 99 and so on. The ASCII value of A is 65, B is 66, C is 67 and so on. The comparison between strings are done on the basis on ASCII value.

Python String Slice Notation

Python String slice can be defined as a substring which is the part of the string. Therefore further substring can be obtained from a string.

There can be many forms to slice a string, as string can be accessed or indexed from both the direction and hence string can also be sliced from both the directions.

Syntax of Slice Operator :

str[start : stop : step ]

other syntax of slice

str[start : stop] #items start through stop-1

str[start : ] #items start through the rest of the array

str[ : stop] #items from the beginning through stop-1

str[ : ] # a copy of the whole array

example :

Page 43: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

s="Monty Python"

print(s[6:10])

print(s[-12:-7])

print(s[-1: :-1]) #reversed all string

print(s[2: 10: 2]) #step = 2

print(s[ : : -1]) #reversed all string

print(s[ : 5]) #from 0 to 4

print(s[3 : ]) #from 3 to end of the string

print(s[ : ]) #copy all strin

output :

Pyth

Monty

nohtyP ytnoM

nyPt

nohtyP ytnoM

Monty

ty Python

Monty Python

NOTE: Both the operands passed for concatenation must be of same type, else it will show an error.

String Funtionand Method

Function :

A function is a block of code to carry out a specific task, will contain its own scope and is called by name. All functions may contain zero(no) arguments or more than one arguments. On exit, a function can or can not return one or more values.

• Function is block of code that is also called by its name. (independent) • The function can have different parameters or may not have any at all. If

any data (parameters) are passed, they are passed explicitly. • It may or may not return any data. • Function does not deal with Class and its instance concept.

<

def functionName( arg1, arg2,….):

…….

# Function_body

……..

Page 44: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Method

A method in python is somewhat similar to a function, except it is associated with object/classes. Methods in python are very similar to functions except for two major differences.

• Method is called by its name, but it is associated to an object (dependent). • A method is implicitly passed the object on which it is invoked. • It may or may not return any data. • A method can operate on the data (instance variables) that is contained by the

corresponding class

class ClassName:

def method_name():

…………..

# Method_body

………………

Built-in String Methods

Python includes the following built-in methods to manipulate strings −

• capitalize() - Capitalizes first letter of string.

Example -

s="apkZube"

print(s.capitalize()) #Apkzube

output of above example :

Apkzube

• count() - The count() method returns the number of occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

Syntax :

str.count(sub, start = 0,end = len(string))

• sub − This is the substring to be searched. • start − Search starts from this index. First character starts from 0 index. By default search

starts from 0 index. • end − Search ends from this index. First character starts from 0 index. By default search

ends at the last index.

s="I Love Python Tutorial"

print(s.count('o')) #3

print(s.count('o',5)) #2

Page 45: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

print(s.count('t')) #2

print(s.count('t',2,9)) #0

output of above example :

3

2

2

0

• index() - The index() method determines if the string str occurs in string or in a substring of string, if the starting index beg and ending index end are given. This method is same as find(), but raises an exception if sub is not found.

syntax : str.index(str, beg ,end )

• str − This specifies the string to be searched. • beg − This is the starting index, by default its 0. • end − This is the ending index, by default its equal to the length of the string.

s="I Love Python Tutorial"

print(s.index('i'))

print(s.index('i',2))

print(s.index('Love'))

print(s.index('Love',7))

print(s.index('i',0,10))

output of above example :

19

0

19

2

Traceback (most recent call last):

File "main.py", line 16, in

print(s.index('Love',7)

ValueError: substring not found

• find() - The find() method determines if the string str occurs in string, or in a substring of string if the starting index beg and ending index end are given.

str.find(str, beg, end)

• str − This specifies the string to be searched. • beg − This is the starting index, by default its 0. • end − This is the ending index, by default its equal to the lenght of the string.

Page 46: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

s="I Love Python Tutorial"

print(s.find('I'))

print(s.find('I',2))

print(s.find('Love'))

print(s.find('t',2,10))

output of above example :

0

-1

2

9

• isalpha() - The isalpha() method checks whether the string consists of alphabetic characters only.

syntax - str.isalpha()

s="I Love Python 3 Tutorial"

print(s.isalpha())

s="Python" # No space & digit in this string

print(s.isalpha())

output of above example :

False

True

• isalnum() - The isalnum() method checks whether the string consists of alphanumeric characters.

str.isalnum()

s="I Love Python 3 Tutorial"

print(s.isalnum())

s="Python" # No space

print(s.isalnum())

output of above example :

False

True

• isdigit() - The method isdigit() checks whether the string consists of digits only.

Syntax - str.isdigit()

Page 47: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

s="I Love Python 3 Tutorial"

print(s.isdigit())

s="123" # Only digit in this string

print(s.isdigit())

output of above example :

False

True

• islower() - The islower() method checks whether all the case-based characters (letters) of the string are lowercase.

example :

s="I Love Python 3 Tutorial"

print(s.islower())

p="python"

print(p.islower())

output of above example :

False

True

• isnumeric() - The isnumeric() method checks whether the string consists of only numeric characters. This method is present only on unicode objects.

Note − Unlike Python 2, all strings are represented in Unicode in Python 3. Given below is an example illustrating it.

Example :

str = "apkzube97"

print (str.isnumeric())

str = "10121997"

print (str.isnumeric())

output of above example :

False

True

• isspace() - The isspace() method checks whether the string consists of whitespace

Page 48: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Example :

str = " "

print (str.isspace())

str = "apkzube"

print (str.isspace())

output of above example :

True

False

• istitle() - The istitle() method checks whether all the case-based characters in the string following non-casebased letters are uppercase and all other case-based characters are lowercase.

Explanation:

s1='I Love Python Tutorial'

print(s1.istitle())

s2='I love python 3'

print(s2.istitle())

output of above example :

True

False

• len() - The len() method returns the length of the string.

Example -

s1='I Love Python Tutorial'

print(len(s1))

s2='I love python 3'

print(len(s2))

output of above example :

22

15

• lower() - The method lower() returns a copy of the string in which all case-based characters have been lowercased.

Page 49: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Example -

s1='I Love Python Tutorial'

print(s1.lower())

s2='I love python 3'

print(s2.lower())

output of above example :

i love python tutorial

i love python 3

• upper() - The upper() method returns a copy of the string in which all case-based characters have been uppercased

Example -

s1='I Love Python Tutorial'

print(s1.upper())

s2='I love python 3'

print(s2.upper())

output of above example :

I LOVE PYTHON TUTORIAL

I LOVE PYTHON 3

• max() - The max() method returns the max alphabetical character from the string str.

Example -

s1='I Love Python Tutorial'

print(max(s1))

s2='apkzube'

print(max(s2))

output of above example :

y

z

• min() - The min() method returns the min alphabetical character from the string str.

Example -

s1='PythonTutorial'

Page 50: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

print(min(s1))

s2='apkzube'

print(min(s2))

output of above example :

P

a

• lstrip() - The lstrip() method returns a copy of the string in which all chars have been stripped from the beginning of the string (default whitespace characters).

• rstrip() - The rstrip() method returns a copy of the string in which all chars have been stripped from the end of the string (default whitespace characters).

str.lstrip([chars])

str.rstrip([chars]) Example -

s1=' I Love Python Tutorial '

print(s1.lstrip())

s2='###ApkZube###'

print(s2.lstrip('#'))

output of above example :

I Love Python Tutorial

ApkZube###

###ApkZube

• replace - The replace() method returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.

str.replace(old, new,[max])

Exmple -

• old − This is old substring to be replaced. • new − This is new substring, which would replace old substring. • max − If this optional argument max is given, only the first count occurrences are replaced.

s1='I Love Python Tutorial, I Love ApkZube, I Love Coding'

print(s1.replace('Love','Like'))

print(s1.replace('I','He',2))

output of above example :

Page 51: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

I Like Python Tutorial, I Like ApkZube, I Like Coding

He Love Python Tutorial, He Love ApkZube, I Love Coding

• split() - The split() method returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.

str.split(str="", num = string.count(str)).

Example -

• str − This is any delimeter, by default it is space. • num − this is number of lines to be made

s1='I Love Python,Java,Android,PHP,JavaScript'

print(s1.split(','))

print(s1.split(',',2)) #total 3 element in list

output of above example :

['I Love Python', 'Java', 'Android', 'PHP', 'JavaScript']

['I Love Python', 'Java', 'Android,PHP,JavaScript']

• swapcase() - The swapcase() method returns a copy of the string in which all the case-based characters have had their case swapped.

Example -

s1='I Love Python,Java,Android,PHP,JavaScript'

print(s1.swapcase())

output of above example :

i lOVE pYTHON,jAVA,aNDROID,php,jAVAsCRIPT

Python List

Python list is a data structure which is used to store various types of data.In Python, lists are mutable i.e., Python will not create a new list if we modify an element of the list.

It works as a container that holds other objects in a given order. We can perform various operations like insertion and deletion on list.A list can be composed by storing a sequence of different type of values separated by commas.

Page 52: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Python list is enclosed between square([])brackets and elements are stored in the index basis with starting index 0.

Syantax :

<list_name>=[value1,value2,value3,...,valuen];

list=['foo','bar','baz','quz','quux','corge']

print(list)

my_list=[1,2,3,4,4.5,'apkzube','X']

print(my_list)

A list can be created by putting the value inside the square bracket and separated by comma.

Output of above program :

['foo', 'bar', 'baz', 'quz', 'quux', 'corge']

[1, 2, 3, 4, 4.5, 'apkzube', 'X']

• Syntax to Access Python List

<list_name>[index]

we can use slice operator to access list element.

<list_name>[start : stop : step]

Example :

list=['foo','bar','baz','quz','quux','corge']

print(list[2])

print(list[4:6])

print(list[-4:-1])

print(list[1:5:2])

print(list[-1: :-1]) #reverse list

output of above example :

baz

['quux', 'corge']

['baz', 'quz', 'quux']

['bar', 'quz']

Page 53: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

['corge', 'quux', 'quz', 'baz', 'bar', 'foo']

Note: Internal Memory Organization:

List do not store the elements directly at the index. In fact a reference is stored at each index which subsequently refers to the object stored somewhere in the memory. This is due to the fact that some objects may be large enough than other objects and hence they are stored at some other memory location.

• Iteration of list : In Python, we can Iteration list using for loop is one of common way to Iteration list

list1=['a','b','c',1,2,3]

for x in list1 :

print(x)

output :

a

b

c

1

2

3

Python List Operations

Apart from creating and accessing elements from the list, Python allows us to perform various other operations on the list. Some common operations are given below

• Adding Python Lists

In Python, lists can be added by using the concatenation operator(+) to join two lists.

list1=['a','b','c']

list2=['x','y','z']

list3=list1+list2

print(list3)

output of above example :

['a', 'b', 'c', 'x', 'y', 'z']

Note: '+'operator implies that both the operands passed must be list else error will be shown.

let's run example :

list1=['a','b','c']

a='x'

print(list1+a)

Page 54: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

\ output of above example :

Traceback (most recent call last):

File "main.py", line 11, in

print(list1+a)

TypeError: can only concatenate list (not "str") to list

• Python Replicating lists

Replicating means repeating, It can be performed by using '*' operator by a specific number of time.

Example :

list1=['a','b','c']

print(list1*3)

output of above example :

['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']

• Python List Slicing

A subpart of a list can be retrieved on the basis of index. This subpart is known as list slice. This feature allows us to get sub-list of specified start and end index.

<list_name>[start : stop : step]

Example :

list=['foo','bar','baz','quz','quux','corge']

print(list[4:6])

print(list[-4:-1])

print(list[1:5:2])

print(list[-1: :-1]) #reverse list

\ output of above example :

['quux', 'corge']

['baz', 'quz', 'quux']

['bar', 'quz']

['corge', 'quux', 'quz', 'baz', 'bar', 'foo']

Note: If the index provided in the list slice is outside the list, then it raises an IndexError exception.

Python List Other Operations

Page 55: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Apart from above operations various other functions can also be performed on List such as Updating, Appending and Deleting elements from a List.

• Updating List - To update or change the value of particular index of a list, assign the value to that particular index of the List.

Example :

data1=[5,10,15,20,25]

print("Values of list are: " )

print(data1)

data1[2]="Multiple of 5"

print("Values of list are: ")

print(data1)

output of above example :

Values of list are:

[5, 10, 15, 20, 25]

Values of list are:

[5, 10, 'Multiple of 5', 20, 25]

• Appending List - Python provides, append() method which is used to append i.e., add an element at the end of the existing elements.

Example :

list1=['a','b','c']

list1.append(1.5)

list1.append('x')

list1.append(['y','z']) #append list into list as single object

print(list1)

output of above example :

['a', 'b', 'c', 1.5, 'x', ['y', 'z']]

• Deleting Elements - In Python, del statement can be used to delete an element from the list. It can also be used to delete all items from startIndex to endIndex.

Example :

list1=['a','b','c']

print("data in list : ",list1)

del(list1[2])

print("new data in list : ",list1)

output of above example :

Page 56: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

data in list : ['a', 'b', 'c']

new data in list : ['a', 'b']

Python Lists Function & Method

Python provides various Built-in functions and methods for Lists that we can apply on the list.

Following are the common list functions.

fun Description

min(list) It returns the minimum value from the list given.

max(list) It returns the largest value from the given list.

len(list) It returns number of elements in a list.

cmp(list1,list2) It compares the two list. No longer available in Python 3.

list(seq) It takes sequence types and converts them to lists

• min(list) - this method is used to get min value from the list. In Python3 lists element's type should be same otherwise compiler throw ypeError.

Example :

list1 = ['a','b','c']

list2 = [1,2,3]

list3=['a','b','c',1,2,3]

print(min(list1)) #a

print(min(list2)) #1

print(min(list3)) #typeError

output of above example :

a

1

File "main.py", line 15, in

print(min(list3))

TypeError: unorderable types: int() < str()

• max() - The max() method returns the elements from the list with maximum value.

Example :

Page 57: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

list1 = ['a','b','c']

list2 = [1,2,3]

list3=['a','b','c',1,2,3]

print(max(list1)) #c

print(max(list2)) #3

print(max(list3)) #typeEror

output of above example :

c

3

Traceback (most recent call last):

File "main.py", line 15, in

print(max(list3))

TypeError: unorderable types: int() > str()

• len() - The len() method returns the number of elements in the list.

Example :

list1 = ['a','b','c']

list2 = []

list3=['a','b','c',1,2,3]

print(len(list1))

print(len(list2))

print(len(list3))

output of above example :

3

0

6

• list() - The list() method takes sequence types and converts them to lists. This is used to convert a given tuple into list.

Tuple are very similar to lists with only difference that element values of a tuple can not be changed and tuple elements are put between parentheses instead of square bracket. This function also converts characters in a string into a list.

Example :

t= (1997, 'C++', 'Java', 'Python')

Page 58: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

list1 = list(t)

print ("List elements : ", list1)

str = "ApkZube"

list2 = list(str)

print ("List elements : ", list2)

output of above example :

List elements : [1997, 'C++', 'Java', 'Python']

List elements : ['A', 'p', 'k', 'Z', 'u', 'b', 'e']

Python includes the following list methods

method description

list.count(obj) Returns count of how many times obj occurs in list

list.extend(seq) Appends the contents of seq to list

list.append(obj) Appends object obj to list

list.index(obj) Returns the lowest index in list that obj appears

list.insert(index, obj)

Inserts object obj into list at offset index

list.pop(obj = list[-1])

Removes and returns last object or obj from list

list.remove(obj) Removes object obj from list

list.reverse() Reverses objects of list in place

list.sort([func]) Sorts objects of list, use compare func if given

• count() - The count() method returns count of how many times obj occurs in list.

Example :

list1 =[1,2,3,'a','b','c',1,2,3]

print(list1.count(1))

print(list1.count('b'))

print(list1.count(4))

output of above example :

2

1

0

Page 59: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

• append() - The append() method appends a passed obj into the existing list.

Example :

list1 =[1,2,3]

list1.append(4)

list1.append('apkzube')

list1.append(['a','b','c']) #append as single object

print(list1)

output of above example :

[1, 2, 3, 4, 'apkzube', ['a', 'b', 'c']]

• extend() - The extend() method appends the contents of seq to list.

list.extend([seq])

Example :

list1 =[1,2,3]

list1.extend([4])

list1.extend('apkzube')

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

print(list1)

output of above example :

[1, 2, 3, 4, 'a', 'p', 'k', 'z', 'u', 'b', 'e', 'a', 'b', 'c']

• index() - The index() method returns the lowest index in list that obj appears.

Example :

list1 =['apkzube','python','java','c++',1,2,3]

print("index of java : ",list1.index('java'))

print("index of 2 : ",list1.index(2))

output of above example :

index of java : 2

index of 2 : 5

• insert() - The insert() method inserts object obj into list at offset index.

list.insert(index, obj)

index − This is the Index where the object obj need to be inserted.

obj − This is the Object to be inserted into the given list.

Page 60: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Example :

list1 =['apkzube','python','java','c++',1,2,3]

list1.insert(3,'C#')

print(list1)

output of above example :

['apkzube', 'python', 'java', 'C#', 'c++', 1, 2, 3]

• pop() - The pop() method removes and returns last object or obj from the list.

list.pop(index)

index− This is an optional parameter, index of the object to be removed from the list. by default its -1 [last element]

Example :

list1 =['apkzube','python','java','c++',1,2,3]

list1.pop() # 3 is pop

print(list1)

list1.pop(2) # list[2] = "java" pop

print(list1)

output of above example :

['apkzube', 'python', 'java', 'c++', 1, 2]

['apkzube', 'python', 'c++', 1, 2]

• remove(obj) - object to be removed from the list.

Example :

list1 =['apkzube','python','java','c++',1,2,3]

list1.remove("java")

print(list1)

list1.remove(2)

print(list1)

output of above example :

['apkzube', 'python', 'c++', 1, 2, 3]

['apkzube', 'python', 'c++', 1, 3]

• reverse() - The reverse() method reverses objects of list in place.

Example :

Page 61: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

list1 =['apkzube','python','java','c++',1,2,3]

list1.reverse()

print(list1)

output of above example :

[3, 2, 1, 'c++', 'java', 'python', 'apkzube']

• sort() - The sort() method sorts objects of list, use compare function if given. but type of element in list should be same otherwise compiler throw typeError.

Example 1 :

list1 =[22,30,100,300,399]

list2=['z','ab','abc','a','b']

list1.sort()

list2.sort()

print(list1)

print(list2)

output of above example :

[22, 30, 100, 300, 399]

['a', 'ab', 'abc', 'b', 'z']

Example 2:

list3=['a','b',1,2]

list3.sort()

print(list3)

output of above example :

Traceback (most recent call last):

File "main.py", line 9, in

list3.sort()

TypeError: unorderable types: int() < str()

Python Tuple

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The main difference between the tuples and the lists is that the tuples cannot be changed unlike lists. Tuples use parentheses (), whereas lists use square [] brackets.

Tuple is similar to list. Only the difference is that list is enclosed between square bracket, tuple between parenthesis and List has mutable objects whereas Tuple has immutable objects.

Page 62: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

tuple=() #empty tuple

Example : Creating a tuple is as simple as putting different comma-separated values. Optionally, you can put these comma-separated values between parentheses also.

t1=('a','b',1,2,3.14,"ApkZube")

t2="a", "b", "c", "d"

#tuple contain other list and tuple

t3 =(1,2,3,['a','b','c'],('z',26))

print(t1)

print(t2)

print(t3)

output of above example :

('a', 'b', 1, 2, 3.14, 'ApkZube')

('a', 'b', 'c', 'd')

(1, 2, 3, ['a', 'b', 'c'], ('z', 26))

For a single valued tuple, there must be a comma at the end of the value.

t1=(5,)

print(t1)

output of above example :

(5,)

Accessing Values in Tuples

To access values in tuple, use the square brackets for slicing along with the index or indices to obtain the value available at that index. For example -

tuple[index]

slice operator syntax :

tuple[start : stop : step]

by default step is +1

t=(3,7,4,2)

Page 63: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

print(t[2])

print(t[1:3])

print(t[-4:-2])

print(t[-1 : : -1]) #start from -1 and step =-1 so its basicly return reverse tuple

output of above example :

4

(7, 4)

(3, 7)

(2, 4, 7, 3)

interation tuple using for loop is same as list :

t=("apkzube",'xyz',1,2,3)

for x in t:

print(x)

ouput :

apkzube

xyz

1

2

3

Tuple Operations

Python allows us to perform various operations on the tuple. Following are the common tuple operations.

• Adding Tuples

Tuple can be added by using the concatenation operator(+) to join two tuples this create new tuple.

Note: The new sequence formed is a new Tuple.

Example :

t1=(1,2,3)

t2=('x','y','z')

t3=t1+t2

print(t3)

output of above example :

(1, 2, 3, 'x', 'y', 'z')

Page 64: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

• Replicating Tuple

Replicating means repeating. It can be performed by using '*' operator by a specific number of time.

Example :

t1=(1,2,3)

t2=('x','y','z')

print(t1*2)

print(t2*3)

output of above example :

(1, 2, 3, 1, 2, 3)

('x', 'y', 'z', 'x', 'y', 'z', 'x', 'y', 'z')

• Updating Tuples

Tuples are immutable, which means you cannot update or change the values of tuple elements. You are able to take portions of the existing tuples to create new tuples as the following example -

t1 = (1, 2,3)

t2 = ('abc', 'xyz')

# Following action is not valid for tuples

# t1[0] = 4;

# So let's create a new tuple as follows

t3 = t1 + t2

print (t3)

output of above example :

(1, 2, 3, 'abc', 'xyz')

• Delete Tuple Elements

Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.To explicitly remove an entire tuple, just use the del statement. For example −

t = ('apkZube', 'python', 1, 2);

print (t)

del t;

print ("After deleting t :")

print (t)

Page 65: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

output of above example :

('apkZube', 'python', 1, 2)

After deleting t :

Traceback (most recent call last):

File "main.py", line 15, in

print (t)

NameError: name 't' is not defined

Built-in Tuple Functions

fun Description

cmp(t1, t2)

Compares elements of both tuples (py 2.x). In Python 3 the cmp built-in function was removed

len(tuple) Gives the total length of the tuple.

max(tuple) Returns item from the tuple with max value.

min(tuple) Returns item from the tuple with min value.

tuple(seq) Converts a sequence into tuple.

• len(tuple) - The len() method returns the number of elements in the tuple.

Example :

t1= (1,2,3,4,5)

t2 = ('x','y','z',[1,2],3)

print(len(t1))

print(len(t2))

output of above example :

5

5

• max(tuple) - The max() method returns the elements from the tuple with maximum value. Type of element should be same otherwise complier throw TypeError.

Example :

t1= (1,2,3,4,5)

t2 = ('x','y','z')

print(max(t1))

Page 66: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

print(max(t2))

output of above example :

5

z

• min(tuple) - The min() method returns the elements from the tuple with minimum value. Type of element should be same otherwise complier throw TypeError.

Example :

t1= (1,2,3,4,5)

t2 = ('x','y','z')

print(min(t1))

print(min(t2))

output of above example :

1

x

• tuple(seq) - The tuple() method converts a list of items into tuples.

Example :

s="apkzube"

t1=tuple(s)

list=[1,2,3]

t2=tuple(list)

print(t1)

print(t2)

output of above example :

('a', 'p', 'k', 'z', 'u', 'b', 'e')

(1, 2, 3)

Why should wee use Tuple? (Advantages of Tuple)

• Processing of Tuples are faster than Lists. • It makes the data safe as Tuples are immutable and hence cannot be changed. • Tuples are used for stringformatting.

Python Dictionary

Page 67: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Dictionary is an unordered set of key and value pair. It is a container that contains data, enclosed within curly braces.The pair i.e., key and value is known as item. The key passed in the item must be unique.

The key and the value is separated by a colon(:). This pair is known as item. Items are separated from each other by a comma(,). Different items are enclosed within a curly brace and this forms Dictionary.

dict = { } #empty dictionary

dict = {1:'Python',2:'Java',3:'C++'}

• Dictionary is mutable i.e., value can be updated. • Key must be unique and immutable. Value is accessed by key. Value can be updated while

key cannot be changed. • Dictionary is known as Associative array since the Key works as Index and they are decided

by the user.

Accessing Dictionary Values

Since Index is not defined, a Dictionary values can be accessed by their keys only. It means, to access dictionary elements we need to pass key associated to the value

syntax :

<dictionary_name>[key]

dict = {1:'Python',2:'Java',3:'C++','c': 'Gods language'}

print(dict[1])

print(dict['c'])

output :

Python

Gods language

iterate all elemnet using for loop for keys() method, keys() method return list of all keys in dictionary.

dict = {1:'Python',2:'Java',3:'C++','c': 'Gods language'}

print(dict.keys())

for x in dict.keys():

print(dict[x])

output :

dict_keys([1, 2, 3, 'c'])

Python

Java

C++

Page 68: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Gods language

If we attempt to access a data item with a key, which is not a part of the dictionary, we get an error as follows −

dict = {1:'Python',2:'Java',3:'C++','c': 'Gods language'}

print(dict[4])

output of above example :

Traceback (most recent call last):

File "main.py", line 9, in < module>

print(dict[4])

KeyError: 4

Updating Dictionary Elements

You can update a dictionary by adding a new entry or a key-value pair, modifyingan existing entry, or deleting an existing entry as shown in a simple example given below

dict = {1:'Python',2:'Java',3:'C++'}

dict[3]="C#"

dict[4]="PHP" #insert new value

print(dict)

output of above example :

{1: 'Python', 2: 'Java', 3: 'C#', 4: 'PHP'}

Deleting Dictionary Elements

del statement is used for performing deletion operation. An item can be deleted from a dictionary using the key only. To explicitly remove an entire dictionary, just use the del statement. Following is a simple example -

Example :

dict = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}

del dict[3] # remove entry with key 'Name'

print(dict)

dict.clear() # remove all entries in dict

print("dict : ",dict)

del dict # delete entire dictionary

print(dict[2])

output of above example :

Page 69: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

{1: 'Python', 2: 'Java', 4: 'PHP'}

dict : {}

Traceback (most recent call last):

File "main.py", line 17, in

print(dict[2])

TypeError: 'type' object is not subscriptable

Built-in Dictionary Functions and Methods

dictionary function

fun description

cmp(dict1, dict2)

No longer available in Python 3.

len(dict) Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.

str(dict) Produces a printable string representation of a dictionary

type(variable) Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.

dictionary methods

method description

dict.clear() Removes all elements of dictionary dict

dict.copy() Returns a shallow copy of dictionary dict

dict.fromkeys() Create a new dictionary with keys from seq and values set to value.

dict.get(key, default=None)

For key key, returns value or default if key not in dictionary

dict.has_key(key) Removed, use the in operation instead.

Page 70: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

dict.items() Returns a list of dict's (key, value) tuple pairs

dict.keys() Returns list of dictionary dict's keys

dict.setdefault(key, default = None)

Similar to get(), but will set dict[key] = default if key is not already in dict

dict.update(dict2) Adds dictionary dict2's key-values pairs to dict

dict.values() Returns list of dictionary dict's values

• len(dict) - The method len() gives the total length of the dictionary. This would be equal to the number of items in the dictionary.

Example :

dict = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}

print(len(dict))

output of above example :

4

• str(dict) - The method str() produces a printable string representation of a dictionary.

Example :

dict = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}

print(str(dict))

output of above example :

{1: 'Python', 2: 'Java', 3: 'C++', 4: 'PHP'}

• type() - The method type() returns the type of the passed variable. If passed variable is dictionary then it would return a dictionary type.

Example :

dict = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}

print(type(dict))

output of above example :

<class 'dict'>

Page 71: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

• clear() - The method clear() removes all items from the dictionary.

Example :

dict = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}

print(str(dict))

dict.clear()

print(str(dict))

output of above example :

{1: 'Python', 2: 'Java', 3: 'C++', 4: 'PHP'}

{}

• copy() - The method copy() returns a shallow copy of the dictionary.

Example :

dict1 = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}

dict2=dict1.copy()

print(dict2)

output of above example :

{1: 'Python', 2: 'Java', 3: 'C++', 4: 'PHP'}

• fromkeys() - The method fromkeys() creates a new dictionary with keys from seq and values set to value.

dict.fromkeys(seq[, value]))

Example :

seq = ('java', 'python', 'c++')

dict = dict.fromkeys(seq)

print ("New Dictionary : %s" % str(dict))

dict = dict.fromkeys(seq, 50)

print ("New Dictionary : %s" % str(dict))

output of above example :

New Dictionary : {'python': None, 'java': None, 'c++': None}

New Dictionary : {'python': 50, 'java': 50, 'c++': 50}

• itmes() - The method items() returns a list of dict's (key, value) tuple pairs.

Example :

Page 72: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

dict1 = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}

print(dict1.items())

output of above example :

dict_items([(1, 'Python'), (2, 'Java'), (3, 'C++'), (4, 'PHP')])

• keys() - The method keys() returns a list of all the available keys in the dictionary.

Example :

dict1 = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}

all_keys=dict1.keys()

print(all_keys)

output of above example :

dict_keys([1, 2, 3, 4])

• update() - The method update() adds dictionary dict2's key-values pairs in to dict. This function does not return anything.

dict.update(dict2)

Example :

dict1 = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}

dict2= {1: 'Python3',5:'C'} #update Python to Python3

dict1.update(dict2)

print(dict1)

output of above example :

{1: 'Python3', 2: 'Java', 3: 'C++', 4: 'PHP', 5: 'C'}

• value() - The method values() returns a list of all the values available in a given dictionary.

Example :

dict1 = {1:'Python',2:'Java',3:'C++',4 : 'PHP'}

values= dict1.values()

print(values)

output of above example :

dict_values(['Python', 'Java', 'C++', 'PHP'])

• setdefault() - The method setdefault() is similar to get(), but will set dict[key] = default if key is not already in dict.

dict.setdefault(key, default = None)

Page 73: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

• key − This is the key to be searched. • default − This is the Value to be returned in case key is not found.

output of above example :

dict={'emp_name':'Vishal','age':21,'emp_id':101}

dict.setdefault('company','apkzube')

print(dict['emp_name'])

print(dict['company'])

output of above example :

Vishal

ApkZube

Python Functions

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions

Defining a Function

1

Keyword def is used to start and declare a function. def specifies the starting of function block.

2

def is followed by function-name followed by parenthesis.

3

Parameters are passed inside the parenthesis. At the end a colon is marked.

4

Python code requires indentation (space) of code to keep it associate to the declared block.

5

The first statement of the function is optional. It is documentation string of function.

6

Following is the statement to be executed.

7

The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

Syntax

Page 74: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

def functionname( parameters ):

"function_docstring"

function_suite

return [expression]

By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.

Example :

def sum(a,b) :

c=a+b

return c

Calling a Function

To execute a function it needs to be called. This is called function calling. Function Definition provides the information about function name, parameters and the definition what operation is to be performed. In order to execute the function definition, we need to call the function.

Example :

def swap(x, y):

temp = x;

x = y;

y = temp;

return

x = 2

y = 3

swap(x, y) #call fun

print(x)

print(y)

output of above example :

2

3

Python Function return Statement

return[expression] is used to return response to the caller function. We can use expression with the return keyword. send back the control to the caller with the expression.In case no expression is given after return it will return None.In other words return statement is used to exit the function definition.

Page 75: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

def sum(a,b):

print("Adding the two values")

print("Printing within Function")

print(a+b)

return a+b

def msg():

print("Hello")

return

total=sum(10,20)

print('total : ',total)

msg()

print("Rest of code")

output of above example :

Adding the two values

Printing within Function

30

total : 30

Hello

Rest of code

Function Argument and Parameter

There can be two types of data passed in the function.

• The First type of data is the data passed in the function call. This data is called arguments. • The second type of data is the data received in the function definition. This data is

called parameters.

Arguments can be literals, variables and expressions. Parameters must be variable to hold incoming values.

Alternatively, arguments can be called as actual parameters or actual argumentsand parameters can be called as formal parameters or formal arguments.

# x is parameters or formal parameters or formal arguments.

def evenOdd( x ):

if (x % 2 == 0):

print("even")

else:

Page 76: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

print("odd")

# Driver code

evenOdd(2) # here 2 is argument or actual perameter

evenOdd(3) #3 is argument or actual perameter

output of above example :

even

odd

Function Arguments

You can call a function by using the following types of formal arguments −

• Required arguments • Keyword arguments • Default arguments • Variable-length arguments

• Required Arguments - Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition

def cube(x):

"This x a passed num value into this function, return cube of x"

y=x*x*x;

return y

# Now you can call cube function

z=cube(2) #required to pass argument

print(z)

output of above example :

8

• Keyword Arguments - Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.

This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.

def remainder(dividend,divisor):

x=dividend%divisor

Page 77: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

return x

rem = remainder(divisor = 3, dividend = 10) #keyword argument

print("remainder of 10/3 : ",rem)

output of above example :

remainder of 10/3 : 1

• Default Arguments - A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed

def emp_data(name,emp_id,age,company = "self employee"):

print("Details of: ",name)

print("Emp Id : ",emp_id)

print("Age : ",age)

print("Company : ",company)

#call emp_data fun

emp_data("Vishal",101,21,"ApkZube")

print("-----------------------")

emp_data("Jignesh",102,22)

output of above example :

Details of: Vishal

Emp Id : 101

Age : 21

Company : ApkZube

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

Details of: Jignesh

Emp Id : 102

Age : 22

Company : self employee

• Variable-length Arguments - You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.

Syntax for a function with non-keyword variable arguments is given below

def functionname([formal_args,] *var_args_tuple ):

Page 78: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

"function_docstring"

function_suite

return [expression]

An asterisk (*) is placed before the variable name that holds the values of allnonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example −

def printinfo( arg1, *vartuple ):

"This prints a variable passed arguments"

print ("Output is: ")

print (arg1)

for var in vartuple:

print (var)

return

# Now you can call printinfo function

printinfo( 10 )

printinfo( 70, 60, 50 )

output of above example :

Output is:

10

Output is:

70

60

50

Python Anonymous Function (Lambda Function)

These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.

• Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.

• An anonymous function cannot be a direct call to print because lambdarequires an expression.

• Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.

• Although it appears that lambdas are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is to stack allocation by passing function, during invocation for performance reasons.

Syntax :

lambda [arg1 [,arg2,.....argn]]:expression

Page 79: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Example :

#Normal Function definition is here

def square(x):

return x*x

# anonymous function

sqr = lambda x: x*x

#Calling square function

print("Square of number is",square(10)) #call normal function

print("Square of number is",sqr(2)) #call anonymous function

output of above example :

Square of number is 100

Square of number is 4

Scope of Variable

All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.

The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python −

• Global variables - Variable defined outside the function is called Global Variable. Global variable is accessed all over program thus global variable have widest accessibility.

• Local variables - Variables declared inside a function body is known as Local Variable. These have a local access thus these variables cannot be accessed outside the function body in which they are declared.

Example :

x=50

def print_data():

x=5

y=10

print("(x,y):(",x,",",y,")")

print_data() #(x,y):( 5 , 10 )

print("Global x :",x) #Global x : 50

print("Local y : ",y) #y is local veriable - throw NameError

Page 80: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

output of above example :

(x,y):( 5 , 10 )

Global x : 50

Traceback (most recent call last):

File "main.py", line 10, in

print("Local y : ",y) #y is local veriable - throw NameError

NameError: name 'y' is not defined

Python Input And Output

Python provides methods that can be used to read and write data. Python also provides supports of reading and writing data to Files.

print()

The simplest way to produce output is using the print statement where you can pass zero or more expressions separated by commas. This function converts the expressions you pass into a string and writes the result to standard output as follows −

print("Hello ApkZube")

x=150

print(x)

output of above example :

Hello ApkZube

150

Input from Keyboard :

In Python 3, raw_input() function is deprecated. Moreover, input() functions read data from keyboard as string, irrespective of whether it is enclosed with quotes ('' or "" ) or not.

• input() - The input([prompt]) function is equivalent to raw_input, except that it assumes that the input is a valid Python expression and returns the evaluated result to you.

def cube(x):

return x*x*x

a=int(input("Enter number :"))

print("cube of ",a," is ",cube(a))

output of above example :

Enter number :10

Page 81: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

cube of 10 is 1000

Python File Handling

Python provides the facility of working on Files. A File is an external storage on hard disk from where data can be stored and retrieved.

• Opening a File - Before working with Files you have to open the File. To open a File, Python built in function open() is used. It returns an object of File which is used with other functions. Having opened the file now you can perform read, write, etc. operations on the File.

• closing file - The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done. Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.

file_object = open(file_name [, access_mode][, buffering])

Here are parameter details −

• file_name − The file_name argument is a string value that contains the name of the file that you want to access.

• access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is an optional parameter and the default file access mode is read (r).

• buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).

Comparision operators in Python

mode description

r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.

rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.

r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file.

rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.

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

wb Opens a file for writing only in binary format. Overwrites the file if the file

Page 82: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

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

w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

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

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

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

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

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

The file Object Attributes

• file.closed - Returns true if file is closed, false otherwise. • file.mode - Returns access mode with which file was opened. • file.name - Returns name of the file.

Example :

# Open a file

data = open("data.txt", "wb")

print ("Name of the file: ", data.name)

print ("Closed or not : ", data.closed)

print ("Opening mode : ", data.mode)

data.close() #closed data.txt file

output of above example :

Page 83: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Name of the file: data.txt

Closed or not : False

Opening mode : wb

Reading and Writing Files

The file object provides a set of access methods to make our lives easier. We would see how to use read() and write()methods to read and write files.

• write() - The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text. The write() method does not add a newline character ('\n') to the end of the string .

file_object.write(string)

example :

# Open a file

data = open("data.txt", "w")

data.write("Welcome to ApkZube's Python Tutorial")

print("done")

data.close()

output of above example :

done

• read() - The read() method reads a string from an open file. It is important to note that Python strings can have binary data. apart from text data.

file_object.read([count])

Here, passed parameter is the number of bytes to be read from the opened file. This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file.

# Open a file

data = open("data.txt", "r+")

file_data = data.read(18) # read 18 byte only

full_data = data.read() #read all byte into file from last cursor

print(file_data)

print(full_data)

data.close()

output of above example :

Welcome to ApkZube

Page 84: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

's Python Tutorial

File Positions

The tell() method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file.

The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved.

If from is set to 0, the beginning of the file is used as the reference position. If it is set to 1, the current position is used as the reference position. If it is set to 2 then the end of the file would be taken as the reference position.

# Open a file

data = open("data.txt", "r+")

file_data = data.read(18) # read 18 byte only

print("current position after reading 18 byte :",data.tell())

data.seek(0) #here current position set to 0 (starting of file)

full_data = data.read() #read all byte

print(file_data)

print(full_data)

print("position after reading file : ",data.tell())

data.close()

output of above example :

current position after reading 18 byte : 18

Welcome to ApkZube

Welcome to ApkZube's Python Tutorial

position after reading file : 36

Renaming and Deleting Files

Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files.

To use this module, you need to import it first and then you can call any related functions.

Page 85: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

• rename() - The rename() method takes two arguments, the current filename and the new filename.

syntax ;

os.rename(current_file_name, new_file_name)

import os

os.rename('data.txt','my_data.txt')

output of above example :

• remove() - You can use the remove() method to delete files by supplying the name of the file to be deleted as the argument.

syntax :

os.remove(file_name)

import os

os.remove('my_data.txt')

my_data.txt file was deleted

Directories in Python

All files are contained within various directories, and Python has no problem handling these too. The os module has several methods that help you create, remove, and change directories

• mkdir() - You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method, which contains the name of the directory to be created.

syntax ;

os.mkdir("dir_name")

import os

os.mkdir('apkzube')

• chdir() - You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the directory that you want to make the current directory.

syntax :

os.chdir("newdir")

import os

Page 86: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

# Changing a directory to "/home/newdir"

os.chdir("/home/newdir")

• getcwd() - The getcwd() method displays the current working directory.

import os

print(os.getcwd())

output of above example :

/home

• rmdir() - The rmdir() method deletes the directory, which is passed as an argument in the method. Before removing a directory, all the contents in it should be removed

import os

# This would remove "/home/apkzube" directory.

os.rmdir( "/home/apkzube" )

result :

apkzube dir will be removed.

Python Module

Modules are used to categorize Pyhton code into smaller parts. A module is simply a Python file, where classes, functions and variables are defined.

Grouping similar code into a single file makes it easy to access. Have a look at below example.If the content of a book is not indexed or categorized into individual chapters, the book might have turned boring and hectic. Hence, dividing book into chapters made it easy to understand.

In the same sense python modules are the files which have similar code. Thus module is simplify a python code where classes, variables and functions are defined.

Advantage

• Reusability: Module can be used in some other python code. Hence it provides the facility of code reusability.

• Categorization: Similar type of attributes can be placed in one module.

Importing a Module

You can use any Python source file as a module by executing an import statement in some other Python source file. The import has the following syntax −

import module1[, module2[,... moduleN]

Exmple :

Page 87: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

The Python code for a module named a name normally resides in a file main.py. Here is an example of a simple module,

main.py −

import test

x = test.add(5,10)

print("x=",x)

test.py -

def add(a,b):

z=a+b

print('inside add func')

return z

output of above example : run main.py

inside add func

x=15

from...import Statement

Python's from statement lets you import specific attributes from a module into the current namespace. The from...import has the following syntax −

from modname import name1[, name2[, ... nameN]]

Example : we have fib.py with fib function now lets see how we can use fib module:

fib.py

# Fibonacci numbers module

def fib(n): # return Fibonacci series up to n

result = []

a, b = 0, 1

while b < n:

result.append(b)

a, b = b, a + b

return result

main.py

from fib import fib

print(fib(100))

output of above example :

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

Page 88: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

from...import * Statement

It is also possible to import all the names from a module into the current namespace by using the following import statement

from module_name import *

This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.

Executing Modules as Scripts

Within a module, the module’s name (as a string) is available as the value of the global variable __name__. The code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__".

Add this code at the end of your module

# Fibonacci numbers module

def fib(n): # return Fibonacci series up to n

result = []

a, b = 0, 1

while b < n:

result.append(b)

a, b = b, a + b

return result

if __name__ == "__main__":

f = fib(100)

print(f)

output of above example :

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

Built in Modules in Python:

There are many built in modules in Python. Some of them are as follows: math, random , threading , collections , os , mailbox , string , time , tkinter etc..

• math() - Using math module , you can use different built in mathematical functions.

math module Functions:

fun description

ceil(n) It returns the next integer number of the given number

Page 89: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

sqrt(n) It returns the Square root of the given number.

exp(n) It returns the natural logarithm e raised to the given number

floor(n) It returns the previous integer number of the given number.

log(n,baseto) It returns the previous integer number of the given number

pow(baseto, exp)

It returns baseto raised to the exp power.

sin(n) It returns sine of the given radian.

cos(n) It returns cosine of the given radian.

tan(n) It returns tangent of the given radian.

Example :

import math

a=4.6

print(math.ceil(a))

print(math.floor(a))

b=9

print(math.sqrt(b))

print(math.exp(3.0))

print(math.log(2.0))

print(math.pow(2.0,3.0))

print(math.sin(0))

print(math.cos(0))

print (math.tan(45))

output of above example :

5

4

3.0

20.085536923187668

0.6931471805599453

8.0

0.0

1.0

1.6197751905438615

Page 90: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

• Constants - The math module provides two constants for mathematical Operations:

• math.pi : Returns constant Pi = 3.14159... • math.e : Returns constant e= 2.71828...

import math

print("math.pi : ",math.pi)

print("math.e : ",math.e)

output of above example :

math.pi : 3.141592653589793

math.e : 2.718281828459045

• random - The random module is used to generate the random numbers. It provides the following two built in functions:

Comparision operators in Python

fun description

random() It returns a random number between 0.0 and 1.0 where 1.0 is exclusive.

randint(x,y) It returns a random number between x and y where both the numbers are inclusive.

Example :

import random

print(random.random())

print(random.randint(2,8))

output of above example : gives random output -

0.6856434575033108

3

Python Package

A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on.

Steps to create and import Package:

1

Create a directory, say Info

Page 91: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

2

Place different modules inside the directory. We are placing 3 modules msg1.py, msg2.py and msg3.py respectively and place corresponding codes in respective modules. Let us place msg1() in msg1.py, msg2() in msg2.py and msg3() in msg3.py.

3

Create a file __init__.py which specifies attributes in each module.

4

Import the package and use the attributes using package.

Have a look over the example:

1) Create directory -

import os

os.mkdir("Info")

2) Place different modules in package: (Save different modules inside the Info package)

msg1.py

def msg1():

print("This is msg1" )

msg2.py

def msg2():

print("This is msg2" )

msg3.py

def msg3():

print("This is msg3" )

3 ) create __init__.py file:

from msg1 import msg1

from msg2 import msg2

from msg3 import msg3

4) main.py

import Info

Info.msg1()

Info.msg2()

Info.msg3()

run main.py and we get following output :

This is msg1

Page 92: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

This is msg2

This is msg3

What is __init__.py file?

__init__.py is simply a file that is used to consider the directories on the disk as the package of the Python. It is basically used to initialize the python packages.

Python OOPs Concepts

Python is an object-oriented programming language. It allows us to develop applications using Object Oriented approach. In Python, we can easily create and use classes and objects.

here is a small introduction of Object-Oriented Programming (OOP) to help you -

• Class − A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.

• Object − A unique instance of a data structure that is defined by its class. An object comprises both data members (class variables and instance variables) and methods.

• Data member − A class variable or instance variable that holds data associated with a class and its objects.

• Class variable − A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables are not used as frequently as instance variables are.

• Function overloading − The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or arguments involved.

• Instance variable − A variable that is defined inside a method and belongs only to the current instance of a class.

• Inheritance − The transfer of the characteristics of a class to other classes that are derived from it.

• Polymorphism - Polymorphism is made by two words "poly" and "morphs". Poly means many and Morphs means form, shape. It defines that one task can be performed in different ways

• Encapsulation - Encapsulation is also the feature of object-oriented programming. It is used to restrict access to methods and variables. In encapsulation, code and data are wrapped together within a single unit from being modified by accident.

• Data Abstraction - Abstraction is used to hide internal details and show only functionalities. Abstracting something means to give names to things, so that the name captures the core of what a function or a whole program does.

• Instance − An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle.

• Instantiation − The creation of an instance of a class. • Method − A special kind of function that is defined in a class definition. • Operator overloading − The assignment of more than one function to a particular operator.

Python Object

Python is an object oriented programming language. So, its main focus is on objects unlike procedure oriented programming languages which mainly focuses on functions.

Page 93: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

In object oriented programming language, object is simply a collection of data(variables) and methods (functions) that act on those data.

Python Class

A class is a blueprint for the object. Let's understand it by an example:

Suppose a class is a prototype of a building. A building contains all the details about the floor, doors, windows, etc. we can make another buildings (as many as we want) based on these details. So building is a class and we can create many objects from a class.

An object is also called an instance of a class and the process of creating this object is known as instantiation.Python classes contain all the standard features of Object Oriented Programming. A python class is a mixture of class mechanism of C++ and Modula-3.

Creating Classes

The class statement creates a new class definition. The name of the class immediately follows the keyword class followed by a colon as follows −

class className:

'Optional class documentation string'

class_suite

• he class has a documentation string, which can be accessed via ClassName.__doc__. • The class_suite consists of all the component statements defining class members, data

attributes and functions.

Example :

class Student:

'Common base class for all students'

student_count=0

def __init__(self, name, id):

self.name = name

self.id = id

Student.student_count+=1

def printStudentData(self):

print ("Name : ", self.name, ", Id : ", self.id)

s=Student("vishal",101)

s.printStudentData()

output of above example :

Page 94: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

1) Name : vishal , Id : 101

Explanation:

• The variable student_countis a class variable whose value is shared among all the instances of a in this class. This can be accessed as Student.student_count from inside the class or outside the class.

• The first method __init__() is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class.

• You declare other class methods like normal functions with the exception that the first argument to each method is self. Python adds the self argument to the list for you; you do not need to include it when you call the methods.

Creating Instance Objects

To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts. Lets Create Studnet class object of above example :

std=Student('Jignesh','102')

Accessing Attributes

You access the object's attributes using the dot operator with object. Class variable would be accessed using class name as follows

class Student:

'Common base class for all students'

student_count=0

def __init__(self, name, id):

self.name = name

self.id = id

Student.student_count+=1

def printStudentData(self):

print ("Name : ", self.name, ", Id : ", self.id)

std1=Student("vishal",101)

std2=Student("Jignesh",102)

std3=Student("Ravi",103)

print("Total Student : ",Student.student_count)

std1.printStudentData()

std2.printStudentData()

Page 95: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

std3.printStudentData()

output of above example :

Total Student : 3

Name : vishal , Id : 101

Name : Jignesh , Id : 102

Name : Ravi , Id : 103

Instead of using the normal statements to access attributes, you can use the following functions..

• getattr(obj, name[, default]) − to access the attribute of object. • hasattr(obj,name) − to check if an attribute exists or not. • setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would be

created. • delattr(obj, name) − to delete an attribute.

Example :

hasattr(std1, 'id') # Returns true if 'id' attribute exists

getattr(std1, 'id') # Returns value of 'id' attribute

setattr(std1, 'id', 104) # Set attribute 'id' 104

delattr(std1, 'id') # Delete attribute 'id'

Built-In Class Attributes

Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute −

• __dict__ : Dictionary containing the class's namespace. • __doc__ : Class documentation string or none, if undefined. • __name__ : Class name. • __module__ : Module name in which the class is defined. This attribute is "__main__" in

interactive mode. • __bases__ : A possibly empty tuple containing the base classes, in the order of their

occurrence in the base class list.

let us try to access all these attributes

class Student:

'Common base class for all students'

student_count=0

def __init__(self, name, id):

self.name = name

self.id = id

Student.student_count+=1

Page 96: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

def printStudentData(self):

print ("Name : ", self.name, ", Id : ", self.id)

std1=Student("vishal",101)

std2=Student("Jignesh",102)

std3=Student("Ravi",103)

print("Total Student : ",Student.student_count)

print ("Student.__doc__:", Student.__doc__)

print ("StudentStudent.__name__:", Student.__name__)

print ("Student.__module__:", Student.__module__)

print ("Student.__bases__:", Student.__bases__)

print ("Student.__dict__:", Student.__dict__ )

output of above example :

Total Student : 3

Student.__doc__: Common base class for all students

StudentStudent.__name__: Student

Student.__module__: __main__

Student.__bases__: (<class 'object'>,)

Student.__dict__: {'__module__': '__main__', 'student_count': 3, '__dict__': <attribute '__dict__' of 'Student' objects>, 'printStudentData' :

<function Student.printStudentData at 0x7f51563f4158>, '__doc__': 'Common base class for all students', '__init__':

<function Student.__init__ at 0x7f51563f40d0>, '__weakref__': <attribute '__weakref__' of 'Student' objects>}

Python Constructors

A constructor is a special type of method(function) which is used to initialize theinstance members of the class. Constructor can be parameterized and non-parameterized as well. Constructor definition executes when we create object of the class. Constructors also verify that there are enough resources for the object to perform any start-up task.

Creating a Constructor

1

A constructor is a class function that begins with double underscore (_). The name of the constructor is always the same __init__().

2

Page 97: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

While creating an object, a constructor can accept arguments if necessary. When we create a class without a constructor, Python automatically creates a default constructor that doesn't do anything

3

Every class must have a constructor, even if it simply relies on the default constructor.

Example :

Let's create a class named ComplexNumber, having two functions __init__() function to initialize the variable and getData() to display the number properly.

class ComplexNumber:

def __init__(self,r=0,i=1):

self.real=r;

self.imag=i;

def getData(self):

print('{0}+{1}j'.format(self.real,self.imag))

c1=ComplexNumber(5,6)

c1.getData()

output :

5+6j

Parameterized Constructor

constructor with parameters is known as parameterized constructor.The parameterized constructor take its first argument as a reference to the instance being constructed known as self and the rest of the arguments are provided by the programmer.

class Student:

# Constructor - parameterized

def __init__(self, name):

print("This is parametrized constructor")

self.name = name

def show(self):

print("Hello",self.name)

student = Student("vishal")

student.show()

Page 98: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

output :

This is parametrized constructor

Hello vishal

Python Inheritance

Instead of starting from a scratch, you can create a class by deriving it from apre-existing class by listing the parent class in parentheses after the new class name.

The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in the child class. A child class can also override data members and methods from the parent.

Syntax :

class SubClassName (ParentClass1[, ParentClass2, ...]):

'Optional class documentation string'

class_suite

example :

class Parent: # define parent class

parentAttr = 100

def __init__(self):

print ("Calling parent constructor")

def parentMethod(self):

print ('Calling parent method')

def setAttr(self, attr):

Parent.parentAttr = attr

def getAttr(self):

print ("Parent attribute :", Parent.parentAttr)

class Child(Parent): # define child class

def __init__(self):

Page 99: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

print ("Calling child constructor")

def childMethod(self):

print ('Calling child method')

c = Child() # instance of child

c.childMethod() # child calls its method

c.parentMethod() # calls parent's method

c.setAttr(200) # again call parent's method

c.getAttr() # again call parent's method

output of above example :

Calling child constructor

Calling child method

Calling parent method

Parent attribute : 200

In a similar way, you can drive a class from multiple parent classes. multiple inheritance we will learn in next tutorial.

You can use issubclass() or isinstance() functions to check a relationships of two classes and instances.

• issubclass(sub, sup) boolean function returns True, if the given subclass sub is indeed a subclass of the superclass sup.

• isinstance(obj, Class) boolean function returns True, if obj is an instance of class Class or is an instance of a subclass of Class

Overriding Methods

You can always override your parent class methods. One reason for overriding parent's methods is that you may want special or different functionality in your subclass.

Example :

class Parent: # define parent class

def myMethod(self):

print ('Calling parent method')

class Child(Parent): # define child class

def myMethod(self):

print ('Calling child method')

Page 100: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

c = Child() # instance of child

c.myMethod() # child calls overridden method

output of above example :

Calling child method

Base Overloading Methods

The following table lists some generic functionality that you can override in your own classes −

Method Description

__init__ ( self [,args...] )

Constructor (with any optional arguments) Sample Call : obj = className(args)

__del__( self ) Destructor, deletes an object Sample Call : del obj

__repr__( self ) Evaluatable string representation Sample Call : repr(obj)

__str__( self )

Printable string representation Sample Call : str(obj)

__cmp__ ( self, x )

Object comparison Sample Call : cmp(obj, x)

Overloading Operators

Suppose you have created a Vector class to represent two-dimensional vectors. What happens when you use the plus operator to add them? Most likely Python will yell at you.

You could, however, define the __add__method in your class to perform vector addition and then the plus operator would behave as per expectation

Example :

class Vector:

def __init__(self, a, b):

self.a = a

Page 101: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

self.b = b

def __str__(self):

return 'Vector (%d, %d)' % (self.a, self.b)

def __add__(self,other):

return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)

v2 = Vector(5,-2)

print (v1 + v2)

output of above example :

Vector(7,8)

Data Hiding

An object's attributes may or may not be visible outside the class definition. You need to name attributes with a double underscore prefix, and those attributes then will not be directly visible to outsiders.

Example :

class JustCounter:

__secretCount = 0

def count(self):

self.__secretCount += 1

print (self.__secretCount)

counter = JustCounter()

counter.count()

counter.count()

print (counter.__secretCount)

output of above example :

1

2

Traceback (most recent call last):

File "test.py", line 12, in

print counter.__secretCount

Page 102: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

AttributeError: JustCounter instance has no attribute '__secretCount'

Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName. If you would replace your last line as following, then it works for you −

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

print (counter._JustCounter__secretCount)

output of above example :

1

2

2

Python Multilevel Inheritance

Multilevel inheritance is also possible in Python like other Object Oriented programming languages. We can inherit a derived class from another derived class, this process is known as multilevel inheritance. In Python, multilevel inheritance can be done at any depth

Example of Multilevel Inheritance :

class Animal:

def eat(self):

print('Eating...')

class Dog(Animal):

def bark(self):

print('Barking...')

class BabyDog(Dog):

def weep(self):

print('Weeping...')

d=BabyDog()

d.eat()

d.bark()

d.weep()

output :

Page 103: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Eating...

Barking...

Weeping...

Python Multiple Inheritance

Like C++, a class can be derived from more than one base classes in Python. This is called multiple inheritance. In multiple inheritance, the features of all the base classes are inherited into the derived class. The syntax for multiple inheritance is similar to single inheritance.

Example :

class ClassA:

pass

class ClassB:

pass

class ClassC(ClassA,ClassB):

pass

let's see example :

class First(object):

def __init__(self):

super(First, self).__init__()

print("first")

class Second(object):

def __init__(self):

super(Second, self).__init__()

print("second")

class Third(Second, First):

def __init__(self):

super(Third, self).__init__()

print("third")

Page 104: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

Third(); #call Third class constructor

output :

first

second

third

Why super () keyword

The super() method is most commonly used with __init__ function in base class. This is usually the only place where we need to do some things in a child then complete the initialization in the parent.

class Child(Parent):

def __init__(self, stuff)

self.stuff = stuff

super(Child, self).__init__()

Private members of parent class

We don’t always want the instance variables of the parent class to be inherited by the child class i.e. we can make some of the instance variables of the parent class private, which won’t be available to the child class. We can make an instance variable by adding double underscores before its name. For example,

# Python program to demonstrate private members

# of the parent class

class C(object):

def __init__(self):

self.c = 21

# d is private instance variable

self.__d = 42

class D(C):

def __init__(self):

self.e = 84

C.__init__(self)

object1 = D()

# produces an error as d is private instance variable

print(D.d)

output of above example :

Traceback (most recent call last):

Page 105: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

File "main.py", line 16, in <module>

print(D.d)

AttributeError: type object 'D' has no attribute 'd'

Python Polymorphism

Polymorphism is based on the greek words Poly (many) and morphism(forms). We will create a structure that can take or use many forms of objects.

Example of inbuilt polymorphic functions :

# len() being used for a string

print(len("geeks"))

# len() being used for a list

print(len([10, 20, 30]))

output of above example :

5

3

Method Overloading

python does not supports method overloading. We may overload the methods but can only use the latest defined method.

# First product method.

# Takes two argument and print their

# product

def product(a, b):

p = a * b

print(p)

# Second product method

# Takes three argument and print their

# product

def product(a, b, c):

p = a * b*c

print(p)

output of above example :

Page 106: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

100

Overriding Methods

You can always override your parent class methods. One reason for overriding parent's methods is that you may want special or different functionality in your subclass.

Example :

class Parent: # define parent class

def myMethod(self):

print ('Calling parent method')

class Child(Parent): # define child class

def myMethod(self):

print ('Calling child method')

c = Child() # instance of child

c.myMethod() # child calls overridden method

output of above example :

Calling child method

Exceptions Handling

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.

When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits.

• Handling an exception

If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.

try:

You do your operations here

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

except ExceptionI:

If there is ExceptionI, then execute this block.

except ExceptionII:

Page 107: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

If there is ExceptionII, then execute this block.

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

else:

If there is no exception then execute this block.

With our “Hello, World!” program written, we are ready to run the program. We’ll use the python3 command along with the name of our program file. Let’s run the program:

• A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.

• You can also provide a generic except clause, which handles any exception. • After the except clause(s), you can include an else-clause. The code in the else-block

executes if the code in the try: block does not raise an exception. • The else-block is a good place for code that does not need the try: block's protection.

Example :

try:

fh = open("testfile", "w")

fh.write("This is my test file for exception handling!!")

except IOError:

print ("Error: can\'t find file or read data")

else:

print ("Written content in the file successfully")

fh.close()

output of above example :

Written content in the file successfully

The except Clause with No Exceptions

You can also use the except statement with no exceptions defined as follows

try:

You do your operations here

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

except:

If there is any exception, then execute this block.

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

else:

If there is no exception then execute this block

Page 108: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except statement is not considered a good programming practice though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur.

The except Clause with Multiple Exceptions

You can also use the same except statement to handle multiple exceptions as follows −

try:

You do your operations here

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

except(Exception1[, Exception2[,...ExceptionN]]]):

If there is any exception from the given exception list,

then execute this block.

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

else:

If there is no exception then execute this block.

The try-finally Clause

You can use a finally: block along with a try: block. The finally: block is a place to put any code that must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this −

try:

You do your operations here;

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

Due to any exception, this may be skipped.

finally:

This would always be executed.

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

Note − You can provide except clause(s), or a finally clause, but not both. You cannot use else clause as well along with a finally clause.

Example :

try:

fh = open("testfile", "w")

fh.write("This is my test file for exception handling!!")

finally:

print ("Error: can\'t find file or read data")

fh.close()

Page 109: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

If you do not have permission to open the file in writing mode, then this will produce the following result −

Error: can't find file or read data

Argument of an Exception

An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows −

Example :

# Define a function here.

def temp_convert(var):

try:

return int(var)

except ValueError as Argument:

print ("The argument does not contain numbers\n", Argument)

# Call above function here.

temp_convert("xyz")

output of above example :

The argument does not contain numbers

invalid literal for int() with base 10: 'xyz'

Raising an Exception

You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as follows

raise [Exception [, args [, traceback]]]

Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None.

The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception.

Example :

def functionName( level ):

if level < 1:

raise Exception(level)

# The code below to this would not be executed

Page 110: theories of this language and the second volume includes exercises of this language.dl.ketabesabz.com/ebooks3/up/python-tutorial-1_[www... · 2020. 8. 17. · Picalo etc. 11. Applications

# if we raise the exception

return level

try:

l = functionName(-10)

print ("level = ",l)

except Exception as e:

print ("error in level argument",e.args[0])

output of above example :

error in level argument -10

Writing the “Hello, World!” Program

Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.

Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError. This is useful when you need to display more specific information when an exception is caught.

In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to create an instance of the class Networkerror.

class Networkerror(RuntimeError):

def __init__(self, arg):

self.args = arg

So once you have defined the above class, you can raise the exception as follows −

try:

raise Networkerror("Bad hostname")

except Networkerror,e:

print(e.args)