Professional Documents
Culture Documents
Unit 1 Py
Unit 1 Py
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.
Assembly language
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
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
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
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’