You are on page 1of 67

PYTHON-PROGRAMMING

SCAS
6/1/2020
What is Python?
• Python is a general interpreted
purpose interactive object high level
oriented and programming
• language.
It was first introduced in 1991 by Guido van
Rossum , a Dutch computer programmer.
• The language places strong emphasis on code
reliability and simplicity so that the
programmers can develop applications rapidly

6/1/2020
contd..
• Python is multi-paradigm(top-down/bottom-up)
programming language ,which allows user to
code in several different programming styles.
• Python supports cross platform development and
is available through open source.
• Python is widely used for scripting in Game menu
applications effectively.

6/1/2020
contd..
• Python can be easily integrated with C/C++
CORBA, ActiveX and Java.
• CPython is a python integrated with C/C++
language.
• Similarly JPython is a purely integrated
language where Java and Python code can
interchangeably use inline in the program.

6/1/2020
Advantages of Python
• Most programs in Python require considerably
less number of lines of code to perform the
same task compared to other languages like C
.So less programming errors and reduces the
development time needed also.
• Though Perl is a powerful language ,it is
highly syntax oriented .Similarly C also.

6/1/2020
Why to Learn Python
• There are large number of high-level
programming languages C ,C++,Java
like
etc.But when compared to all these languages
Python has simplest Syntax, availability of
libraries and built-in modules.
• Python comes with an extensive collection of
third party resources that extend the
capabilities of the language.

6/1/2020
contd..
• Python can be used for large variety of tasks
like Desktop applications ,Data base
applications,network programming ,game
programming and even mobile development
also.
• Python is also a cross platform language which
means that the code written for one operating
system like Windows ,will work equally well
with Linux or MacOS without any changes to
the python code.

6/1/2020
INSTALLING PYTHON ON YOUR PC
• To learn this language first ,you have to
download the software which is the Python
Interpreter.
• Presently the version in use is Python 3.x
But you can also use Python 2.x ,like
2.7..etc .This depends on your system and your
interest.
To download the Python interpreter go to the
site http://www.python.org/downloads and
click on the suitable icon.
6/1/2020
contd..
• The website appears as shown below.

6/1/2020
contd..
• This Python shell allows us to use Python
in interactive mode.
• The shell waits for a command from the
user
,executes it and returns the result.

6/1/2020
IDLE
• IDLE is a graphical user interface for doing
Python development, and is a standard and
free part of the Python system.
• It is usually referred to as an Integrated
Development Environment (IDE).
• One can write the Python code or script using
the IDLE which is like an editor.This comes
along with Python bundle.

6/1/2020
contd..
The only thing to do is that we have to launch
the IDLE program .
• While the Python shell allows the user to work
in interactive mode, the Idle allows to write
the code and save it with .py extension. For
Ex: myProg_py.
• This file is known as Python script.

6/1/2020
contd..
• Once the program is saved ,it can be
executed either by clicking the Run module
or F5.
• If there are no errors you observe the results.

6/1/2020
contd..
• The Screenshot for IDLE will be as shown
below. The >>> is the prompt, telling you Idle
is waiting for you to type something.

6/1/2020 yayavaram@yahoo.com
Your First Program
• To develop the Python program ,TYPE
cmd in start and get command prompt.
• This will open a command line prompt where
type python to get the python prompt.
• Type print(“Hello Python”)
• You can see the output

6/1/2020 yayavaram@yahoo.com
Or take notepad and type

• # Prints the words Hello Python


print(“Hello Python”)
print(“Its nice learning Python”)
print(“Python is easy to learn”)

6/1/2020
contd..
• In the above program ,the lines appear after
the # sign are treated as comments. They are
ignored and not executed by Python
interpreter. This will help only to improve the
readability of the program.
• After typing the code save this program with
an extension .py .For Ex: FirstProg.py
• Now type “python FirstProg.py” at
command prompt
• Dont type the above code from python
interpretor.
6/1/2020
contd..
• After execution you find the output
as Hello Python
Its nice learning Python
Python is easy to
learn.

6/1/2020
Print() function
print(“Hello”)
Output :
Hello

print(“Hello”,”GoodMorning”)
Output: Hello Goodmorning
Here in output , by default there is a space between two words.

print(“Hello”,”Morning”,sep=“-”)
Output: Hello-Morning
Here the separator is – which is given as an argument in print function.
This is called keyword argument print function.

