0% found this document useful (0 votes)
16 views

Computer Programming Notes Part1

Uploaded by

amundala amani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Computer Programming Notes Part1

Uploaded by

amundala amani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 116

COMPUTER

PROGRAMMING
UNIT1:
INTRODUCTION TO PYTHON
Introduction
• Computers are increasingly used for a variety
of purposes in engineering and science
including control, data analysis, simulations
and design optimization. It is therefore
becoming more important for engineering
students to have a robust understanding of
computing and to learn how to program
What is a computer?
• A computer is an electronic device that manipulates
information, or data. It has the ability to store, retrieve,
and process data.
The main components of a computer are hardware,
software and data.
• Hardware is any part of your computer that has
a physical structure, such as the keyboard or mouse. It
also includes all of the computer's internal parts.
• Software is any set of instructions that tells the
hardware what to do and how to do it. Examples of
software include web browsers, games, and word
processors.
• Computer is used daily in every field from simple person
to scientists and engineers to perform complex tasks.
Computer Program
Before getting into computer programming, let us first
understand computer programs and what they do.
• A computer program is a sequence of instructions
written using a Computer Programming Language to
perform a specified task by the computer.
• A computer program is also called computer
software, which can range from two lines to millions
of lines of instructions.
• Computer program instructions are also called
program source code and computer programming is
also called program coding.
Computer Program
The act of writing computer programs is called
computer programming.
• A computer without a computer program is just a
dump box; it is programs that make computers
active.
• As we have developed so many languages to
communicate among ourselves, computer scientists
have developed several computer-programming
languages to provide instructions to the computer
(i.e., to write computer programs).
Computer Program
• There are hundreds of programming languages,
which can be used to write computer programs and
following are a few of them:
Java, C, C++, Python, PHP, Perl, Ruby, Matlab
• The first computer program is generally dated to
1843, when mathematician Ada Lovelace published
an algorithm to calculate a sequence of Bernoulli
numbers, intended to be carried out by Charles
Babbage's Analytical Engine.
COMPUTER LANGUAGES
To write a program (tells what to do) for a computer, we must
use a computer language. Over the years computer languages
have evolved from machine languages to natural languages. The
following is the summary of computer languages
• 1940‘s -- Machine Languages
• 1950‘s -- Symbolic Languages
• 1960‘s -- High Level Languages
• Machine Language: In the earliest days of computers, the
only programming languages available were machine
languages. Each computer has its own machine language
which is made of streams of 0‘s and 1‘s. The instructions in
machine language must be in streams of 0‘s and 1‘s. This is
also referred as binary digits. These are so named as the
machine can directly understand the programs.
COMPUTER LANGUAGES

Advantages:
• 1) High speed execution
• 2) The computer can understand instructions immediately
• 3) No translation is needed.
Disadvantages:
• 1) Machine dependent
• 2) Programming is very difficult
• 3) Difficult to understand
• 4) Difficult to write bug free programs
• 5) Difficult to isolate an error
• Example: Addition of two numbers
• 2 0010
• + 3 0 0 1 1 --- --------------- 5  0 1 0 1 --- ---------------
COMPUTER LANGUAGES
• Symbolic Languages (or) Assembly Language:
In the early 1950‘s Admiral Grace Hopper, a mathematician and naval
officer, developed the concept of a special computer program that
would convert programs into machine language. These early
programming languages simply mirrored the machine languages using
symbols or mnemonics to represent the various language instructions.
These languages were known as symbolic languages. Because a
computer does not understand symbolic language it must be
translated into the machine language. A special program called an
Assembler translates symbolic code into the machine language. Hence
they are called as Assembly language.
Advantages:
• 1) Easy to understand and use
• 2) Easy to modify and isolate error
• 3) High efficiency
• 4) More control on hardware
COMPUTER LANGUAGES

Disadvantages:
1) Machine Dependent Language
2) Requires translator
3) Difficult to learn and write programs
4) Slow development time
5) Less efficient
Example:
• PUSH 2, A
• PUSH 3, B
• ADD A, B
• PRINT C
COMPUTER LANGUAGES

• High-Level Languages:
Even though the symbolic languages greatly improved
programming efficiency, symbolic languages were also
very tedious because each machine instruction had to
be individually coded. The desire to improve
programmer efficiency and to change the focus from
the computer to the problems being solved led to the
development of high-level languages. High-level
languages are portable to many different computers
allowing the programmer to concentrate on the
application problem at hand rather than the intricacies
of the computer.
COMPUTER LANGUAGES

Advantages:
1) Easy to write and understand
2) Easy to isolate an error
3) Machine independent language
4) Easy to maintain
5) Better readability
6) Low Development cost
7) Easier to document
8) Portable
COMPUTER LANGUAGES

Disadvantages:
1) Needs translator
2) Requires high execution time
3) Poor control on hardware
4) Less efficient
Difference between Machine,
Assembly, High Level Languages
Feature Machine Assembly High Level
Form 0‘s and 1‘s Mnemonic codes Normal English
Machine Dependent Dependent Independent
Translator Not Needed Needed(Assembler) Needed(Compiler)
Execution Time Less Less High
Languages Only one Different Different
Manufacturers Languages
Nature Difficult Difficult Easy
Memory Space Less Less More
Language Translators

