Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 74

Unit I

Introduction to Python
Programming Languages – Python History –
Getting Started with Python – Writing a Simple
program – Reading input from console –
Identifiers – Variables, Assignment
Statements and Expressions – Simultaneous
Assignments – Named Constants – Data
Types and Operators – Evaluating expressions
– Augmented Assignment operators – Type
conversion – Common Python Functions –
Strings and Characters – Objects and Methods
– Formatting Numbers and Strings.
Programming Languages
 Computer programming languages are used to
communicate through instructions in to a
computer.
 They are based on syntactic and semantic rule.

 The computer can perform arithmetic


operations, Using some specialized languages
called the programming languages.
Types:
 Machine language or Low level language

 Assembly language

 High level language


Machine language:
It is a machine language here the
instruction written in binary code
The machine language consists of 0’s
and 1’s.
It looks like: 10101000111
combination
0 & 1 are called as binary
Here all the operation performed by
using binary form.
Example : C , C++.
Assembly language
programs written in machine level
language are very difficult to read and
modify.
Assembly languages uses short
descriptive word, known as mnemonic, to
represent the each instructions.
Example :
add - adding numbers
sub - subtracting numbers
add 2, 4, result
Assembly
Machine code
source file assembler
file
ex: add 2,
0101101010
3, result
High level language:
programs are written by using high level
language
It consist of normal English and easy to
learn and use.
This program run in different types of
machine.
The instruction in high level
programming language are called statement.
Example: C, C++, Java, Python.
Programming languages divided into following
category:
Interpreted programming language
Here most of the instruction executed
directly, without compiling the program.
Example: basic , python , pascal.
Functional programming language
It is defined as every calculation
performed using mathematical
evaluation(predefined function),
Example : clean , curry.
Compiled programming language
Here compiler translate source code into
machine code . Ex: c , c++ , java , visual
basic.
Markup programming languages
It is a artificial language it refer how the
content will be displayed in webpage.
Example: HTML , XML.
Object oriented programming languages
it is based on the concept of object,
which may contain data , or attributes ,
methods ..
Example: c++ , python…
‘python’ Programming History
It was created by Guido Van Rossum ,
python is derived from many other language
including ABC , Modula 3, C , C++ , Algol-
68 , Small talk , Unix.
It got name from “Monty Python Flying
Circus”.
‘python’ is a general purpose
interpreted , interactive , object oriented ,and
high level language,
Released in 1991, it support both 32
and 64 bit integers and word size.
Python is High level language:
It is look like a normal English. It is
most compatible with human language.
Python is interpreted:
Python is processed at run time by the
interpreter, you do not need to compile your
program before executing it.
Python support Object –Oriented,
Python is a beginners language.
Python is interactive :
you can type into python prompt and
interact with the interpreter directly to write
the program.
Features and application of ‘python’
languages
 python ’ is general purpose ,structured
programming language.
 Easy to learn.
 Easy to maintain.
 Free and open source.
 High level language.
 Extensive libraries.
1. Interpreter mode

K.ANGURAJU , AP/CSE
Python interpreter mode
The python interpreter is a program that reads
and execute python code ,
python programs stored in a file with an
extension of .py
To start the python interpreter by clicking
python icon, or by typing python(idle) on a command
line, then click file and new file.

K.ANGURAJU , AP/CSE
An interpreter processes the
program line by line , alternatively
read the lines and perform
computation.
python Analyze and Executes
program statements at the same
time ,

K.ANGURAJU , AP/CSE
Program:
a=int (input("enter the first number"))
b=int (input("Enter the second number"))
sum=a+b
print("result", sum)

K.ANGURAJU , AP/CSE
2. Interactive mode

K.ANGURAJU , AP/CSE
Interactive mode
In this , to type the program into
interactive mode , press enter then the
interpreter displays the result.
Here the chevron (>>>) is a prompt
that indicates that the interpreter is ready to
enter the code.
The interpreter provides an interactive
environment to play with the language
Here the results of expressions are
printed on the same screen