6/1/2020
print (“Good”)
print(“Morning”)
Output:
Good
Morning

print(“Good”,end=“ “)
print(“Morning”)
Output:
Good Morning
Here the first print statement should be ended with space instead of \n

print(“My”,”name”,”is”,sep=“-”,end=“*”)
print(“Monty”,”Python”,sep=”*”,end=“*\n”)
print(“Hello”)
Output
My-name-is*Monty*Python*
Hello
6/1/2020
Variables and Operators
• Variables are the names given to data that we
need to store and manipulate in our
program.
• For example ,to store the age of the user ,we
can write a variable userAge and it is defined
as below.
userAge = 0 or userAge = 50
After we define userAge ,the program will
allocate some memory to store this data.
6/1/2020
contd..
• Afterwards this variable can be accessed by
referring its name userAge.
• Every time we declare a variable ,some initial
value must be given to it.
• We can also define multiple variables at a
time.
For ex: userAge, userName=30,’Peter’
This is same as
userAge=30
userName=‘Peter’
6/1/2020
contd..
• Some precautions: The user name can contain
any letters (lower case or upper case)
numbers or underscores(-) but the first
character shouldn’t be a number
• For Ex: userName,user_Name,user_Name2
etc.. Are valid.
• But 2user_name ,2userName ..are not valid

6/1/2020 yayavaram@yahoo.com
contd..
• Variable names are case sensitive
.username and userNAME are not same.
• Normally two conventions are used in Python
to denote variables.
• Camel case notation or use underscores.
• Camel case is the practice of writing the
compound words with mixed casing.For
ex:”thisIsAvariableName”
• Another is to use underscores (-).
6/1/2020 yayavaram@yahoo.com
contd..
• This separates the words.For example:
“user_Name_variable”
• In the above example userAge=30,the ‘=‘ sign
is known as Assignment Sign
• It means ,we are assigning the value on the
right side of the = sign to the variable on the
left.
• So the statements x=y and y=x have different
meanings in programming.
6/1/2020 yayavaram@yahoo.com
contd..
• For example ,open your IDLE editor and type
the following program.
x=5
y=10
x=y
print(“x
=“,x)
Print(‘y
=“,y)
Now save this program with .py
extension. For example myprog1.py
6/1/2020 yayavaram@yahoo.com
contd..
• Run the program either by
clicking . Runmodule or F5
The output should be as below.
x=10
y=10
Here in the program you have assigned x=y in
the third line.So the value of x is changed
to10
while the value of y do not change .
6/1/2020 yayavaram@yahoo.com
contd..
• Suppose you change the third line from x=y to
y=x, mathematically x=y and y=x may be
same .But it is not same in programming.
• After changing ,you again save your program
and Run the module as done above.What is the
output you expect?
• Surprisingly x=5 ,y=5 will be the
output. are you convinced with the
output?
6/1/2020 yayavaram@yahoo.com
Basic Operators
• Python accepts all the basic operators like +
(addition),(subtraction),*(multiplication),/
(division),//(floor division),%(modulus) and
**(exponent).
• For example ,if x=
7,y=2 addition: x+y=9
subtraction:x-y=5
Multiplication:x*y=14
Division: x/y=3.5

