Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

Basic python programming

Unit - i
Introduction to object oriented programming (oop):

Computer programming and programming languages:

A program is a collection of instructions that is a computer how to solve a particular


problem. Programming is the process of taking an algorithm and writing it in a particular
programming language so that it can be executed by a computer.

A programming language is a language specifically designed to express


communications that can be performed by a computer programming language are used to
create programs that control the behavior of a system to express algorithms or as a mode of
human communication.

Irrespective of the language that a programmer uses a program written using any
programming language has to be converted into machine language so that the computer can
understand it there are two ways to do this compile the program or interpret the program:

Selecting the perfect language for a particular application at hand is a daunting task.
The selection of language for writing a program depends on the following factors

➢ The type of computer hardware and software on which the program is to be executed
➢ The type of program
➢ The expertise and availability of the programmers
➢ Features to write the application it should have built-in features that support the
development of software that are reliable and less prone to cash lower development
and maintenance
➢ Cost stability and capability to support even more than the expected simultaneous
users
➢ Elasticity of a language that implies the east with which new features or functions can
be added to the existing program
➢ Portability
➢ Better speed of development that include the time it takes to write a code time taken
to find a solution to the problem at hand time taken to find the box available to of
development tools experience and skill of the programmers and testing regime.
Generations of programming languages

The concept of generations of programming languages also known as levels is closely


connected to the advances in technology the five generations of programming languages
include machine language, assembly language, high level language, very high-level language,
and 5th generation language.

First generation (1GL): Machine language

A first-generation programming language is a machine-level programming language.


The instructions in 1GL are made of binary numbers, represented by 1s and 0s. This makes
the language suitable for the understanding of the machine but far more difficult to interpret
and learn by the human programmer. This language is machine dependent. They could be
directly executed on the central processing unit (CPU) if the computer, and there is no need to
employ a compiler or assembler to translate from a high-level language or assembly language
to the machine code.

Advantages of Machine Language:


1. It is directly understood by the computer. That’s why it is possible to communicate with
computers directly.
2. The main advantage is that program of machine language run very fast because no translator
program is required for the CPU.
3. Program written in machine language needs less memory to run.
Disadvantages of Machine Language:
1. It is very difficult to learn and program in machine language as only 0 &1 are used.
2. A program written in machine language is almost impossible to understand by human.
3. It takes more time to write a program in machine language and It is difficult to debug the
program.
4. This language is machine dependent. That means a program written for one computer might
not run-in other computers with different hardware configuration.
5. The programmer has to know details of hardware to write a program in machine language.
6. All operation codes have to be remembered.
7. All memory addresses have to be remembered.

Second Generation Languages (2GL): Assembly language