K.ANGURAJU , AP/CSE
Example:

K.ANGURAJU , AP/CSE
PYTHON INTERPRETER

Source code

Interpreter

Input data
Output

K.ANGURAJU , AP/CSE
Writing a Simple program
writing a program that involves
designing the algorithm then convert into
programming code.
Multiplication of two numbers
A=10
B=20
C=A*B
Print(c)
Ex:2
Print(“enter into python world”)
Program for area of circle

Radius=5
Area=3.14*Radius*Radius
Print(“area of circle is”, Area)
Reading input from console
using input() function to ask the user
input at run time.
Syntax:
Variable= eval(input(“statement”))
Description:
Variable – dummy variable name
eval() - convert the string into value
Input() - reading input from user
Example:
A=eval(input(“Enter a value”))
B=eval(input(“Enter b value”))
C=A/B
Print(“the result is”, c)

Output:
Enter a value 100
Enter b value 10
The result is10
python Character Set
The character set are used to represent
information. Also the characters used to write
‘python’ program , It is basically two types.
1. Source character set
2. Execution character set

python
character set

Source Execution
character set character set

Alphabets
Digits Special Escape
a…z White spaces
0…9 characters sequence
A…..Z K.ANGURAJU , AP/CSE
Execution character set
 \a - bell alert - beep sound
 \t - ,horizontal tab
 \n - new line
 \v - vertical tab

K.ANGURAJU , AP/CSE
Identifiers
Identifiers are names given to the
different program elements,
Example: - variables , functions , list…etc
Rules for naming identifiers:
1. It consist of letters and digits.
2. First character must be letter, or begin with _
3. _ underscore also consider as character.
4. Both upper/lower character accepted.
5. No special character allowed.
6. identifier cannot be keyword.

K.ANGURAJU , AP/CSE
variables
Definition:
A variable is an identifier,
A variable is nothing but a reserved
memory location (or) place holder to store
values.
Rules for naming variables:
1. It consist of letters and digits.
2. First character must be letter, or begin with _
3. _ underscore also consider as character.
4. Both upper/lower character accepted.
5. No special character allowed.
6. Variables cannot be keyword
K.ANGURAJU , AP/CSE
Variable declaration:
syntax: v1,v2,v3…….etc
Example:
>>> a , b
Initializing variables:(assignment statement)
Initialization of variable can be done
using assignment operator (=) ,variable can
be initialized while declaration itself
Syntax: variable name =value
Example:
>>> radius=10
>>> cutoff=198.4
>>> c=‘a’
K.ANGURAJU , AP/CSE
Scope of variables
Local variables:
A variable which is declared
inside a function is called as local
variable.
Global variables/external variables:
A variable which is declared
outside a function is called as
global variable.
K.ANGURAJU , AP/CSE
Expression
Expression is defined as combination of
variables or constants are interconnected with
operators.
Syntax:
variable=expression;
There are following expression are:
1.Arithmetic expression
It perform only arithmetic operation(+,-,/,%)
Example:
Num1=10
num2 = 20
sum=Num1+Num2
Print(sum)
Output: 30
K.ANGURAJU , AP/CSE
2.Relational expression
it perform operation by using relational
operator.(<, > <= , >= , == ,!=)
Example:
A=10
B=20
If(A>B):
print(“a is big”)
Else:
print(“b is big”)
Output:
b is big

K.ANGURAJU , AP/CSE
3.Logical expression
it perform the operation by using logical
operators
Example:
if((a>b)and (a>c)):
4.Conditional expression
Here also we use relational operator
to perform conditional operation.

K.ANGURAJU , AP/CSE
Simultaneous assignment statement
In python we assign the various
values into multiple variable at same time
Example:
Var1,var2,….. Var n=exp1,exp2…….exp n
Example: swapping of two numbers
A=11 A,B=11,20
B=20
A,B=B,A
Print(“after swapping A and B value is”, A,B)
Data type

Data type Description Memory Example