6/1/2020 yayavaram@yahoo.com
contd
• Floor division: x // y=3(rounds off the answer
to the nearest whole number)
• Modulus: x%y= 1(Gives the remainder when
7 is divided by 2
• Exponent : x**y=49(7 to the power of 2)

6/1/2020 yayavaram@yahoo.com
Additional assignment Operators
• +=: x+= 2 is same as equal to x=x+2
• Similarly for subtraction:
x-=2 is same as x=x-2

6/1/2020 yayavaram@yahoo.com
Data Types
• Python accepts various data types like Integer,
Float and String.
• Integers are numbers with no decimal parts
like 2 ,-5 , 27 ,0 ,1375 etc..
• Float refers to a number that has decimal
parts.Ex: 1.2467 ; -0.7865 ; 125.876
• userHeight = 12.53
• userWeight = 65.872

6/1/2020 yayavaram@yahoo.com
contd..
• String: string refers to text.Strings are defined
within single quotes.
• For Ex: Variable Name = ‘initialvalue’
• VariableName=“initial value”
• userName=‘peter’
• userSpouseName=“Mary”
• userAge =“35”
here “35” is a string

6/1/2020 yayavaram@yahoo.com
contd..

• Multiple substrings can be combined by using


the concatenate sign(+)
• Ex:”Peter”+ “Lee” is equivalent to the string
“PeterLee”

6/1/2020 yayavaram@yahoo.com
The following table lists all operators from highest precedence to lowest.

6/1/2020
Type Casting
• Type casting helps to convert from one data
type to another .i.e from integer to a string or
vice versa.
• There are three built in functions in Python
int() ; str() ; float()
• To change a float to an integer
type int(7.3256).The output is 7
• To change a string into integer
int(“4”).The output is 4

6/1/2020 yayavaram@yahoo.com
contd..
• Ex: int(“RAM”) ----- returns syntax error
• Int(“3.7654”) -------returns syntax error
• The str() function converts an integer or a float
to a string.
• Ex: str(82.1) The output is “82.1”
• Ex: str(757) The output is “757”
• Ex: str(Ram) The output is “Ram”

6/1/2020 yayavaram@yahoo.com
Associativity of Python Operators
When two operators have the same precedence, associativity helps to determine the
order of operations.
Associativity is the order in which an expression is evaluated that has multiple
operators of the same precedence. Almost all the operators have left-to-right
associativity.
For example, multiplication and floor division have the same precedence. Hence, if
both of them are present in an expression, the left one is evaluated first.

6/1/2020
Non associative operators
Some operators like assignment operators and comparison operators
do
not have associativity in Python.

There are separate rules for sequences of this kind of operator and
cannot be expressed as associativity.

For example, x < y < z neither means (x < y) < z nor x < (y < z). x <
y < z is equivalent to x < y and y < z, and is evaluated from left-to-
right.

Furthermore, while chaining of assignments like x = y = z = 1 is


perfectly valid, x = y = z+= 2 will result in error.

6/1/2020
Condition Statements
• To change the flow of control ,normally we
use some conditional statements in a
program .The flow of the program is based on
whether the condition is met or not .
• The most common condition statement
is Comparison statement which is denoted
by (= =) sign.
• For ex: when you are writing a==b ,means you
are asking the program to check whether the
value of a is equals to that of b or not.
6/1/2020 yayavaram@yahoo.com
contd..
• The other comparison statements are
“not equals” (!=)
“smaller than”(<)
“greater
than”(>)
“greater than or equal to (>=)
Examples:8!= 4----Not equals
6>=2 ----Greater than or equal
to 7>2 ---Greater than
4<9 – Less than or equal to
6/1/2020
Logical Operators
• There are three logical operators in Python
• And , or ,not
• The and operator returns True if all the
conditions are met ,else it will return False.
• The or operator returns true if atleast one
condition is met.Else it will return false.
• The not operator returns True if the condition
after the not keyword is false.Else it will return
False.
6/1/2020 yayavaram@yahoo.com
Python Decision Making
• It is one of the commonly used control flow
statements.
• It allows the program to evaluate if certain condition
is met. And to perform the appropriate action based
on the result of the evaluation
• For example , if condition 1 is met
do task A
elif condition 2 is met
do task B
elif stands for else if and we can have as many elif
statements as we like

6/1/2020 yayavaram@yahoo.com
Syntax of if..else

The syntax of the if...else statement is −

if expression:
statement(s)
else:
statement(s)

6/1/2020
The elif Statement

The elif statement allows you to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE.

Similar to the else, the elif statement is optional. However, unlike else, for which there
can be at most one statement, there can be an arbitrary number of elif statements
following an if.

Syntax:
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)

Core Python does not provide switch or case statements as in other languages

6/1/2020
Program
• Open notepad and type the program

a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
6/1/2020
Python - Loops
Python programming language provides following types of
loops to handle looping requirements.
• while loopRepeats a statement or group of statements
while a given condition is TRUE. It tests the condition
before executing the loop body.
• for loopExecutes a sequence of statements multiple times
and abbreviates the code that manages the loop variable.
• nested loopsYou can use one or more loop inside any
another while, for or do..while loop.

6/1/2020
A while loop statement in Python programming
language repeatedly executes a target statement as
long as a given condition is true.

Syntax
The syntax of a while loop in Python programming
language is −

while expression:
statement(s)

6/1/2020
Ex:

count = 0
while (count < 9):
print 'The count is:', count
count = count + 1

print "Good bye!"