These are the programs which are used for


converting the programs in one language
into machine language instructions, so that
they can be executed by the computer.
There are two translators, namely,
compiler and interpreter.
Comparison between compiler and
interpreter
Compiler Interpreter
A compiler translates the entire An interpreter translates the
source code in a single run. entire source code line by line.

It consumes less time i.e., it is It consumes much more time


faster than an interpreter. than the compiler i.e., it is
slower than the compiler.
It is more efficient. It is less efficient.

CPU utilization is more. CPU utilization is less as


compared to the compiler.
Comparison between compiler and
interpreter
Compiler Interpreter
Both syntactic and semantic errors Only syntactic errors are checked.
can be checked simultaneously.
The compiler is larger. Interpreters are often smaller than
compilers.
It is not flexible. It is flexible.
The localization of errors is difficult. The localization of error is easier
than the compiler.
A presence of an error can cause A presence of an error causes only a
the whole program to be re- part of the program to be re-
organized. organized.
Computer Programming -
Environment
• Though Environment Setup is not an element of any Programming
Language, it is the first step to be followed before setting on to
write a program.
• When we say Environment Setup, it simply implies a base on top of
which we can do our programming. Thus, we need to have the
required software setup, i.e., installation on our PC which will be
used to write computer programs, compile, and execute them. For
example, if you need to browse Internet, then you need the
following setup on your machine: A working Internet connection to
connect to the Internet, A Web browser such as Internet Explorer,
Chrome, Safari, etc.
Similarly, you will need the following setup to start with programming
using any programming language.
• A text editor to create computer programs.
• A compiler to compile the programs into binary format.
• An interpreter to execute the programs directly.
Compiler
• You write your computer program using your favorite
programming language and save it in a text file called the
program file.
• Now let us try to get a little more detail on how the
computer understands a program written by you using a
programming language. Actually, the computer cannot
understand your program directly given in the text format,
so we need to convert this program in a binary format,
which can be understood by the computer.
• The conversion from text program to binary file is done by
software called Compiler and this process of conversion
from text formatted program to binary format file is called
program compilation. Finally, you can execute binary file to
perform the programmed task.
Compiler (con’d)
• The following flow
diagram gives an
illustration of the process:
• So, if you are going to
write your program in any
such language, which
needs compilation like C,
C++, Java and Pascal, etc.,
then you will need to
install their compilers
before you start
programming.
Interpreter
• Compilers are required in case you are going to
write your program in a programming language
that needs to be compiled into binary format
before its execution.
• There are other programming languages such as
Python, MATLAB, PHP , Perl, etc., which do not
need any compilation into binary format; in this
case, an interpreter can be used to read such
programs line by line and execute them directly
without any further conversion.
Interpreter(con’d)
• So, if you are going to
write your programs in
PHP, Python, MATLAB,
Perl, Ruby, etc., then
you will need to install
their interpreters before
you start programming.
Basic elements of programming
• A program is a collection of instructions for the
computer to execute. It is essentially an algorithm; in
that sense it has to be deterministic. Each instruction
should be unambiguous. A programming language
just like any language has a set of rules. These rules
describe the syntax and semantics of the language.
The basic elements of a programming language are
described below.
 Variables are places to store values on the computer
memory. The name of the variable serves as the
address in the memory, where the value of this
variable is held. e.g. x=5, x is the variable; it
represents a particular location in the memory, where
the value 5 is stored. Variables can have types.
Basic elements of programming(con’d)
 Types describe the kind of values a variable can accept and they are
divided in primitive and composite.
 Primitive data types are the ones provided by the programming
language and they typically contain integers, floating-point numbers
and characters.
 In computer science, a composite data type or compound data
type is any data type which can be constructed in a program using
the programming language's primitive data types and other
composite types. It is sometimes called a structure or aggregate
data type, although the latter term may also refer to arrays, lists,
etc. The act of constructing a composite type is known
as composition.
Most modern computer languages recognize five basic categories of
data types: Integer, Floating Point, Character, Character String, and
composite types, with various specific subtypes defined within each
broad category. Composite data types include arrays, lists, and
collections or combination of primitives and other data types.
Basic elements of programming(con’d)
In some languages the declaration of the type
and dimensions of a variable is not required.
Variables can be local or global. Local ones are
only accessible in a particular part of the
program, while global ones can be accessed
anywhere.
Basic elements of programming(con’d)
A variable is only available from inside the region it is
created. This is called scope.
 Local scope
• A variable created inside a function belongs to the local
scope of that function, and can only be used inside that
function.
• Example: A variable created inside a function is
available inside that function:
def myfunc():
x = 300
print(x)
myfunc()
Basic elements of programming(con’d)
Function Inside Function
• As explained in the example above, the variable x is not
available outside the function, but it is available for any
function inside the function:
• Example: The local variable can be accessed from a
function within the function:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
Basic elements of programming(con’d)
 Global Scope