bytes
int integer 2 bytes int a=20;
numbers
float Decimal 4 bytes float
point b=20.1
numbers
char Single 1 byte char s=n;
character
double Double 8 bytes double
precision d=234324
K.ANGURAJU , AP/CSE
Data types
Data type of an variable determines
what values it holds and also what
operation performed on it.
There are following data types are:
1.Integer (int)
2. Floating point type (float)
3. String type (string)
4.Booleans (bool type)
5. List (list [])
6.Tuple (tuple ())
7.None type (None)
K.ANGURAJU , AP/CSE
Integer:
An integer type (int ) represents
signed whole numbers . without decimal
point. They can be positive or negative
numbers.
The range is -2 , 147 to +2 , 147
1. Normal integer numbers:
It is a signed whole numbers it may
be positive or negative
>>> a = 27
>>> b = -23
>>> c = 3435

K.ANGURAJU , AP/CSE
2. Octal literals (base 8)
To indicate integer in octal numbers, you
can use the prefix of 0o or 0O(zero followed
by upper or lower case o)
>>> x = 0o56
>>> print(x)
46)
3. Hexadecimal literals( base 16):
To indicate integer in hexadecimal
numbers, you can use the prefix 0x or
0X(zero followed by upper or lower case x)
>>> y = 0x9A
>>> print(y)
>>>154
K.ANGURAJU , AP/CSE
4. Binary literals( base 2):
To indicate integer in binary
numbers,
you can use the prefix 0b or
0B(zero followed by upper or lower case
b)
>>> s = 0b1111
>>> print(s)
15

K.ANGURAJU , AP/CSE
Floating point number
Definition:
Floating point type represent numbers
with fractional part (or) real numbers with
decimal point.
They can be positive or negative
numbers, It will take 4 bytes of memory.
Example:
>>> a = 3.14
>>> b = -15.45

K.ANGURAJU , AP/CSE
Strings /char
Strings in python are identified as a
nearby set of characters represented in the
quotation marks.
python allows either pairs of single or
double quotes,
Ex: ‘Hi’ or “Hello” or ‘“Hi’’’
Slicing in string:
subsets of strings can be taken using
the slice operator( [] and [:] )

K.ANGURAJU , AP/CSE
Booleans
Definition
Boolean is a data type, Having two values it
is denoted by True and False , It is defined by
“George Boole”
The most common way to produce a
Boolean value is with a relational operator
>>> print(2==2)
True
>>> print (2<3)
True
Print(2!=2)
False
K.ANGURAJU , AP/CSE
Lists
• A list contains items separated by commas and
enclosed with square bracket [ ] .
• List holds heterogeneous values

• List and arrays are same in python.

• values stored in list is accessed by using its index or

its value by slicing.


Syntax
List_name=[ ]
Or
List_name= [ value1, value2 …. Value n]
Example 1:
>>> a = [ ] - empty list
>>> b = [“ram”, 31 , 54 , 12 , 47 ]
>>> print( b )
[“ram”, 31 , 54 , 12 , 47] K.ANGURAJU , AP/CSE
Tuple Assignment
tuple contains items(elements) separated
by commas and enclosed with parenthesis().
After creation of tuple those values cannot be
modified and also cannot insert a new element with in
those tuple
In tuple also possible to assign more than one
values into more than one variable at a time.
Example:
>>> s=(“ram”, 54 , 656 , 50)
>>> print(s)
‘ram’ , 54 , 656 , 50
>>> print(s[0])
‘ram’
>>> a , b =(10 , 20)
>>> print (a,b)
>>> 10 20 K.ANGURAJU , AP/CSE
Operator precedence: evaluating expreassion

Arithmetic expression are evaluated by


