Computer Programming Notes Part1
Computer Programming Notes Part1
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
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.)
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
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
- Subtraction 5-2=3
* Multiplication 5*3=15
/ Division 10/2=5
** 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.
/= 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.
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 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