• A variable created in the main body of the Python code
is a global variable and belongs to the global scope.
• Global variables are available from within any scope,
global and local.
• Example: A variable created outside of a function is
global and can be used by anyone:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Basic elements of programming(con’d)
An array is the most basic data structure. It
is a list of elements of the same type.
Individual element of an array can be accessed
using a consecutive range of integers. This is
referred to as the index. The index denotes
the position of an element in the list. One
dimensional array is called vector and two
dimensional array is called matrix.
Basic elements of programming(con’d)
Assignment is the task of storing a value in a
variable. It is commonly done using the equal
sign (=). Keep in mind that the equal sign in
Mathematics stands for equality, and in
programming it stands for assignment.
Expressions compute new values from old
ones. The expression 5 + 3 will calculate the
sum of the values 5 and 3. In this expression,
the plus sign is an operator, which operates on
the values 5 and 3.
Basic elements of programming(con’d)
 Statements or instructions, describe what the program
will do. They can contain assignments, expressions and
control flow operations.
 Control flow operations are divided in two main
categories, conditionals and loops.
 Conditionals, as the name suggests, condition the flow
of the program, if a variable has a particular value (or
belongs in a particular range of values), then a
particular set of statements will be executed, if not
another set will.
 Loops are used for repetition; their construction
contains a rule determining how many times a set of
statements will be repeated.
Basic elements of programming(con’d)
 An entire set of statements grouped together is called
a function. A function takes variables, in this case
called parameters, and can return values.
Calling a function transfers the control over to the
function; the group of statements which form it will be
executed. When this finishes, it returns (with or without a
result) to the original flow of the program.
• Having specified these basic elements of programming,
a program can be redefined as an ordered collection of
statements, functions and variables.
Computer Programming -
Environment
Text Editor
• A text editor is software that is used to write
computer programs. Your Windows machine
must have a Notepad, which can be used to
type programs.
Computer Programming –
Environment(con’d)
You can launch it by following these steps :
• Start → All Programs → Accessories →
Notepad .
Or in search bar, type Notepad and click on
Notepad.
• You can download and install other good
editors like Notepad++, Sublime text, etc.
INTRODUCTION TO PYTHON
What is Python?
• Python is a popular programming language. Python
was invented by Guido Van Rossum in the year 1989,
but it was introduced into the market on 20th February
1991.
• The Python programming language has been used by
many people like Software Engineers, Data Analysts,
Civil engineers, Network
Engineers,Mathematicians,Accountants, Scientists, and
many more.
• Using Python, one can solve complex problems in less
time with fewer lines of code.
• Python is an interpreted high-level dynamically typed
object-oriented programming language.
What is Python?
High Level Language
• A high-level language gives the programmer
freedom to code programs which are
independent of a particular type of device.
They are called high level languages as they
are closer to human languages. Python is high
level because it is not a compiled language;
Python requires another program to run the
code unlike C which runs directly on local
processor.
What is Python?
Interpreted Language
• Python is an interpreted language, as the Python
program’s source code is converted into byte code that
is then executed in the Python virtual machine, unlike
C or C++.
Dynamically Typed Language
• Python is a dynamically typed language because the
type of the variable is checked during run time.
Object-Oriented Language
• Python is an object-oriented language because the
Python developer can use classes and objects to write
clean and reusable codes.
What can Python do?
• Python can be used on a server to create web
applications.
• Python can be used alongside software to create
workflows.
• Python can connect to database systems. It can
also read and modify files.
• Python can be used to handle big data and
perform complex mathematics.
• Python can be used for rapid prototyping, or for
production-ready software development.
Python Syntax compared to other
programming languages
• Python was designed for readability, and has
some similarities to the English language with
influence from mathematics.
• Python uses new lines to complete a command,
as opposed to other programming languages
which often use semicolons or parentheses.
• Python relies on indentation, using whitespace,
to define scope; such as the scope of loops,
functions and classes. Other programming
languages often use curly-brackets for this
purpose.
Advantages and disadvantages of
using Python
Advantages of using Python
• As Python syntaxes are closer to human language, it is easier to
learn, understand and write the code.
• It is both functional and objected-oriented language.
• Python has a large community support and also it has a large
number of modules, libraries and packages.
• Due to its simplicity, developing a Python program or application is
faster than developing in any other language like Java.
• Python is a choice of language in data science, machine learning
and artificial intelligence due to its wide variety of machine learning
packages and libraries.
• Almost everything can be developed using Python; it also has tools
for app development such as kivy, flask, Django and many others.
Disadvantages of using Python
• It’s not recommended for communication
with hardware components.
• There are no time optimizers in Python;
hence it’s slower than most of the
languages like C, C++, and Java.
• The indentation-based coding makes it a
little difficult for people changing their
language from C, C++, or Java to Python.
Using Python
• Even if you don’t want to become a software developer, you can do
various other things with Python, or Matlab. Let’s say you work in a
road project, where you have to find the layout of the curves, or cut
and fill volumes of the soils. You can automate all these calculations
with Python, in an easier manner than possible with the MS-Excel.
You can plot the graphs; do linear, polynomials or matrix algebra
and so many things.
• Python is one of the computer programming languages that adhere
to the off-side rule of syntax, meaning that blocks in that language
are expressed by their indentation. The term was coined by Peter
Landin, possibly as a pun on the offside rule in association football.
This is contrasted with free-form languages, notably curly-bracket
programming languages, where indentation has no computational
meaning and indent style is only a matter of coding
conventions and formatting.
Using Python
• Python also suspends the off-side rule within brackets. A
statement within brackets continues until its brackets match
(or mismatch):
{
"this": True,
"that": False,
"them": [1, 2,
3, 4, 5,
6, 7, 8,
9, 10, 11, 23]
}
Python Installation
• Many PCs and Macs will have python already installed.
• To check if you have python installed on a Windows PC, search
in the start bar for Python or run the following on the
Command Line (cmd.exe):
• C:\Users\Your Name>python --version
• To check if you have python installed on a Linux or Mac: on
Linux, open the command line or on Mac , open the Terminal
and type: python --version
• If you find that you do not have Python installed on your
computer, then you can download it for free from the
following website: https://www.python.org/
Python Quickstart
• Python is an interpreted programming language, this
means that as a developer you write Python (.py)
files in a text editor and then put those files into the
python interpreter to be executed.
• The way to run a python file is like this on the
command line:
• C:\Users\Your Name>python helloworld.py
where "helloworld.py" is the name of your python file.
The Python Command Line
• To test a short amount of code in python sometimes it is quickest and
easiest not to write the code in a file. This is made possible because
Python can be run as a command line itself.
Type the following on the Windows, Mac or Linux command line:
• C:\Users\Your Name>python
• Or, if the "python" command does not work, you can try "py":
• C:\Users\Your Name>py
From there you can write any python.
• C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
Which will write "Hello, World!" in the command line:
• Whenever you are done in the python command line, you can simply type
the following to quit the python command line interface: exit() or ctrl+z
Python Syntax
• Syntax is a set of rules that tell us what arrangements of
characters create a valid statement in a language.
Human languages and programming languages are both
dependent on syntax. To use either type of language
effectively, you need to know how to fit elements
together to achieve your goal. In the case of a human
language, this goal is successful communication. In the
case of a programming language, the goal is to issue a set
of directives that a computer can read and act on.
Python Syntax
• Syntax errors occur when the elements in a statement are
disordered in a way that impedes successful communication. Let’s
look at a simple example from English:
• The dog chased the rabbit. The rabbit chased the dog. Chased the
rabbit the dog.
As you can see, word order matters a great deal in English. The words
are the same in these three sentences, but combining them in
different ways results in very different meanings. Sentence one
contains a simple statement that accords with English syntax. Sentence
two switches the positions of the subject and direct object, so that
while the sentence still makes sense syntactically, the meaning is
radically different. The third sentence shuffles the words around in
such a way that it’s difficult to read. It doesn’t follow the conventions
of English syntax, so it’s unclear what the sentence is saying.
Python Syntax
• Using correct syntax is arguably even more important in
programming languages than it is in human languages. If
you’re learning a new human language and you only have a
beginner’s understanding of its syntax, you’ll often still be
able to get your meaning across. This is because syntax in
human languages is often flexible, and human listeners can
problem-solve to figure out the meaning of an imperfect
sentence.
• Programming languages are less accommodating to syntax
errors. Syntax determines how we organize the elements in
our code to make it legible to the computer. If there’s a
syntax error, the computer might not be able to read it.
Python Syntax
• Here are some examples of what programming syntax can
determine:
• whether we use lower-case or upper-case characters
• how we notate code comments
• how we use whitespace
• how we indicate the relationships between statements (individual
commands issued to the computer)
Syntax is important in programming because it would be impossible to
write functioning code without it. Code is a set of instructions written
in a language that a computer can read and act on. If there are syntax
errors in the code, the program won’t work.
Syntax vs semantics