The language in which different mnemonics are used to write a program is called
assembly language. In this language alphanumeric symbols are used to write programs instead
of 0’s and l’s.
These alphanumeric symbols are known as mnemonic codes and can combine in a
maximum of five-letter combinations e.g., ADD for addition, SUB for subtraction, DIV for
division, MUL for multiplication etc. Because of this feature, assembly language is also known
as ‘Symbolic Programming Language.
Assembly language is second-generation language and low-level language. It was
mostly used programming language for second generation computers. Although this language
is more developed than machine language, it is not equivalent to high-level language, so
assembly language is called low-level language.
A translator program is required to translate the Assembly Language to machine
language. This translator program is called `Assembler’.
Advantages of Assembly Language:
1. Assembly language is easier to understand and write a program as compared to machine
language.
2. It saves a lot of time and effort to write a program.
3. It is easier to modify program instructions than machine language.
4. It is easier to debug a program than machine language.
Disadvantages of Assembly Language:
1. One of the major disadvantages is that assembly language is machine dependent. A program
written for one computer might not run-in other computers with different hardware
configuration.
2. Since it is machine dependent, the programmer also needs to understand the hardware.
3. It needs translator program.

Third Generation Language(3GL): High Level Language:

High-level programming languages mean that the languages are easily understandable
and close to human language. These languages are similar to human language like English and
machine independent that’s why these languages are called high level programming language.

These languages are easy to understand for people but computers cannot understand
directly. So, it needs to convert the program written in high level language into machine
language using a translator program. These languages are called third generation language.
Some examples of high-level programming languages are Fortran, Basic, Pascal,
Cobol, C, C++, Visual Basic, Java, Oracle, Python etc.
Advantages of High-Level Language:
1. High level languages are programmer friendly. They are easy to learn as well as easy to write
and maintain the program.
2. Less error prone, easy to find bug and debug.
3. The programmer need not to know details of hardware to write a program.
4. It is machine independent language.
5. High level programming results in better programming productivity.
Disadvantages of High-Level Language:
1. The problem with high-level languages is that they cannot communicate directly with the
hardware’s or computers.
2. It needs translator program and It takes additional translation times to translate the source to
machine code.
3. High level programs are comparatively slower than low level programs.
4. Compared to low level programs, they need more memory space to run.
Fourth Generation Language(4GL):
4GL stands for Fourth Generation Language. Fourth Generation Language is also called
very high-level programming language. Fourth generation programming languages are the one
which are closer to human languages rather than the high level or middle level programming
languages. 4GLs are associated with databases and data processing, allowing the efficient
development of business-oriented systems.
Most fourth-generation languages are non-procedural or functional languages that
encourage users and programmers to specify the results they want, while the computer
determines the sequence of instructions that will accomplish those results. Thus, fourth-
generation languages have helped simplify the programming process. Examples of 4GLs
are SQL, Oracle etc.
Fifth Generation Language(5GL):

5GL stands for Fifth Generation Language. Fifth Generation Language is also called
natural language. Fifth generation languages are designed to make the computer solve a given
problem without the programmer. Fifth-generation languages are used mainly in artificial
intelligence research and to manufacture artificial intelligence (AI) based devices or machines.
Intelligent Compiler is used to translate the program written in 5GL to machine language.
Examples of 5GLs PROLOG (PROgramming LOGic), LISP, Mercury etc.

programming paradigms

A programming paradigm is a fundamental style of programming that defines how the


structure and basic elements of a computer program will be built. The style of writing programs
and the set of capabilities and limitations that a particular programming language has depends
on the programming paradigm it supports. These paradigms, in sequence of their application,
can be classified as follows:

◆ Monolithic programming—emphasizes on finding a solution


◆ Procedural programming—lays stress on algorithms
◆ Structured programming—focuses on modules
◆ Object-oriented programming—emphasizes on classes and objects
◆ Logic-oriented programming—focuses on goals usually expressed in predicate calculus
◆ Rule-oriented programming—makes use of ‘if-then else’ rules for computation
◆ Constraint-oriented programming—utilizes invariant relationships to solve a problem.

Each of these paradigms has its own strengths and weaknesses and no single paradigm can
suit all applications.

Monolithic Programming

Programs written using monolithic programming languages such as assembly language


and BASIC consist of global data and sequential code. As the name suggests, monolithic
programs have just one program module as such programming languages do not support the
concept of subroutines. Therefore, all the actions required to complete a particular task are
embedded within the same application itself. This not only makes the size of the program large
but also makes it difficult to debug and maintain. For all these reasons, monolithic
programming language is used only for very small and simple applications where reusability
is not a concern.

Procedural Programming

In procedural languages, a program is divided into subroutines that can access global
data. To avoid repetition of code, each subroutine performs a well-defined task. A subroutine
that needs the service provided by another subroutine can call that subroutine.
Advantages:

✓ The only goal is to write correct programs.


✓ Programs are easier to write as compared to monolithic programming.

Disadvantages:

✓ No concept of reusability
✓ Requires more time and effort to write programs
✓ Programs are difficult to maintain
✓ Global data is shared and therefore may get altered (mistakenly)

Structured Programming:

Structured programming was basically defined to be used in large programs that require
large development team to develop different parts of the same program. Structured
programming employs a top-down approach in which the overall program structure is broken
down into separate modules. In structured programming, the program flow follows a simple
sequence Besides sequential flow, structured programming also supports selection and
repetition as mentioned here.

Selection allows for choosing any one of a number of statements to execute, based on
the current status of the program. Selection statements contain keywords such as ‘if’, ‘then’,
‘end if’, or ‘switch’ that help to identify the order as a logical executable.

In repetition, a selected statement remains active until the program reaches a point
where there is a need for some other action to take place. It includes keywords such as ‘repeat’,
‘for’, or ‘do… until’. Essentially, repetition instructs the program as to how long it needs to
continue the function before requesting further instructions.

Object-oriented Programming (OOP)

With the increase in size and complexity of programs, there was a need for a new
programming paradigm that could help to develop maintainable programs. To implement this,
the flaws in previous paradigms had to be corrected. Consequently, OOP was developed.
monolithic, procedural, and structured programming paradigms are task-based as they focus
on the actions the program should accomplish. However, the object-oriented paradigm is task-
based and databased. In this paradigm, all the relevant data and tasks are grouped together in
entities known as objects. The striking features of OOP include the following:

• Programs are data centered.


• Programs are divided in terms of objects and not procedures.
• Functions that operate on data are tied together with the data.
• Data is hidden and not accessible by external functions.
• New data and functions can be easily added as and when required.
• Follows a bottom-up approach for problem solving.

Features of object-oriented programming:

Object Oriented programming brings programming close to real life, as we are always dealing
with an object, performing operations on it, using it's methods and variables etc. OOP is
designed in such a way that one should focus on an object while programming and not the
procedure. It is necessary to understand some of the concepts used extensively in object-
oriented programming. These include:

• Objects • Classes

• methods • Inheritance

• messing passing • Data abstraction and encapsulation

• Polymorphism • container ship

• delegation • reusability

Classes

A class is a code template for creating objects, we can think of it as a blueprint. It


describes the possible states and behaviors that every object of a certain type could have. For
instance, if we say that “every employee will have a name and salary, and can be given a raise”,
then we just defined a class!

class employee ():

def __init__(self, name,age,id,salary): //creating a function

self.name = name // self is an instance of a class


self.age = age

self.salary = salary

self.id = id

Class creates a user-defined data structure, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class.

Objects

An object is a real-life entity. An object is the collection of various data and functions that
operate on those data. An object contains the following properties.

o State - The attributes of an object represent its state. It also reflects the properties of an
object.
o Behaviour - The method of an object represents its behaviour.
o Identity - Each object must be uniquely identified and allow interacting with the other
object.

emp_1=employee('aayushi','johari',350000)

emp_2=employee('test','test',100000)

print(emp_1.email)

print(emp_2.email)

Methods

A method in object-oriented programming is a procedure associated with a class. A


method defines the behavior of the objects that are created from the class. Another way to say
this is that a method is an action that an object is able to perform. The association between
method and class is called binding. 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.

• The method is implicitly used for an object for which it is called.


• The method is accessible to data that is contained within the class.

message passing

A request for an object to perform one of its operations is called a message. Operation
means method/function. A message cannot go automatically it creates an interface, which
means it creates an interface for an object. The interface provides the abstraction over the
message means hide the implementation. So, we get to know, An interface is a set of
operations that a given object can perform. All communication between objects is done via
message is called message passing, as people exchange information similarly the sending
and receiving of information by the object is said to be message passing, to make possible
message passing the following things have to be followed to be done:

• We have to create classes that define objects and its behaviour.


• Then Creating the objects from class definitions
• Calling and connecting the communication among objects

Inheritance

Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides


code reusability to the program because we can use an existing class to create a new class
instead of creating it from scratch. In inheritance, the child class acquires the properties and
can access all the data members and functions defined in the parent class. A child class can
also provide its specific implementation to the functions of the parent class.

Following are the benefits of inheritance.

1. Code reusability- we do not have to write the same code again and again; we can just
inherit the properties we need in a child class.
2. It represents a real-world relationship between parent class and child class.
3. It is transitive in nature. If a child class inherits properties from a parent class, then all
other sub-classes of the child class will also inherit the properties of the parent class.

Polymorphism
Polymorphism is a concept of object-oriented programming, which means multiple
forms or more than one form. Polymorphism enables using a single interface with input of
different datatypes, different class or may be for different number of inputs.

For example, Polymorphism in ‘+’ operator


• You might have used the ‘+’ arithmetic python operator multiple times in your
programs.
• And chances are, you might have used it with multiple different types.
• This right here is an implementation of polymorphism in Python.
• You use the same + symbol whether you want to add two integers, or concatenate
two strings, or extend two lists.
• The + operator acts differently depending on the type of objects it is operating
upon.
Abstraction
Abstraction in Java and Python is a programming methodology in which details of the
programming codes are hidden away from the user, and only the essential things are
displayed to the user. Abstraction is concerned with ideas rather than events. It’s like a user
running a program (Web Browser) without seeing the background codes. Abstraction is
achieved in either Abstract classes or interface in Java and Python. NetBeans and Eclipse
IDE implements abstraction for Java while Django implements abstraction for Python.
Encapsulation
This is a programming style where implementation details are hidden. It reduces
software development complexity greatly. With Encapsulation, only methods are exposed.
The programmer does not have to worry about implementation details but is only concerned
with the operations. For example, if a developer wants to use a dynamic link library to
display date and time, he does not have to worry about the codes in the date and time class
rather he would simply use the data and time class by using public variables to call it up. In
essence encapsulation is achieved in Python and Java by creating Private variables to define
hidden classes in and then using public variables to call them up for use. With this approach,
a class can be updated or maintained without worrying about the methods using them. If you
are calling up a class in ten methods and you need to make changes, you don’t have to update
the entire methods rather you update a single class. Once the class is changed, it
automatically updates the methods accordingly. Encapsulation also ensures that your data is
hidden from external modification. Encapsulation is also known as Data-Hidden.
Containership
Containership Is the ability of a class to contain objects of one of more classes as
member data. le. g. Class One an have object of class Two as its data member. This would
allow the object of class One to call the public functions of class Two. Here Class One
becomes the container, whereas class Two becomes the contained class. Containership is also
called composition because class One is composed of class Two. It represents ‘has-a’
relationship.
Delegation
In delegation more than one object is involved in handling request. The object that
receives the request for a service, delegate it to another object called its delegate. Delegation
is based on the property that a complex object is made of several simpler objects. e. g. our
body is made up of brain, heart, hand, eyes etc. the functioning of the whole body as a system
rest on correct functioning of the parts it is composed of. In delegation, they have ‘has-a’
relationship.
Reusability
In OOP, The concept of inheritance provide the idea of reusability. This means that
we can add additional features to an existing class without modifying it. This is possible by
deriving a new class from the existing one. The new class will have the combined features of
both the classes. The real appeal and power of the inheritance mechanism is that it allows the
programmer to reuse a class that is almost, but not exactly, what he wants, and to tailor the
class in such a way that it does not introduce any undesirable side effects into the rest of the
classes.
Merits and demerits of object-oriented programming language

OOP stands for object-oriented programming. It offers many benefits to both the
developers and the users. Object-orientation contributes to the solution of many problems
associated with the development and quality of software products. The new technology
promises greater programmer productivity, better quality of software and lesser maintenance
cost. The primary advantages are:

Merits:

• Through inheritance, we can eliminate redundant code and extend the use of existing
classes.
• We can build programs from the standard working modules that communicate with one
another, rather than having to start writing the code from scratch. This leads to saving
of development time and higher productivity.

• The principle of data hiding helps the programmer to build secure programs that cannot
be invaded by code in other parts of the program.

• It is possible to have multiple objects to coexist without any interference.

• It is possible to map objects in the problem domain to those objects in the program.

• It is easy to partition the work in a project based on objects.

• The data-centered design approach enables us to capture more details of a model in an


implementable form.

• Object-oriented systems can be easily upgraded from small to large systems.

• Message passing techniques for communication between objects make the interface
descriptions with external systems much simpler.

• Software complexity can be easily managed.

• Polymorphism can be implemented i.e. behavior of functions or operators or objects can


be changed depending upon the operations.

Demerits:

· It requires more data protection.

· Inadequate for concurrent problems

· Inability to work with existing systems.

· Compile time and run time overhead.

· Unfamiliraity causes training overheads.

Basics of Python Programming


Python is an interpreted, object-oriented, high-level programming language with
dynamic semantics. Its high-level built in data structures, combined with dynamic typing and
dynamic binding, make it very attractive for Rapid Application Development, as well as for
use as a scripting or glue language to connect existing components together. Python's simple,
easy to learn syntax emphasizes readability and therefore reduces the cost of program
maintenance. Python supports modules and packages, which encourages program modularity
and code reuse. The Python interpreter and the extensive standard library are available in
source or binary form without charge for all major platforms, and can be freely distributed.
History of Python Programming:
Guido van Rossum is the author of Python, an interpreted, interactive object-oriented
programming language. In the late 1980s, Van Rossum began work on Python at
the National Research Institute for Mathematics and Computer Science in the
Netherlands, or Centrum voor Wiskunde en Informatica (CWI) as it is known in Dutch.
Python Implementation started on December, 1989 and reached version 1.0 in
January 1994. Python 2.0 was released on October 16, 2000 , with many major new features,
including a cycle-detecting garbage collector (in addition to reference counting) for memory
management and support for Unicode. However, the most important change was to the
development process itself, with a shift to a more transparent and community-backed process.
Python 3.0, a major, backwards-incompatible release, was released on December 3,
2008 after a long period of testing. Many of its major features have also been backported to
the backwards-compatible, while by now unsupported, Python 2.6 and 2.7.

he following table lists all the important versions of Python:

Version Release Date Important Features


Python 0.9.0 February • Classes with inheritance exception handling
1991 • Functions
• Modules

Python 1.0 January 1994 • Functional programming tools (lambda, map, filter and reduce).
• Support for complex numbers.
• Functions with keyword arguments

Python 2.0 October 2000 • List comprehension.


Version Release Date Important Features
Python 2.7.0 July 2010 • Cycle-detecting garbage collector.
- EOL - Jan • Support for Unicode. Unification of data types and classes
2020
Python 3 December • Backward incompatible.
2008 • print keyword changed to print() function
Python 3.6 December • raw_input() function depreciated
2016 • Unified str/Unicode types.

Python 3.6.5 March 2018 • Utilities for automatic conversion of Pytthon 2.x code

Python 3.7.0 May 2018 • New C API for thread-local storage


• Built-in breakpoint()
• Data classes
• Context variables
• More..

Python 3.8 October 2019 • Assignment Expression


• Positional-only parameters
• Parallel filesystem cache for compiled bytecode files
• More..

Python 3.9 October 2020 • Dictionary Merge & Update Operators


- Current • New removeprefix() and removesuffix() string methods
Version • Builtin Generic Types
• More..

Why the Name Python?


There is a fact behind choosing the name Python. When he began implementing
Python, Guido van Rossum was also reading the published scripts from Monty Python a BBC
comedy series from the 1970s. Van Rossum thought he needed a name that was short, unique,
and slightly mysterious, so he decided to call the language Python.
Features of python
1. Easy
When we say the word ‘easy’, we mean it in different contexts.
a. Easy to Code
Python is very easy to code as compared to other popular languages like Java and
C++. Anyone can learn Basic Python syntax in just a few hours. Thus, it is programmer-
friendly.
b. Easy to Read
Being a high-level language, Python code is quite like English. Looking at it, you can
tell what the code is supposed to do. Also, since it is dynamically-typed, it mandates
indentation. This aids readability.
2. Expressive
First, let’s learn what is expressiveness. Suppose we have two languages A and B, and
all programs that can be made in A can be made in B using local transformations. However,
there are some programs that can be made in B, but not in A, using local transformations.
Then, B is said to be more expressive than A.

3. Free and Open-Source


Firstly, Python is freely available. You can download it from the Python Official
Website. Secondly, it is open-source. This means that its source code is available to the
public. You can download it, change it, use it, and distribute it. This is called
FLOSS(Free/Libre and Open Source Software).
4. High-Level
Python is a high-level language. This means that as programmers, we don’t need to
remember the system architecture. Also, we need not manage memory. This makes it more
programmer-friendly and is one of the key python features.
5. Portable
Let’s assume you’ve written a Python code for your Windows machine. Now, if you
want to run it on a Mac, you don’t need to make changes to it for the same. In other words,
you can take one code and run it on any machine. This makes Python a portable language.
6. Interpreted
If you’re familiar with any languages like C++ or Java, you must first compile it, and
then run it. But in Python, there is no need to compile it. Internally, its source code is
converted into an immediate form called bytecode. So, all you need to do is to run your
Python code without worrying about linking to libraries, and a few other things. By
interpreted, we mean the source code is executed line by line, and not all at once. Because of
this, it is easier to debug your code. Also, interpreting makes it just slightly slower than Java,
but that does not matter compared to the benefits it offers.
7. Object-Oriented
A programming language that can model the real world is said to be object-oriented.
It focuses on objects and combines data and functions. Contrarily, a procedure-oriented
language revolves around functions, which are code that can be reused. Python supports both
procedure-oriented and object-oriented programming which is one of the key python features.
It also supports multiple inheritance, unlike Java.
8. Extensible
If needed, you can write some of your Python code in other languages like C++.
This makes Python an extensible language, meaning that it can be extended to other
languages.
9. Embeddable
We just saw that we can put code in other languages in our Python source code.
However, it is also possible to put our Python code in a source code in a different language
like C++. This allows us to integrate scripting capabilities into our program of the other
language.
10. Large Standard Library
Python downloads with a large library that you can use so you don’t have to write
your own code for every single thing. There are libraries for regular expressions,
documentation-generation, unit-testing, web browsers, threading, databases, CGI, email,
image manipulation, and a lot of other functionality.
11. GUI Programming
Software is not user-friendly until its GUI is made. A user can easily interact with the
software with a GUI. Python offers various libraries for making Graphical user interface for
your applications. For this, you can use Tkinter, wxPython or JPython. These toolkits allow
you for easy and fast development of GUI.
12. Dynamically Typed
Python is dynamically-typed. This means that the type for a value is decided at
runtime, not in advance. This is why we don’t need to specify the type of data while declaring
it.
The future of python
Python might not have bright years in the past years (which is mainly launch in the year
1991) but it has seen a continuous and amazing trend of growth in the 21st century. This stack
overflow graph of major programming languages’ growth exclusively depicts the steady
progress of the PYTHON! The growth rate of python was not something easy to achieve.
Python programming language is better used for app development, web app or web
development, game development, scientific computing, system administration, etc. There are
several traits of this programming tool which has provided it with an incredibly successful
journey. Python has a main role in the new-edge technologies of current and upcoming times
like ML and AI. Looking at the shining future of these technologies which are heavily assisted
by python codes, several people wonder Python will be the language of the future.

Writing and executing first python program


Python programs can execute in two different modes which are
• Interactive mode
• Script mode
Interactive mode
Interactive mode is also called as shell mode or immediate mode. Once Python is
installed, typing python in the command line will invoke the interpreter in immediate mode.
We can directly type in Python code, and press Enter to get the output. Python provides us the
feature to execute the Python statement one by one at the interactive prompt. It is preferable in
the case where we are concerned about the output of each line of our Python program.

Script Mode

In script mode, we type Python program in a file and then use the interpreter to execute the
content from the file.

To create and run a Python script, we will use following steps in IDLE, if the script mode is
not made available by default with IDLE environment.

1. File>New File (for creating a new script file) or Press ctrl+N.


2. Write the Python code as function i.e. script.
3. Save it (^S).
4. Execute it in interactive mode- by using RUN option (^F5).

literal constants
A literal is an explicit representation of a value. Generally, literals are a notation for
representing a fixed value in source code. They can also be defined as raw value or data given
in variables or constants. In python, we have different types of literals such as string literals,
numeric literals, Boolean literals and a special literal.
Numeric literals
Numeric literals are those that are initialized to numeric data type object. All forms of
positive and negative numbers including integer number, real number, complex number,
hexadecimal, binary number and octal number belong to numeric literals.
Integers in python are numbers with no fractional component. An integer representing a
decimal number can be defined as follows.
>>> 10
10
>>> -10
-10
>>> 2455642
2455642
We can also define integers from other number systems. A binary number is represented as a
numeric literal starting with ‘0b’ and consists of digits 0 and 1 as follows.
>>> 0b10110101
181
>>> 0b1010
10
>>> 0b0101
5
A number in the hexadecimal number system starts with ‘0x’ and can be represented in python
as follows.
>>> 0xab
171
>>> 0xa1
161
>>> 0x10
16
An integer literal in the octal number system starts with ‘0o’ and can be represented in python
as follows.
>>> 0o10
8
>>> 0o124
84
A floating point literal in python represents a real number which consists of Integral as well as
fractional part. A floating point number in the decimal number system can be represented as
follows.
>>> 3.45
3.45
>>> 3.e25
3e+25
Complex numbers are in the form of a+bj where ‘a’ represents the real part and ‘b’ represents
the imaginary part of the complex number. A numeric literal representing a complex number
can be written as follows.
>>> 4+5j
(4+5j)
>>> 4.5+8j
(4.5+8j)
PYTHON SYNTAX

Python Indentations

Where in other programming languages the indentation in code is for readability only, in
Python the indentation is very important.

Python uses indentation to indicate a block of code.

Example
Python will give you an error if you skip the indentation:

Example

Comments

Python has commenting capability for the purpose of in-code documentation. A comment is
text that doesn’t affect the outcome of a code, it is just a piece of text to let someone know what
you have done in a program or what is being done in a block of code.

There are two types of comments in Python.

1. Single line comment


2. Multiple line comment

Single-Line Comments in Python

In Python, a single line comment starts with a hash character (#), and is followed by text that
contains further explanations.

Example

Multi-Line Comments in Python

Python doesn't offer a separate way to write multiline comments. However, there are other
ways to get around this issue. We can use # at the beginning of each line of comment on
multiple lines.

Example
Docstrings

Python also has extended documentation capability, called docstrings.

Docstrings can be one line, or multiline.

Python uses triple quotes at the beginning and end of the docstring:

Example

Docstrings are also comments:


Python Keywords

Keywords are the reserved words in Python. In Python, keywords are case sensitive. There are
33 keywords in Python

Here is a list of the Python keywords.

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

1. The name of the variable must always start with either a letter or an underscore (_). For
example: _str, str, num, _num are all valid name for the variables.

2. The name of the variable cannot start with a number. For example: 9num is not a valid
variable name.

3. The name of the variable cannot have special characters such as %, $, # etc, they can only
have alphanumeric characters and underscore (A to Z, a to z, 0-9 or _ ).

4. Variable name is case sensitive in Python which means num and NUM are two different
variables in python.

Standard data types

Python provides various standard data types that define the storage method on each of them.
The data types defined in Python are given below.
Getting the Data Type

Python provides the type() function to know the data-type of the variable. Similarly, the
isinstance() function is used to check an object belongs to a particular class
PYTHON VARIABLES

A Python variable is a reserved memory location to store values. In other words, a variable in
a python program gives data to the computer for processing.

Creating Variables

Unlike other programming languages, Python has no command for declaring a variable.A
variable is created the moment you first assign a value to it.

Variables do not need to be declared with any type and can even change type after they have
been set.

Example
v

Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for Python variables:

• A variable name must start with a letter or the underscore character


• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _)
• Variable names are case-sensitive (age, Age and AGE are three different variables)

Remember that variables are case-sensitive

Output Variables

The Python print statement is often used to output variables. To combine both text and a
variable, Python uses the + character:

Example

You can also use the + character to add a variable to another variable:
Example

For numbers, the + character works as a mathematical operator:

Example
If you try to combine a string and a number, Python will give you an error:

Example

PYTHON NUMBERS
There are three numeric types in Python:

• int
• float
• complex

Variables of numeric types are created when you assign a value to them:

To verify the type of any object in Python, use the type() function:

Int

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

Example

Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.

Example

Float can also be scientific numbers with an "e" to indicate the power of 10.

Example
Complex

Complex numbers are written with a "j" as the imaginary part:

Example
PYTHON STRINGS

String Literals

• String literals in python are surrounded by either single quotation marks, or double
quotation marks.
• 'hello' is the same as "hello".
• Strings can be output to screen using the print function. For example: print("hello").
• Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters. However, Python does not have a character data type,
a single character is simply a string with a length of 1. Square brackets can be used to
access elements of the string.

Example

Get the character at position 1 (remember that the first character has the position 0):
Example

Substring. Get the characters from position 2 to position 5 (not included):

Example

The strip() method removes any whitespace from the beginning or the end:
Example

The len() method returns the length of a string:

Example

The lower() method returns the string in lower case:


Example

The upper() method returns the string in upper case:

Example

The replace() method replaces a string with another string:


Example

The split() method splits the string into substrings if it finds instances of the separator:

Basic Input, Output, and String Formatting in Python


To be useful, a program usually needs to communicate with the outside world
by obtaining input data from the user and displaying result data back to the user. Input may
come directly from the user via the keyboard, or from some external source like a file or
database. Output can be displayed directly to the console or IDE, to the screen via a Graphical
User Interface (GUI), or again to an external source.

Reading Input From the Keyboard

Programs often need to obtain data from the user, usually by way of input from the keyboard.
The simplest way to accomplish this in Python is with input().

input([<prompt>])

Reads a line of input from the keyboard.

input() pauses program execution to allow the user to type in a line of input from the keyboard.
Once the user presses the Enter key, all characters typed are read and returned as a string:

Note that the newline generated when the user presses the Enter key isn’t included as part of

the return string.

input() always returns a string. If you want a numeric type, then you need to convert the
string to the appropriate type with the int(), float(), or complex() built-in functions:
Writing Output to the Console

The simplest way to produce output is using the print() function where you can pass zero or
more expressions separated by commas. This function converts the expressions you pass into
a string before writing to the screen.

Keyword Arguments to print()


print() takes a few additional arguments that provide modest control over the format of the
output. Each of these is a special type of argument called a keyword argument

• Keyword arguments have the form <keyword>=<value>.


• Any keyword arguments passed to print() must come at the end, after the list of objects
to display.
• Keyword arguments have the form <keyword>=<value>.
• Any keyword arguments passed to print() must come at the end, after the list of objects
to display.

The sep= Keyword Argument


Adding the keyword argument sep=<str> causes objects to be separated by the
string <str> instead of the default single space:

To squish objects together without any space between them, specify sep='':
The end= Keyword Argument
The keyword argument end=<str> causes output to be terminated by <str> instead of the
default newline:

Type Conversion in Python

The process of converting the value of one data type into another type is called Type
Conversion. Python has two types of type conversion.

Implicit Type Conversion

Explicit Type Conversion

Implicit Type Conversion


Python automatically converts one data type into another data type. This process doesn't need
any user involvement.

Example

Example 2
Explicit Type Conversion

Python defines type conversion functions like int(), float(), str() to directly convert one data
type into another. This type of conversion is also called typecasting because the user casts
(change) the data type of the objects.

int(a, base)

This function converts any data type into integer

float()

This function is used to convert any data type to a floating point number.

ord()

This function is used to convert a character into integer (ascii value of character).

hex()

This function is used to convert an integer into a hexadecimal string.


oct()

This function converts an integer into an octal string.

str()

This function is used to convert a value (integer or float) into a string.

Example

PYTHON OPERATORS

Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical
operations:

Operator Name Example


+ Addition x+y
- Subtraction x-y

* Multiplication x*y
/ Division x/y

% Modulus x%y

** Exponentiation x ** y
// Floor division x // y
Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As


= x=5 x=5
+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3
&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Python Comparison Operators


Comparison operators are used to compare two values:

Operator Name Example


== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Python Logical Operators


Logical operators are used to combine conditional statements:

Operator Description Example


and Returns True if both statements are true x < 5 and x< 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are the same
object, with the same memory location:

Operator Description Example


is Returns true if both variables are the same object x is y
is not Returns true if both variables are not the same object x is not y
Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example


in Returns True if a sequence with the specified value is present in x in y
the object
not in Returns True if a sequence with the specified value is not x not in y
present in the object
v

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description


& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill Shift left by pushing zeros in from the right and let the leftmost bits
left shift fall off
>> Signed Shift right by pushing copies of the leftmost bit in from the left, and
right shift let the rightmost bits fall off

You might also like