6/1/2020
For Loop
• The For Loop executes a block of code
repeatedly until the condition in the
for statement is no longer valid.
• In Python ,an iterable refers to anything that
can be looped over ,such as a string ,list or
Tuple.
• The syntax for looping through an iterable is :
for an iterable
print(a)

6/1/2020
contd..
• Ex: pets =
[‘cats’,’dogs’,’rabbits’,’hamsters’] for x in
pets:
print(x)
In this program,first we declared the list pets
and give the members ‘cats’,’dogs’,’rabbits’ and
‘hamsters’.Next the statement for x: loops
through the pets list and assigns each member in
the list to the variable myPets.
6/1/2020
contd..
• If we run the program ,the output will
be cats
dogs
rabbits
hamsters
• It is also possible to display the index of the members
in the List.For this the function enumerate() is
used.
for index,x in enumerate(pets):
print(index,x)

6/1/2020
contd..
•The output is:
0 cats
1 dogs
2 rabbits
3 hamsters

6/1/2020
Looping through a sequence of Numbers
• To loop through a sequence of numbers ,the
built-in range() function is used.
• The range() function generates a list
of numbers and has the syntax :
range(start,end,step).
• If start is not mentioned ,the numbers
generated will start from zero.
• Similarly if step is not given , alist of
consecutive numbers will be generated (i.e
step=1)
6/1/2020
contd..
• For ex:
• Range(4) will generate the List[0,1,2,3,]
• Range(3,9) will generate a List[3,4,5,6,7,8]
• Range(4,10,2) will generate List[4,6,8]

6/1/2020
Example
• To check the working of range function with for loop
type the following script on Idle.
• for i in range(5);
print(i)
The output will be:
0
1
2
3
4

6/1/2020
for i in range(10):
print(“The value of i is currently”,i)

Here range function takes the value of i from 0 to 9

for i in range(2,8):
print(“The value of i is currently”,i)

Here the first value 2 is taken from range, the last


value 7 is taken though the second argument is 8

6/1/2020
By default the increment is 1, but to change the
increment
for i in range (2,8,3):
print(“The value of i is currently ”,i)

Output:
The value of i is currently 2
The value of i is currently 5

6/1/2020
normally. This means that the loop did not encounter
a break statement.
For and else
i=111
for i in range (2,8,3):
print(“The value of i is currently ”,i)

else
print(“The value of i is currently ”,i)

Output
The value of i is currently 111

6/1/2020
Nested Loops
Python programming language allows to use one
loop inside another loop. Following section shows
few examples to illustrate the concept.

Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)

6/1/2020
The syntax for a nested while loop statement in Python
programming language is as follows −

while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that you can put any
type of loop inside of any other type of loop. For
example a for loop can be inside a while loop or vice
versa.

6/1/2020
Break
• This will help to exit from the loop when a
certain condition is met.Here break is a
keyword in Python.
• Ex: j=0
for i in the range(5):
j=j+2
print(‘i=‘,i, ‘j=‘,j)
if j==6:
break

6/1/2020
contd..
•The output of the above program will be:
i=0,j=2
i=1,j=4

i=2,j=6
without the break keyword ,the program
should loop from i=0 to i=4 because
the function range(5) is used.
Due to the keyword break ,the program
ends early at i=2.Because when i=2 ,j
6/1/2020
reaches the value 6 .
Continue
• Continue is another important keyword for
Loops.
• When the keyword continue is used ,the
rest of
the loop after the keyword is skipped for that
iteration.
• Ex: j=0
for i in range (5):
j=j+2
print(‘\ni=‘,i,j=‘,j)
if j==6:
continue
6/1/2020
contd..
• Print(‘i will be skipped over if j=6’)
The output of the program is as
below:
i=0,j=2
I will be skipped over if j=6
i=1,j=4
I will be skipped over if j=6
i=2,j=6
i=3,j=8
i= 4,j=10
I will be
skipped
over if
6/1/2020
j=6
Try,Except
• This control statement controls how the
program proceeds when an error occurs
The syntax is as below.
• Try:
do a Task
except
do
something
else when
an error
6/1/2020
contd..
• For
Ex:
try:
answer = 50/0
print(answer)
except:
print(‘An
error
occurred’)
when we run the program,the message “An error
occurred” will be displayed because answer=50/0 in
the try block canot divide a num,ber by 0.So,the
6/1/2020

You might also like