• The relationship between syntax and semantics is


important. In linguistics, syntax refers to word
order: the way that words need to be sequenced
in order to convey meaning. Semantics is
the meaning that those words convey. Likewise,
in programming, syntax refers to the structure of
the language, the internal logic that determines
how the language needs to be written. The
semantic value of a line of code is its content or
meaning.
Execute Python Syntax

• Python syntax can be executed by writing


directly in the Command Line
Or by creating a python file on the server, using
the .py file extension, and running it in the
Command Line:
C:\Users\Your Name>python myfile.py
Python Indentation
• Indentation refers to the spaces at the beginning
of a code line.
• Where in other programming languages the
indentation in code is for readability only, the
indentation in Python is very important.
• Python uses indentation to indicate a block of
code.
• There are some elements which are common to
all programming languages, namely: data type,
variables, loops, decision making, functions,
classes, objects.
Python Comments
• Comments can be used to explain Python code.
• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.
Creating a Comment
• Comments starts with a #, and Python will ignore them:
• Example
• #This is a comment
print("Hello, World!")
• Comments can be placed at the end of a line, and Python will ignore the
rest of the line:
• Example
• print("Hello, World!") #This is a comment
• A comment does not have to be text that explains the code, it can also be
used to prevent Python from executing code:
• Example
• #print("Hello, World!")
print("Cheers, Mate!")
Python Comments
• Multi Line Comments
• Python does not really have a syntax for multi-line comments.
• To add a multiline comment you could insert a # for each line:
• Example
• #This is a comment
#written in
#more than just one line
print("Hello, World!")
• Or, not quite as intended, you can use a multiline string.
• Since Python will ignore string literals that are not assigned to a variable, you can
add a multiline string (triple quotes) in your code, and place your comment inside
it:
• Example
• """
This is a comment
written in
more than just one line
"""
print("Hello, World!")
• As long as the string is not assigned to a variable, Python will read the code, but
then ignore it, and you have made a multiline comment.
Python Variables
• A variable is a named memory where a programmer can store
data and retrieve for future use using the same name. In
Python, variables are created without specifying any data
type. There is no specific keyword used to create a variable.
Variables are created directly by specifying the variable name
with a value.
• We use the following syntax to create a variable.
variable_name = value
• When a variable is defined, we must create it with a value. If
the value is not assigned the variable gives an error stating
that variable is not defined.
Python Variables
• Python code to illustrate variable declaration error
roll_number
print(f'Student roll number is {roll_number}')
• So when a variable is created, we must assign a value to it.
• Python code to illustrate variable declaration
roll_number = 101
print(f'Student roll number is {roll_number}')
Python Variables
Declaring multiple variables in a single statement
• In Python, it is possible to define more than one variable using
a single statement. When multiple variables are created using
a single statement, the variables and their corresponding
value must be separated with a comma symbol.
• Python code to illustrate variable declaration
name, roll_number = ('Rama', 101)
print(f'Student {name} roll number is {roll_number}')
Python Variables
Displaying data type of a variable
• In Python, the data type of a variable is never fixed to a
particular data type and it keeps changing according to the
value assigned to it. A variable in Python stores value of any
data type. It can change its data type dynamically.
Python Variables
Displaying data type of a variable
• The Python programming language provides a built-in
function type ( ) to display the data type of a variable.
• Example:
a = 105
print(type(a))
a = 10.66
print(type(a))
a = 'rama'
print(type(a))
Python Data Types
• A data type, in programming, is a classification that specifies which
type of value a variable has and what type of mathematical,
relational or logical operations can be applied to it without causing
an error. A string, for example, is a data type that is used to classify
text and an integer is a data type used to classify whole numbers.
• The data type defines which operations can safely be performed
to create, transform and use the variable in another computation.
When a program language requires a variable to only be used in
ways that respect its data type, that language is said to be strongly
typed. This prevents errors, because while it is logical to ask the
computer to multiply a float by an integer (1.5 x 5), it is illogical to
ask the computer to multiply a float by a string (1.5 x Alice). When
a programming language allows a variable of one data type to be
used as if it was a value of another data type, the language is said
to be weakly typed. The extent to which a programming language
discourages or prevents type error is known as type safety.
Python Data Types