using it’s precedence(PEMDAS).
When an expression contains more
than one operator , then the order of
evaluation depends on it’s operator
precedence.
Parentheses having highest
precedence , it is executed first with in the
expression.
Example:
5*(5+3) = 40
In this expression first execute
parenthesis , then multiply with five and
K.ANGURAJU , AP/CSE
Next highest precedence is exponentiation
Next highest precedence is multiplication
and division ( * , / , % )
The lowest precedence is addition and
subtraction.( + , -)
Operator with the same precedence are
evaluated from left to right.
EXAMPLE:
Workout this expression and write
correct answer .
3 – 9*(3 + 7)+7 * 3 - 1

K.ANGURAJU , AP/CSE
Named constant
The value of variable is may change
during the execution of a program,
But the named constant represents
permanent data that never changes.
python does not have any special syntax
for creating named constant.
you can simply create a variable and
named as constant.
for difference we use upper character
letter to a constant variable
Example:
PI=3.14
Operators
An operator is symbol that specifies an
operation to be performed on the operands.
Types of operator:
1. Arithmetic operator. + , - , / , *, %
2. Relational Operator.
3. Logical Operator.
4. Assignment Operator.
5. Bitwise Operator.
6. Membership Operators
7. Identity Operators

K.ANGURAJU , AP/CSE
Arithmetic operator

Arithmetic operators are used to


perform mathematical operation like addition
, subtraction , division ….etc
it require two operands
+ - addition operator
- - Subtraction operator
* - multiplication operator
/ - division operator
% - Modulo division operator
** - Exponent (x**y )

K.ANGURAJU , AP/CSE
Example program:
a = int ( input (“Enter the a value”))
b= int ( input ( “enter the b value”))
sum = (a + b)
print("Sum of two number is :", sum)

K.ANGURAJU , AP/CSE
Relational Operator:
These operators compare the values on
either sides of them and decide the relation
among them. They are also known as
Relational operators .
< - less than
<= - less than or equal to
>= -greater than or equal to
> -greater than
= = - is equal to
! = - not equal to

K.ANGURAJU , AP/CSE
Example:
a= int ( input ( “enter a value”))
b= int (input (“enter b value”))
if (a>b):
print(“a is big”)
else:
print(“b is big”)

K.ANGURAJU , AP/CSE
Logical operators
Python logical operator are used to
combine two or more conditions and perform
the logical operations using Logical AND,
Logical OR and Logically NOT.
Logical (and )
(a>c) and (a>b)
Logical ( or )
(a>b) or (a>d)
Logical NOT
29!=29

K.ANGURAJU , AP/CSE
Example:
a= int ( input ( “enter a value”))
b= int (input (“enter b value”))
c = int (input (“enter c value”))
if (a>b) and (a>c):
print(“a is big”)
elif (b>c):
print(“b is big”)
else:
print(“c is big”)

K.ANGURAJU , AP/CSE
Augmented assignment operator
Assignment operator used assign a values
of a variable.
Python allows you to combine assignment
and addition operation using an augmented
assignment operator
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Float division assignment
//= integer division assignment
**= Exponent assignment

K.ANGURAJU , AP/CSE
Syntax:
variable= expression or value;
Example:
a=10
b=20
c= a+b
print(“sum of two number is”,c)
Bitwise Operator
Bitwise operator used to manipulate the
data at bit level, it operates on integers only.
it not applicable to float or real.

operator meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift left
>> Shift right
~ One’s complement

K.ANGURAJU , AP/CSE
Bitwise AND (&)
Here operate with two operand bit by bit.
Truth table for & is:
x= 7= 0000 0111 & 0 1
y= 8 = 0000 1000 0 0 0
a&b
1 0 1
Output: 0000 0000
Bitwise OR ( |)
| 0 1
x= 7= 0000 0111
0 0 1
y= 8 = 0000 1000
1 1 1
aIb
Output: 0000 1111 ^ 0 1
Bitwise exclusive OR (^) 0 0 1
x= 7= 0000 0111
1 1 0
y= 8 = 0000 1000 K.ANGURAJU , AP/CSE
Membership Operators
Python’s membership operators test for
membership in a sequence, such as strings,
lists, or tuples. There are two membership
operators as explained below
in - Evaluates to true if it finds a variable in
the specified sequence and false otherwise.
not in - Evaluates to true if it does not finds a
variable in the specified sequence and false
otherwise