• The Python programming language provides a


variety of built-in data types. The following are
the most commonly used built-in data types in
Python.
String Tuple Set Dictionary
None List
Numeric
Python Data Types
1) None
• In many programming languages, we use the
value null to represent nothing. 'None' is
Python's equivalent of NULL value in other
programming languages. In Python, 'None' is the
object which represents nothing. When we want
a variable to hold nothing, we do assign it with
value 'None'.
• Example:
• roll_number = None
• print (type(roll_number))
Python Data Types
2) Numeric
The Python programming language provides four numeric
data types:
• int - All the numbers without fraction part (Example -
10). For int, there is no upper limit.
• float - All the numbers with a fraction part (Example -
10.5). It’s accurate up to 15 decimal places
• complex - All the numbers with real and imaginary
parts (Example - 5 + 10j).
• bool - boolean values: True and False.
Python Data Types
3) String
• A string is a sequence of character data which are confined in either
a single quote or double quote. The string data type in Python is
called as 'str'. In Python, a string can contain as many characters as
you wish. The only limit is the system's memory. In Python, the
string may also be an empty string.
Example :
wish = 'Good Morning'
print(type(wish))
• When a string contains a single quotation as a character in it, then
enclose it with double quotes.(Example - "It's cool")
• When a string contains double quotation as a character in it, then
enclose it with single quotes. (Example - 'Today is so "hot" outside')
• When a string contains both double quotation and a single
quotation as characters in it, then enclose it with triple quotes.
(Example - '''It's so "hot" outside''')
Escape Sequences in Python Strings

• The escape sequences are the special


characters in string data. All the escape
sequences are prefixed with a backslash (\)
character. A backslash (\) character in a string
means that one or more characters that follow
it should be interpreted with their special
meaning only.
Escape Sequences in Python Strings

The following table presents all escape


sequences that are allowed in Python.
S.No Escape Special Meaning
Sequence

1 \' single quote (') character


2 \" Double quote (") character
3 \\ backslash (\) character
4 \b ASCII Backspace character
Escape Sequences in Python Strings

The following table presents all escape


sequences that are allowed in Python.
S.No Escape Special Meaning
Sequence
5 \n ASCII Newline character
6 \t ASCII Horizontal Tab character. Prints TAB
7 \v ASCII Vertical Tab character
8 \r CR( carriage return). It moves all characters
after ( CR ) to the beginning of the line while
overriding same number of characters moved.
Python Collections (Arrays)

Collection is used to store multiple


items in a single variable. There are
four collection data types in the
Python programming language,
namely : list, tuple, set and dictionary
and they have different characteristics
based on the declaration and the
usage.
Python Collections(con’d)
characteristics List Tuple Set Dictionary
Ordered yes yes no yes

indexed yes yes no yes

changeable yes no no yes

Duplicates yes yes no no


Definition Square Round Curly blackets Key: value
blacket brackets {} pairs
[] ()
Constructor list() tuple() set() dict()
Python Collections(con’d)
• To say that a collection is ordered, means that the
items have a defined order, and that order will
not change.
• The collection is changeable, meaning that we
can change, add, and remove items in a collection
after it has been created.
• To allow Duplicates means that collection can
have items with the same value
• To determine how many items a collection has,
use the len () function
• Collection items can be of any data type.
Python Collections(con’d)
• To create a collection with only one item, you have to
add a comma after the item, otherwise Python will not
recognize it as a collection, especially for tuple.
• Except dictionary, other types of python collections are
referred to by index, where first item is referred to as
index [0].
• Dictionary items are presented in key: value pairs, and
can be referred to by using the key name.
• Unordered means that the items do not have a defined
order, you cannot refer to an item by using an index.
Duplicate values will overwrite existing values.
• To determine the type of a collection, use the
type () function.
Python Collections (con’d)
• Set items are unchangeable, but you can
remove and/or add items whenever you like.
• As of Python version 3.7, dictionaries
are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
• When choosing a collection type, it is useful to
understand the properties of that type.
Choosing the right type for a particular data
set could mean retention of meaning, and, it
could mean an increase in efficiency or
security.
Built-in methods used on python list
Python has a set of built-in methods that you can use on list.

Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list.
count() Returns the number of times a value appears in the
list .Syntax: list.count(value)
extend() Add the elements of a list (or any iterable), to the
end of the current list. Syntax: list.extend(iterable).
Any iterable (list, set, tuple, etc.)

fruits = ['apple', 'banana', 'cherry']


cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
Built-in methods used on python list
Python has a set of built-in methods that you can use on
collections
Method Description
index() Returns the index of the first element with the
specified value
insert() Adds an element at the specified position.
list.insert(pos, elmnt)
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
pop() Removes the element at the specified position.
list.pop(pos)
pos: is Optional. A number specifying the position
of the element you want to remove, default value is
-1, which returns the last item.
pop() returns removed item.
Built-in methods used on python list
Python has a set of built-in methods that you can use on
collections
Method Description
remove() Removes the first item with the specified value.
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

reverse() Reverses the order of the list


sort() Sorts the list
Python Typecasting
• In all programming languages, frequently, we
need to convert the values from one data type
to another data type. The process of
converting a value from one data type to
another data type is called Typecasting or
simply Casting. In Python, the typecasting is
performed using built-in functions.
The following are the constructor functions
used to perform typecasting
Python Typecasting
S.No Function Description
01 int( ) It is used to convert an integer literal, float literal, and
string literal (String must represent a whole number) to an
integer value.
a = int(60.99)

02 float( ) It is used to convert an integer literal, float literal, and


string literal (String must represent a whole number) to a
float value.
a = float(10)
03 str( ) It is used to convert a value of any data type including
strings, integer literals and float literals to a string value.
a = str(60.99)
print(f"value of a is {a} and data type of a is {type(a)}")
Python Typecasting

• In Python, when an integer value is cast to


float value, then it is appended with the
fractional part containing zeros (0).
• In Python, when a float value is cast to an
integer it is rounding down to the previous
whole number.
Python built-in functions.

Function Description
abs() Returns the absolute value of a number
all() Returns True if all items in an iterable object are true
any() Returns True if any item in an iterable object is true
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
dict() Returns a dictionary (Array)
divmod() Returns the quotient and the remainder when
argument1 is divided by argument2
float() Returns a floating point number
hex() Converts a number into a hexadecimal value
Python built-in functions.