K.ANGURAJU , AP/CSE
Example:
>>> s1="welcome"
>>> for word in s1:
print(s1)
Output:
welcome
welcome
welcome
welcome
welcome
welcome
welcome

K.ANGURAJU , AP/CSE
Identity Operators
Identity operators compare the memory
locations of two objects. There are two
Identity operators explained below:
is
is not
Example:
x=20 ; y=25
if ( x is not y):
print (“different identity”)
else:
print (“same identity”)
K.ANGURAJU , AP/CSE
Example 2:
x=15 ; y=20
if ( x is not y):
print (“different identity”)
else:
print (“same identity”)

K.ANGURAJU , AP/CSE
Type Conversion
Type conversion is the process of
convert one data type into another type.
if an integer and float are involved in a
binary operation, python automatically
converts the integer to a float value. This is
called type conversion.
so 3*4.5 is converted as 3.0 * 4.5
sometimes to convert the float value as
integer we use int(value) function.
Example:
>>>Value=6.5
>>>Int(value)
6
>>>
You can also use round(value) function
to round a number to the nearest whole
number.
>>>value=5.6
>>>round(value)
6
Common python functions
A function is a group of statements that
perform a specific task.
Python having lot of predefined library
functions Ex: eval(), input(), print()…etc
These are build in function they are
always available in the python interpreter.
you don’t have to import any modules
to use the functions additionally.
Ex: abs, max, min, pow, and round,…
etc
Simple python build in function
abs(x) - return absolute value for x
Ex: abs(-2) >>>2
max(x1,x2) - return largest among x1,x2
Ex:max(10,20) >>>20
min(x1,x2) - return smallest among x1,x2
Ex:min(10,23) >>>10
Pow(a,b) - return a**b value
Ex:pow(2,3) >>>8
Round(x) - return an integer nearest to
x
Ex:round(10.6) >>>11
Mathematical function
The python math module provides the
mathematical function. listed below
sin(x) -returns the sine of x
cos(x) - returns the cosine of x
tan(x) - returns the tangent of x
exp(x) -returns the exponential of x
Log(x) -returns the logarithm of x
degrees() - convert angle x from radians to
degree
radians() - converts the angle x from
degrees to radians.
Example: import math
Math.sin(x)
Strings and character
a string is a sequence of character.
Python treat strings and character same way.
String values must be enclosed in single
or double quotes.
Python does not have a data type for
character.
Example:
>>>name=“ramkumar”
>>>initial=“m”
AscII code
a character is stored in a computer as a
sequence of 0s and 1s.
There are different ways to encode a
character.
One popular standard is ASCII(American
Standard code for Information Interchange)
It provide 7 bit encoding scheme for
representing all uppercase and lowercase
letters, digits, …etc.
ASCII uses 0 through 127 to represent
character.
Unicode:
Python also support Unicode
Unicode is an encoding scheme for
representing international character.
ASCII is small subset of Unicode.
Unicode was established by the unicode
consortium to support interchange,
processing, and display the written text in the
word’s diverse language.
The ord() and chr() function
Python provides the ord(ch) function for
returning the ASCII code for the character ch
The chr(ch) function for returning the
character represented by the code.
Example:
>>> ch='a'
>>> ord(ch)
97
>>> chr(98)
'b'
>>> ord('A')
65
Python escape sequences
Python uses special notation, which
consist of a backslash (/) followed by a letter
or combination of digit.
Example:
\n - linefeed
\b -Backspace
\t -Tab
\\ -backslash
Printing without newline
To print the multiple values or character
with in single line using end statement.
Example:
Print(“ram”, end=“ “)
Print(“kumar”, end=‘ ‘)
Print(“mani”, end=‘***’)
Output:
ram kumar ***
The str() function
this function is used to convert a number into
a string.
Example:
>>>S=str(3.4)
>>>Print(s)
>>>‘3.4’

You might also like