Function Description
input() Allowing user input
int() Returns an integer number
len() Returns the length of an object
list() Returns a list
max() Returns the largest item in an iterable
min() Returns the smallest item in an iterable
oct() Converts a number into an octal
pow() Returns the value of x to the power of y
print() Prints to the standard output device
Python built-in functions.
Function Description
range() Returns a sequence of numbers, starting from 0 and
increments by 1 (by default)
reversed() Returns a reversed iterator
round() Rounds a numbers
set() Returns a new set object
slice() Returns a slice object
sorted() Returns a sorted list
str() Returns a string object
sum() Sums the items of an iterator
tuple() Returns a tuple
type() Returns the type of an object
Range() function
• In Python, range ( ) is a built-in function used to create a list of integers
with a specified range of values. The general syntax of range ( ) function is
as follows.
• variable_name = range (start, end, difference)
• Example 1:
• a = range(10,20,1)
• print(type(a))
• print(list(a))
• The range( ) function takes three arguments. The first argument indicates
the starting value, the second argument indicates ending value, and the
third argument indicates the difference between each element in the list.
• In Python, the default starting value of range ( ) function is 0, the default
difference between the values of range ( ) function is 1, the ending value is
not included in the list. That means, the range ( ) function returns a list
starting with starting value and ending with End-1 but end value is not
included.
input/output functions
A Program needs to interact with the user to accomplish the desired task; this
is done using Input-Output facility. Input means the data is entered by the
user of the program. In python, we have input() and raw_input ( ) functions
available for Input.
1) input() function
• Syntax: input (expression)
• If prompt is present, it is displayed on monitor, after which the user can
provide data from keyboard. Input takes whatever is typed from the
keyboard and evaluates it. As the input provided is evaluated, it expects
valid python expression. If the input provided is not correct then either
syntax error or exception is raised by python.
• Example 1:
• # python input operations
• # user input
• x = input("Enter any value: ")
• # printing value
• print("Entered value is: ", x)
input/output functions
• 2) raw_input() function
• This input method fairly works in older versions (like 2.x).
• Syntax: raw_input (expression)
• If prompt is present, it is displayed on the monitor after which user can
provide the data from keyboard. The function takes exactly what is typed
from keyboard, convert it to string and then return it to the variable on
LHS of '='.
• Example: In interactive mode
• >>>x=raw_input ('Enter your name: ')
• Enter your name: ABC
• x is a variable which will get the string (ABC), typed by user during the
execution of program. Typing of data for the raw_input function is
terminated by enter key.
• We can use raw_input() to enter numeric data also. In that case we
typecast, i.e., change the data type using function, the string data
accepted from user to appropriate Numeric type.
input/output functions
• 2) raw_input() function
• Always the input( ) function reads input value
as string value only.
To read the value of any other data type, explicitly we
need to convert to the required data type using type
casting.
• Example:
• >>>y=int(raw_input("Enter your roll no."))
• Enter your roll no. 5
• It will convert the accepted string i.e., 5 to integer
before assigning it to 'y'.
Formatted print( ) function to display
a combination of message and value
• The built-in function print( ) is also used to display the combination of
messages and variable values. Example
• num1 = 10 #variale num1 with value 10
• print('The value of variable num1 is ' + num1)
• #Output : The value of variable num1 is 10
• We can also write the same print( ) function as follows.
• num1 = 10 #variale num1 with value 10
• print(f"The value of variable num1 is {num1}")
• #Output : The value of variable num1 is 10
• In the above example code, we have used a formatted string. In
Python, we can use the formatted string that is prefixed with
character "f". In the formatted string, the variable values are included
using curly braces ({ }).
• Always the return value of print( ) function is None.
Reading a single character in Python
• The Python does not provide any direct function to read
a single character as input. But we can use the index
value to extract a single character from the user entered
input value.
Example: ch = input('Enter any data: ')[0]
print(f'The character entered is {ch}')
• When we run the above piece of code, the
input( ) function reads complete data entered by the user
but assigns only first character to the variable ch.
In the above example, the user has entered 'abc' as input
value but the variable ch is assigned with value 'a' only.
Similarly, we can extract any character from the input data
using the index value.
Python Strings

• A string is a sequence of characters which is enclosed in quotes. In


Python, a string value can be enclosed either in single quotes or
double quotes. The Python treats both single quote and double
quote as same. For example, the strings 'Hi Friend' and "Hi
Friend" both are same.

Creating Strings
• In Python, creating string variable is very simple as we need to
assign a string value to a variable.
• Example
• wish_1 = 'Good Morning'
• wish_2 = "Good Evening"
• print(f"wish_1 data type is {type(wish_1)} and wish_2 data type is
{type(wish_2)}")
Python Strings

• Accessing String Values


• In Python, whenever a string data value has been assigned
to a variable, it is organized as an array of characters. The
Python provides a variety of ways to access the string
values. Let's consider the following string value.

☀ Accessing whole string
• To access the entire string which is stored in a variable, we
use the variable name directly.
• Example
• wish = 'Good Morning'
• print(wish)
Python Strings

☀ Accessing a character from a String Values


• To access a single character from a string variable, we use
the index value in square brackets of the respective
character.
Example : wish = 'Good Morning'
print(wish[0])
• We can also access a single character from a string using
negative index values. When we use negative index value, it
starts from the last character with index -1.
Example : wish = 'Good Morning'
print(wish[-2])
Python Strings

☀ Accessing a Substring from a String Value


• In Python, it is also possible to access a substring from
a string. To access substring from a string, we use string
variable name followed by square brackets with
starting index and ending index of the required
substring.
• Example - Accessing a substring from a String
wish = 'Good Morning'
print(wish[2:8]) # Accessing specified substring
print(wish[:8]) # Here default starting index is '0'
print(wish[2:]) # Here default Ending index is 'Last - (11)'
Special Operators with Strings
• The Python programming language provides
special operators which can be used with
string data values. The following table gives
the list of special operators used with strings.
Special Operators with Strings

S.No. Operator Description


1 + It is used to perform concatenation – It adds
values on either side of the operator.

2 * It is used for Reproduction – it generates


new strings, concatenating multiple copies
of the same string.

3 in It is used to check whether a character is


present in the string.
Special Operators with Strings
S.No. Operator Description
4 not in It is used to check whether a character is not
present in the string.
5 r/R It is used to print raw data in a string. Raw
String - Suppresses actual meaning of Escape
characters. The syntax for raw strings is exactly
the same as for normal strings with the
exception of the raw string operator, the letter
"r," which precedes the quotation marks. The
"r" can be lowercase (r) or uppercase (R) and
must be placed immediately preceding the first
quote mark.
Special Operators with Strings
S.No. Operator Description
6 [] It is used to access a character at a specified
index.

7 [:] It is used to access a substring from a string.


Python Operators

• Operators are special symbols in Python that


carry out arithmetic or logical computation.
• Operators are used to perform operations on
variables and values. The value that the
operator operates on is called the operand.
• Below we have different types of operators in
Python
Python Operators
1. Arithmetic Operators
• Arithmetic operators are used to perform
mathematical operations like addition,
subtraction, multiplication, etc.
• For example: sub=10-5 #5
Python Operators
1. Arithmetic Operators
operator name example
+ Addition 5+2=7

- Subtraction 5-2=3

* Multiplication 5*3=15

/ Division 10/2=5

// Floor Division (also a // b (Quotient when a is


called Integer divided by b, rounded to the
Division) next smallest whole number)
% Modulo 10%2=0

** Power 5**2=25
Python Operators
2.Assignment operators
operator name meaning example
= assignment is used to assign values from the a = b + c
right side of the operator to the
value on the left side.

+= Addition This operator adds the value on the a+=5 same as a=a+5
Assignment right side to the value on the left
side and stores the result in the
operand on the left side.

-= Subtraction It subtracts the value on the right a-=5 same as a=a-5


Assignment side from the value on the left side
and stores the result in the operand
on the left side.
Python Operators
2.Assignment operators
operator name meaning example
*= Multiplication It multiplies the right operand a*=2 same as a=a*2
Assignment with the left operand and then
stores the result in the left
operand

/= Division It divides the left operand with the a/=2 same as a=a/2
Assignment right operand and then stores the
quotient in the left operand

%= Remainder It finds the modulus from the left a%=3 same as a%3
Assignment and right operand and stores the
final result in the left operand.
Python Operators
2.Assignment operators
operator name meaning example

//= Double divide It divides the left operand with the a//=3 same as
and equal right operand and stores the floor a=a//3
operator result in the left operand.

**= Exponent It performs exponential or power a**=3 same as


Assignment calculation and assigns value to a=a**3
the left operand.
Python Operators
3. Bitwise operators
operator name meaning example
& Bitwise And It compares the corresponding Let x = 10 (0000
bits of the left operand to the 1010 in binary)
bits of the right operand and if and y = 4 (0000
both bits are 1, the 0100 in binary)
corresponding result is also 1 x & y = 0 (0000
otherwise 0. 0000)

| Bitwise OR It compares the corresponding x | y = 14 (0000


bits of the left operand to the 1110)
bits of the right operand and if
any one of the bit is 1, the
corresponding result is also 1
otherwise 0.
Python Operators
3. Bitwise operators
operator name meaning example

^ Bitwise XOR it compares the x ^ y = 14


corresponding bits of the (0000 1110)
left operand to the bits of
the right operand and if
only one of the bit is 1,
the corresponding result
is also 1 otherwise 0.

~ Bitwise It is unary and has the ~x = -11 (1111


NOT/Ones effect of 'flipping' bits. 0101)
Compleme
nt
Python Operators
3. Bitwise operators
operator name meaning example

>> Bitwise The left operands value is x >> 2 = 2


right moved right by the (0000 0010)
shift number of bits specified
by the right operand.

<< Bitwise The left operands value is x << 2 = 40


left shift moved left by the number (0010 1000)
of bits specified by the
right operand.
Python Operators
4. Comparison Operators

• Comparison operators compare two


values/variables and return a boolean
result: True or False.
• Example: a = 5 b =2 print (a > b) # True
Python Operators
4. Comparison Operators
operator meaning example

== Is Equal To 3 == 5 gives us False


!= Not Equal To 3 != 5 gives us True
> Greater Than 3 > 5 gives us False
< Less Than 3 < 5 gives us True
>= Greater Than or Equal To
3 >= 5 gives us False
<= Less Than or Equal To
3 <= 5 gives us True
Python Operators
5. Logical Operators
• Logical operators are used to check whether
an expression is True or False. They are used in
decision-making.
• For example:
a = 5 b = 6 print((a > 2) and (b >= 6)) # True
Python Operators
5. Logical Operators
operator meaning example

and Logical AND: a and b


True only if both the operands are
True
or Logical OR: a or b
True if at least one of the operands
is True
not Logical NOT: not a
True if the operand is False and
vice-versa.
Python Operators
6. Python Special operators

• Python language offers some special types of


operators like the identity operator and
the membership operator.
Python Operators
6. Python Special operators

1. Identity operators
In Python, is and is not are used to check if two
values are located on the same part of the
memory. Two variables that are equal does not
imply that they are identical.
Python Operators
1. Identity operators.
operator meaning example

is True if the operands are identical (refer to the x is y


same object)

is not True if the operands are not identical (do not x is not y
refer to the same object)
Python Operators
2. Membership Operators
• In Python, in and not. in are the membership
operators. 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.
Python Operators
2. Membership Operators

operator meaning example


.
in True if value/variable is found in the x in y
sequence
not in True if value/variable is not found in x not in y
the sequence

You might also like