SlideShare uma empresa Scribd logo
1 de 99
PYTHON-PROGRAMMING
YNM
What is Python?
• Python is a general purpose interpreted
interactive object oriented and high level
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
10/27/15 yayavaram@yahoo.com
contd..
• Python is multi-paradigm 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.
10/27/15 yayavaram@yahoo.com
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.
10/27/15 yayavaram@yahoo.com
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.
10/27/15 yayavaram@yahoo.com
Why to Learn Python
• There are large number of high-level
programming languages like C ,C++,Java
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.
10/27/15 yayavaram@yahoo.com
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.
10/27/15 yayavaram@yahoo.com
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.
10/27/15 yayavaram@yahoo.com
contd..
• The website appears as shown below.
10/27/15 yayavaram@yahoo.com
contd..
• From the website you can download the suitable
version based on
• your OS (whether the OS is Windows ,MacOS or
Linux).
• And the Processor 32 bit or 64 bit.
• For ex: if you are using 64-bit Windows system ,you
are likely to download Windowsx86-64MSI Installer.
• So just click on the link and download and install the
Python Interpreter.
10/27/15 yayavaram@yahoo.com
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.
10/27/15 yayavaram@yahoo.com
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.
10/27/15 yayavaram@yahoo.com
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.
10/27/15 yayavaram@yahoo.com
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.
10/27/15 yayavaram@yahoo.com
contd..
• The Screenshot for IDLE will be as shown
below. The >>> is the prompt, telling you Idle
is waiting for you to type something.
10/27/15 yayavaram@yahoo.com
Your First Program
• To develop the Python program ,click on the
File and select NewFile.
• This will open a new text editor where you can
write your first program.
• # Prints the words Hello Python
print(“Hello Python”)
print(“Its nice learning Python”)
print(“Python is easy to learn”)
10/27/15 yayavaram@yahoo.com
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 press either F5 or click on Run module.
10/27/15 yayavaram@yahoo.com
contd..
• After execution you find the output as
Hello Python
Its nice learning Python
Python is easy to learn.
10/27/15 yayavaram@yahoo.com
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.
10/27/15 yayavaram@yahoo.com
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’
10/27/15 yayavaram@yahoo.com
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
10/27/15 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 (-).
10/27/15 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.
10/27/15 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
10/27/15 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 .
10/27/15 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?
10/27/15 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
10/27/15 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)
10/27/15 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
10/27/15 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
10/27/15 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
10/27/15 yayavaram@yahoo.com
contd..
• Multiple substrings can be combined by using
the concatenate sign(+)
• Ex:”Peter”+ “Lee” is equivalent to the string
“PeterLee”
10/27/15 yayavaram@yahoo.com
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
10/27/15 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”
10/27/15 yayavaram@yahoo.com
LIST
• A List in Python is a collection data which are
normally related.
• Instead of storing a data as separate variables
,it can be stored as a LIST.
• For ex: to store the age of 4 users , instead of
storing them as user1Age,user2Age,user3Age
and user4Age we can create a List of this data.
• To some extent, lists are similar to arrays in C.
Difference between them is that all the items
belonging to a list can be of different data
type.10/27/15 yayavaram@yahoo.com
contd..
• To declare a List:
ListName=[initial values]. Note ,always square
brackets[] are used to declare a List.
userAge =[20,42,23,25]
• A List can also be declared without assigning
any initial value to it.
• listName=[]. This is an empty list with no
items in it.
10/27/15 yayavaram@yahoo.com
contd..
• To add items to the List ,we use append().
• The individual items of the List are accessed
by their indexes.The index always starts from
0.
• For ex; useAge=[20,25,35,45,65,55]
here userAge[0]= 20,userAge[2]=35.
• Similarly the index -1 denotes the last item
• userAge[-1]=55 and userAge[-2]=65
10/27/15 yayavaram@yahoo.com
SLICE
• To access a set of items in a List we use Slice.
• The notation used is x:y.
• Whenever we use slice notation inPython, the
item at the start index is always included ,but
the item at the end is always excluded i.e y-1
is considered.
• For ex:userAge=[15,25,30,45,50.65.55]
the userAge[0:4] gives values from index 0 to
3 i.e 15,25,30,45
10/27/15 yayavaram@yahoo.com
Add and Remove items
• To add items the append() function is useful.
• For ex :userAge.append(100) will add the
value 100 to the List at the end. Now the new
List is userAge=[15,25,30,45,50.65.55,100]
• To remove any value from the List we write
dellistName[index of item to be deleted]
• For ex: del userAge[2] will give a new List
userAge=[15,25,45,50,65,55,100]
10/27/15 yayavaram@yahoo.com
Program
• # declare the list
myList[2,5,4,5,”Ram”]
• # to print the entire list
print(‘myList’)
• # to print the third item
print(myList[3])
The output is “Ram”
• # to print the last but one item
print(myList[-2])
10/27/15 yayavaram@yahoo.com
Tuple
• Tuples are also a type of Lists.But the difference is
they can’t be modified.
• A tuple consists of a number of values separated by
commas. Unlike lists, however, tuples are enclosed
within parentheses().
• The main differences between lists and tuples are:
• Lists are enclosed in brackets [ ] and their elements
and size can be changed, while tuples are enclosed in
parentheses ( ( ) ) and cannot be updated.
• Tuples can be thought of as read-only lists.
10/27/15 yayavaram@yahoo.com
contd..
• Declaring a Tuple
tupleName=( ‘Raju',786 , 2.23, ‘cdef',70.2 )
monthsOfYear(“Jan”,”Feb”,”March”,”April”)
• monthsOfYear[0]=“Jan”
• monthsOfYear[-1]= “April”
10/27/15 yayavaram@yahoo.com
contd..
• print tuple: # Prints complete list print
• tuple[0] : # Prints first element of the list
• print tuple[1:3]: # Prints elements starting
from 2nd till 3rd print
• tuple[2:] : # Prints elements starting
from 3rd element
• print tinytuple * 2 : # Prints list two times
10/27/15 yayavaram@yahoo.com
Dictionary
• Dictionary is a collection of related data
PAIRS.
• The general Syntax is
dictionaryName={dictionarykey:data}
The same dictionary key should not be used
twice
• For Ex: to store the username and age of 4
users we can write
• myDictionary={“peter”:25,”Ram”:15,”Carl”:5
0,”Kundan”: 20}
10/27/15 yayavaram@yahoo.com
contd…
• Dictionary can also be declared using “dict()”
method.
• userNameAndAge=dict(peter=25,Ram=20,Carl
=30, Krish=“not available”)
• Here round brackets parenthesis) are used
instead of curly brackets.
• dictionaryName={ } denotes an empty
dictionary with no items init
10/27/15 yayavaram@yahoo.com
Add items to Dictionary
• To add items to a dictionary the syntax is
dictionaryName[dictionarykey]=data.
To add “Sam”=40 to the dictionary ,
userNameAndAge[“Sam”]=40
• Now the dictionary will become
userNameAndAge=dict(peter=25,Ram=20,Car
l=30, Krish=“not available”,Sam=40)
10/27/15 yayavaram@yahoo.com
contd..
• To delete or remove items from a dictionary
the syntax is
del dictionaryName[dictionarykey]
• Ex: To remove “Ram”:20 the syntax is
del usernameAndAge[‘’Ram”]
• Now the dictionary is
userNameAndAge={“peter”:25,”Carl”:30,
“Krish”:“not available”,”Sam”:40}
10/27/15 yayavaram@yahoo.com
Declare Dictionary –Alternative way
• Dictionary can also be declared by alternative
method
• myDict={“one”:1.45,5.8:”TwopointFive”,3:”+”,4.5:2}
print(mydict)
The output is
{2.5:’TwopointFive’,3:’+’:4.5,4.5:2}
10/27/15 yayavaram@yahoo.com
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.
10/27/15 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
10/27/15 yayavaram@yahoo.com
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.
10/27/15 yayavaram@yahoo.com
If statement
• 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
10/27/15 yayavaram@yahoo.com
Program
• Open your Idle and type the program
• userInput=input(“Enter 1 or 2”)
if userInput == “1”:
print(“Hello Python”)
print(“how are you”)
elif userInput == “2”:
print(“python great”)
print(“I Love Python”)
else:
print(“ you entered invalid number”)
10/27/15 yayavaram@yahoo.com
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)
10/27/15 yayavaram@yahoo.com
contd..
• Ex: pets = [‘cats’,’dogs’,’rabbits’,’hamsters’]
for myPets in pets:
print(myPets)
In this program,first we declared the list pets
and give the members ‘cats’,’dogs’,’rabbits’ and
‘hamsters’.Next the statement for myPets: loops
through the pets list and assigns each member in
the list to the variable myPets.
10/27/15 yayavaram@yahoo.com
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,myPets in enumerate(pets):
• print(index,myPets)
10/27/15 yayavaram@yahoo.com
contd..
• The output is:
0 cats
1 dogs
2 rabbits
3 hamsters
10/27/15 yayavaram@yahoo.com
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)
10/27/15 yayavaram@yahoo.com
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]
10/27/15 yayavaram@yahoo.com
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
10/27/15 yayavaram@yahoo.com
While Loop
• A while loop repeatedly executes instructions
inside the loop while a certain condition
remains true.
• The syntax of a while loop is
while the condition is true
do the Task A
For Ex:
Counter= 5
While counter > 0:
10/27/15 yayavaram@yahoo.com
contd..
• print(‘counter=‘,counter)
counter = counter-1
When you run the program the output will be
counter=5
counter=4
counter=3
counter=2
counter=1
10/27/15 yayavaram@yahoo.com
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
10/27/15 yayavaram@yahoo.com
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 reaches the
value 6 .
10/27/15 yayavaram@yahoo.com
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
10/27/15 yayavaram@yahoo.com
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 j=6
When j=6,the line after the continue keyword is not
printed.
10/27/15 yayavaram@yahoo.com
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 occurs
10/27/15 yayavaram@yahoo.com
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
remaining of the try block is ignored and the
statement in the except block is executed.
10/27/15 yayavaram@yahoo.com
Functions-Modules
• Functions are pre-written codes that perform a
dedicated task.
• For ex: the function sum() add the numbers.
• Some function require us to pass data in for
them to perform their task.These data are
known as parameters and we pass them to the
function by enclosing their values in
parenthesis() separated by commas.
• The print() function is used to display the text
on the screen.
10/27/15 yayavaram@yahoo.com
contd..
• replace() is another function used for
manipulating the text strings.
• For Ex:
“helloworld”.replace(“world”,”Universe”)
here “world” and “universe” are the
parameters.The string before the Dot is the
string that will be affected.So,”hello world”
will be changed to “hello Universe”
10/27/15 yayavaram@yahoo.com
Your own Functions
• Python has has flexibility to define your own
functions and can be used them in the
program.
• The syntax is:
def functionName(parameters):
code for what the function should do
return[expression]
The two keywords here are “def” and “return”
10/27/15 yayavaram@yahoo.com
contd..
• def tells the program that the indented code
from the next line onwards is part of the
function and return is the keyword that is used
to return an answer from the function.
• Once the function executes a return
statement ,it will exit.
• If your function need not return any value you
can write return or return None.
10/27/15 yayavaram@yahoo.com
contd..
• Ex:def checkIfPrime(numberToCheck):
for x in range(2,numberToCheck):
if(numberToCheck%x==0);
return False
return True
The above function will check whether the
given number is a prime number or not.If the
number is not a prime number it will return
False otherwise return True.
10/27/15 yayavaram@yahoo.com
Variable Scope
• An important concept to understand while
defining a function is the concept of variable
scope.
• Variables defined inside a function are treated
differently from variables defined outside.
• Any variable defined inside a function is only
accessible within the function and such
functions are known as local variables.
• Any variable declared outside a function is
known as global variable and it is accessible
anywhere in the program.
10/27/15 yayavaram@yahoo.com
Importing Modules
• Python provides a large number of built-in
functions and these are saved in files known
as modules.
• To use the modules in our program ,first we
have to import them into our programs.
and this is done by using the keyword import.
Ex: To import the module random we write
import random
10/27/15 yayavaram@yahoo.com
contd..
• To use the randrange() function in the random
module we use
random.randrange(1,10).
This can also be written as
r.randrange(1,10).
• If we want to import more than one functions
we separate them with a comma
• To import the randrange() and randint()
functions we write from random import
randrange,randint.
10/27/15 yayavaram@yahoo.com
Creating own Module
• Creating a module is simple and it can be done
by saving the file with a .py extension and put
it in the same folder as the python file that you
are going to import it from.
• Suppose you want to use the
checkIfPrime()function defined earlier in
another Python script.First save the code
above as prime.ph on your desktop.
10/27/15 yayavaram@yahoo.com
contd..
• The prime.py should have the following code.
def checkIfPrime(numberToCheck):
for x in range(2,numberToCheck):
if(numberToCheck%x==0):
return False
return True
Next create another python file and name it
useCheckIfPrime.py
This should have the following code
10/27/15 yayavaram@yahoo.com
contd..
• Import prime
answer = prime.checkIfPrime(17)
print(answer)
• Now run useCheckIfPrime.py.
• You get the output as True
• Suppose you want to store prime.py and
useCheckIfPrime.py in different folders, you
have to give the python’s system path.
10/27/15 yayavaram@yahoo.com
contd..
• Create a folder called ‘MyPythonModules’ in
the C drive to store prime.py.
• Add the following code to the top of your
useCheckIfPrime.py file.
(i.e before the import prime line)
• Import sys
if’C:MyPythonModules’not in sys.path:
sys.path.append(‘C:MyPythonModules’)
here sys.path refers to python’s system path.
10/27/15 yayavaram@yahoo.com
contd..
• The code above appends the
folder’C:MyPythonModules’ to your system
path.
• Now you can put prime.py in
C:MyPythonModules and checkIfPrime.py in
any other folder of your choice.
10/27/15 yayavaram@yahoo.com
Handling Files
• The basic type of a file is a text file.It consists
of multiple lines of text.To create a text file
type some lines of text like
“I am learning Python programming.
Python is an interesting language” .
save this text file as myfile.txt on your desktop.
Next open Idle and type the code below.
10/27/15 yayavaram@yahoo.com
contd..
• f= open(‘myfile.txt’,’r’)
firstline=f.readline()
secondline=f.readline()
print(firstline)
print(secondline)
f.close()
Save this code as fileOperation.py on your
desktop.
• To open a file we can use open() function.
10/27/15 yayavaram@yahoo.com
contd..
• The open function require two parameters:The
first one is the path to the file and the second
parameter is the mode.
• The commonly used modes are
• ‘r’mode: For reading only
• ‘w’mode: For writing only.
• ‘a’ mode: For appending .If the specified file
does not exist ,it will be created and if the file
exist ,any data written to the file is
automatically added at the end of the file.
10/27/15 yayavaram@yahoo.com
contd..
• ‘r+’mode:For both reading and writing.
• After opening the file
firstline=f.readline() reads the firstline in the
file and assigns it to the variable firstline.
Each time the readline() function is called ,it
reads a new line from the file.
When you run the program the output will be
I am learning Python programming.
Python is an interesting language.
10/27/15 yayavaram@yahoo.com
contd..
• In the output ,you can observe that a line break
is inserted after each line.
• Because the function readline() adds the ‘n’
characters to the end of each line.
• If you don’t want the extra line between each
line of text ,you can wrte
print(firstline,end=‘’).This will remove the ‘n’
characters
• f.close() function closes the file.One should
always close the file after reading is done.It will
freeup any system resources.
10/27/15 yayavaram@yahoo.com
For Loop to Read Text Files
• For loop can also be used to read a text file.
• For ex: f = open(‘myfile.txt’,’r’)
for line in f:
print(line,end=‘’)
f.close()
The for loop helps to read the text file line by
line.
10/27/15 yayavaram@yahoo.com
Opening and reading Text files by Buffer size
• To avoid the too much usage of memory we
can use the read() function instead of
readline() function.
• Ex: msg=inputfile.read(10)
The program reads only the next 19 bytes and
keeps doing it until the entire file is read.
10/27/15 yayavaram@yahoo.com
Deleting and re-naming the Files
• remove() and rename() are the two important
functions available as modules which have to
be imported before they are used in a program.
• The remove() function deletes a file.the syntax
is remove(filename)
• Ex: remove(‘myfile.txt’)
• To rename a file the function rename() is used.
• The syntax is rename(old name,new name)
• rename(‘oldfile.txt,’newfile.txt’) will rename
oldfile.txt to newfile.txt
10/27/15 yayavaram@yahoo.com
Simple Examples-1
• Python code to find the area of a triangle:
• First open Idle and type the code
• a = float(input(‘Enter first side:’))
b= float(input(‘Enter first side:’))
c= float(input(‘Enter first side:’))
s=(a+b+c)/2
area=(s*(s-a)*(s-b)*(s-c))**0.5
print(‘The area of the triangle is %0.2f’%area)
10/27/15 yayavaram@yahoo.com
Simple Examples-2
• Python code to find Square root
num=float(input(‘Enter a number:’))
num_sqrt=num**0.5
print(‘The square root of %0.3f is % 0.3f%
(num,num_sqrt))
This program is saved with .py extension and
executed .the out will ask to enter a number
and on entering a number it gives the squre
root of the number.
10/27/15 yayavaram@yahoo.com
Simple Examples-3
• Python code for factorial of a number
• Num= int(input(‘Enter a number:’))
factorial = 1
if num < 0:
print(‘sorry ,factorial does not exist for
negative numbers’)
elif num == 0;
print(“The factorial of 0 is 1”)
10/27/15 yayavaram@yahoo.com
contd..
• else for i in range(1,num+1):
factorial = factorial*i
print(“The factorial of “,num,”is”,factorial)
• Save the program with .py extension and run
module or press F5.
• The program will ask to enter a number
• After entering the number you get the output
10/27/15 yayavaram@yahoo.com
Simple Examples-4
• Print all the Prime numbers in an Interval.
• Lower=int(input(‘Enter lower range:’))
upper=int(input(‘Enter upper range))
for num in range(lower,upper+1):
if num>1:
for i in range(2,num):
if(num%i)==0:
break
else:
print(num)
10/27/15 yayavaram@yahoo.com
Simple Examples-5
• Code to swap two numbers
• x= input(‘Enter value of x:’)
y=input(‘Enter value of y:’)
temp = x
x=y
y= temp
print(‘The value of x after swapping:
{ }’format(x))
print(‘The value of y after swapping:
{ }’format(y)).
Run the code and observe the output
10/27/15 yayavaram@yahoo.com
Simple Examples-6
• Solve a quadratic equation ax2+bx+c=0
• Import cmath # add complex math module
a= float(input(‘Enter a:’))
b= float(input(‘Enter b:’))
c= float(input(‘Enter c:’))
d= (b**2)-(4*a*c) //calculate discriminant
sol1=(-b-cmath.sqrt(d))/(2*a)
sol2=(-b+cmath.sqrt(d))/(2*a)
print(‘The solutions are {0} and {1}.format(sol1,sol2))
10/27/15 yayavaram@yahoo.com
Simple Examples-7
• To find ASCII value of a given characters
• # Take character from user
c = input("Enter a character: ")
print("The ASCII value of '" + c + "' is",ord(c))
Note: here ord(c) is a builtin function available
in Python to find the ASCII value of a
character
10/27/15 yayavaram@yahoo.com
ACKNOWLEDGEMENT
• I don’t claim any ownership for this lecture as
it is the collection from many books &web
resources
• I thank the authors of the books and web
resources from where I collected the
information and code.
• The sole objective behind this effort is only to
encourage and inspire if possible some young
minds towards this wonderful programming
language -Python
10/27/15 yayavaram@yahoo.com
References
• Learn Python in One Day and Learn It Well -
Jamie Chan.
• Sams Teach Yourself Python Programming for
Raspberry.
• Programming Python, 5th
Edition,O'Reilly
Media.
• Python Cook Book O'Reilly Media.
10/27/15 yayavaram@yahoo.com

Mais conteúdo relacionado

Mais procurados

Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in pythonRaginiJain21
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAMaulik Borsaniya
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPTShivam Gupta
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners Sujith Kumar
 
Python and its Applications
Python and its ApplicationsPython and its Applications
Python and its ApplicationsAbhijeet Singh
 
programming with python ppt
programming with python pptprogramming with python ppt
programming with python pptPriyanka Pradhan
 
Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An IntroductionSwarit Wadhe
 
Data types in python
Data types in pythonData types in python
Data types in pythonRaginiJain21
 
Presentation on python
Presentation on pythonPresentation on python
Presentation on pythonwilliam john
 
File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha V
 
Introduction to-python
Introduction to-pythonIntroduction to-python
Introduction to-pythonAakashdata
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Pedro Rodrigues
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programmingprogramming9
 
Variables in python
Variables in pythonVariables in python
Variables in pythonJaya Kumari
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide shareDevashish Kumar
 

Mais procurados (20)

Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Python basics
Python basicsPython basics
Python basics
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners
 
Python and its Applications
Python and its ApplicationsPython and its Applications
Python and its Applications
 
programming with python ppt
programming with python pptprogramming with python ppt
programming with python ppt
 
Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An Introduction
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Presentation on python
Presentation on pythonPresentation on python
Presentation on python
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
Introduction to-python
Introduction to-pythonIntroduction to-python
Introduction to-python
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Data types in C
Data types in CData types in C
Data types in C
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 

Destaque

Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 
Python: the Project, the Language and the Style
Python: the Project, the Language and the StylePython: the Project, the Language and the Style
Python: the Project, the Language and the StyleJuan-Manuel Gimeno
 
RTOS APPLICATIONS
RTOS  APPLICATIONSRTOS  APPLICATIONS
RTOS APPLICATIONSDr.YNM
 
Object-oriented Programming in Python
Object-oriented Programming in PythonObject-oriented Programming in Python
Object-oriented Programming in PythonJuan-Manuel Gimeno
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundationKevlin Henney
 
8051 Microcontroller Notes
8051 Microcontroller Notes8051 Microcontroller Notes
8051 Microcontroller NotesDr.YNM
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 
Why I Love Python
Why I Love PythonWhy I Love Python
Why I Love Pythondidip
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionNandan Sawant
 
Common MS Excel and MS Excel 2013 useful tricks. By Ashot Engibaryan
Common MS Excel and MS Excel 2013 useful tricks. By Ashot EngibaryanCommon MS Excel and MS Excel 2013 useful tricks. By Ashot Engibaryan
Common MS Excel and MS Excel 2013 useful tricks. By Ashot EngibaryanAshot Engibaryan
 
Python Programming - I. Introduction
Python Programming - I. IntroductionPython Programming - I. Introduction
Python Programming - I. IntroductionRanel Padon
 
Scala in practice
Scala in practiceScala in practice
Scala in practiceTomer Gabel
 
Excel for Marketers - Why do you hate Excel (#Measurefest 2013)
Excel for Marketers - Why do you hate Excel (#Measurefest 2013)Excel for Marketers - Why do you hate Excel (#Measurefest 2013)
Excel for Marketers - Why do you hate Excel (#Measurefest 2013)Russell McAthy
 
PHP, Java EE & .NET Comparison
PHP, Java EE & .NET ComparisonPHP, Java EE & .NET Comparison
PHP, Java EE & .NET ComparisonHaim Michael
 
Inro to Secure Sockets Layer: SSL
Inro to Secure Sockets Layer: SSLInro to Secure Sockets Layer: SSL
Inro to Secure Sockets Layer: SSLDipankar Achinta
 

Destaque (20)

Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Python: the Project, the Language and the Style
Python: the Project, the Language and the StylePython: the Project, the Language and the Style
Python: the Project, the Language and the Style
 
RTOS APPLICATIONS
RTOS  APPLICATIONSRTOS  APPLICATIONS
RTOS APPLICATIONS
 
Object-oriented Programming in Python
Object-oriented Programming in PythonObject-oriented Programming in Python
Object-oriented Programming in Python
 
Mastering Python 3 I/O (Version 2)
Mastering Python 3 I/O (Version 2)Mastering Python 3 I/O (Version 2)
Mastering Python 3 I/O (Version 2)
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundation
 
8051 Microcontroller Notes
8051 Microcontroller Notes8051 Microcontroller Notes
8051 Microcontroller Notes
 
Python Presentation
Python PresentationPython Presentation
Python Presentation
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Why Learn Python?
Why Learn Python?Why Learn Python?
Why Learn Python?
 
Why I Love Python
Why I Love PythonWhy I Love Python
Why I Love Python
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 Edition
 
Common MS Excel and MS Excel 2013 useful tricks. By Ashot Engibaryan
Common MS Excel and MS Excel 2013 useful tricks. By Ashot EngibaryanCommon MS Excel and MS Excel 2013 useful tricks. By Ashot Engibaryan
Common MS Excel and MS Excel 2013 useful tricks. By Ashot Engibaryan
 
Python Programming - I. Introduction
Python Programming - I. IntroductionPython Programming - I. Introduction
Python Programming - I. Introduction
 
Microsoft Excel Seminar
Microsoft Excel SeminarMicrosoft Excel Seminar
Microsoft Excel Seminar
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Excel for Marketers - Why do you hate Excel (#Measurefest 2013)
Excel for Marketers - Why do you hate Excel (#Measurefest 2013)Excel for Marketers - Why do you hate Excel (#Measurefest 2013)
Excel for Marketers - Why do you hate Excel (#Measurefest 2013)
 
PHP, Java EE & .NET Comparison
PHP, Java EE & .NET ComparisonPHP, Java EE & .NET Comparison
PHP, Java EE & .NET Comparison
 
Inro to Secure Sockets Layer: SSL
Inro to Secure Sockets Layer: SSLInro to Secure Sockets Layer: SSL
Inro to Secure Sockets Layer: SSL
 

Semelhante a Python Programming Language

4_Introduction to Python Programming.pptx
4_Introduction to Python Programming.pptx4_Introduction to Python Programming.pptx
4_Introduction to Python Programming.pptxGnanesh12
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introductionstn_tkiller
 
python introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptxpython introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptxChandraPrakash715640
 
Python basics_ part1
Python basics_ part1Python basics_ part1
Python basics_ part1Elaf A.Saeed
 
Introduction to Python.pdf
Introduction to Python.pdfIntroduction to Python.pdf
Introduction to Python.pdfRahul Mogal
 
Fundamentals of python
Fundamentals of pythonFundamentals of python
Fundamentals of pythonBijuAugustian
 
Python-Certification-Training-Day-1-2.pptx
Python-Certification-Training-Day-1-2.pptxPython-Certification-Training-Day-1-2.pptx
Python-Certification-Training-Day-1-2.pptxmuzammildev46gmailco
 
Lecture1_introduction to python.pptx
Lecture1_introduction to python.pptxLecture1_introduction to python.pptx
Lecture1_introduction to python.pptxMohammedAlYemeni1
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
Programming intro variables constants - arithmetic and assignment operators
Programming intro variables   constants - arithmetic and assignment operatorsProgramming intro variables   constants - arithmetic and assignment operators
Programming intro variables constants - arithmetic and assignment operatorsOsama Ghandour Geris
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptxArpittripathi45
 
علم البيانات - Data Sience
علم البيانات - Data Sience علم البيانات - Data Sience
علم البيانات - Data Sience App Ttrainers .com
 
Python for Physical Science.pdf
Python for Physical Science.pdfPython for Physical Science.pdf
Python for Physical Science.pdfMarilouANDERSON
 

Semelhante a Python Programming Language (20)

Module-1.pptx
Module-1.pptxModule-1.pptx
Module-1.pptx
 
4_Introduction to Python Programming.pptx
4_Introduction to Python Programming.pptx4_Introduction to Python Programming.pptx
4_Introduction to Python Programming.pptx
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introduction
 
Class_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdfClass_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdf
 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
#Code2Create: Python Basics
#Code2Create: Python Basics#Code2Create: Python Basics
#Code2Create: Python Basics
 
python introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptxpython introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptx
 
Python basics_ part1
Python basics_ part1Python basics_ part1
Python basics_ part1
 
Introduction to Python.pdf
Introduction to Python.pdfIntroduction to Python.pdf
Introduction to Python.pdf
 
Fundamentals of python
Fundamentals of pythonFundamentals of python
Fundamentals of python
 
Python-Certification-Training-Day-1-2.pptx
Python-Certification-Training-Day-1-2.pptxPython-Certification-Training-Day-1-2.pptx
Python-Certification-Training-Day-1-2.pptx
 
Lecture1_introduction to python.pptx
Lecture1_introduction to python.pptxLecture1_introduction to python.pptx
Lecture1_introduction to python.pptx
 
Vks python
Vks pythonVks python
Vks python
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Programming intro variables constants - arithmetic and assignment operators
Programming intro variables   constants - arithmetic and assignment operatorsProgramming intro variables   constants - arithmetic and assignment operators
Programming intro variables constants - arithmetic and assignment operators
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
 
علم البيانات - Data Sience
علم البيانات - Data Sience علم البيانات - Data Sience
علم البيانات - Data Sience
 
Python for Physical Science.pdf
Python for Physical Science.pdfPython for Physical Science.pdf
Python for Physical Science.pdf
 

Mais de Dr.YNM

Introduction to DSP.ppt
Introduction to DSP.pptIntroduction to DSP.ppt
Introduction to DSP.pptDr.YNM
 
Atmel.ppt
Atmel.pptAtmel.ppt
Atmel.pptDr.YNM
 
PIC Microcontrollers.ppt
PIC Microcontrollers.pptPIC Microcontrollers.ppt
PIC Microcontrollers.pptDr.YNM
 
Crystalstructure-.ppt
Crystalstructure-.pptCrystalstructure-.ppt
Crystalstructure-.pptDr.YNM
 
Basics of OS & RTOS.ppt
Basics of OS & RTOS.pptBasics of OS & RTOS.ppt
Basics of OS & RTOS.pptDr.YNM
 
Introducion to MSP430 Microcontroller.pptx
Introducion to MSP430 Microcontroller.pptxIntroducion to MSP430 Microcontroller.pptx
Introducion to MSP430 Microcontroller.pptxDr.YNM
 
Microcontroller-8051.ppt
Microcontroller-8051.pptMicrocontroller-8051.ppt
Microcontroller-8051.pptDr.YNM
 
Introduction to ASICs.pptx
Introduction to ASICs.pptxIntroduction to ASICs.pptx
Introduction to ASICs.pptxDr.YNM
 
VHDL-PRESENTATION.ppt
VHDL-PRESENTATION.pptVHDL-PRESENTATION.ppt
VHDL-PRESENTATION.pptDr.YNM
 
Basics of data communications.pptx
Basics of data communications.pptxBasics of data communications.pptx
Basics of data communications.pptxDr.YNM
 
CPLD & FPGA Architectures and applictionsplications.pptx
CPLD & FPGA Architectures and applictionsplications.pptxCPLD & FPGA Architectures and applictionsplications.pptx
CPLD & FPGA Architectures and applictionsplications.pptxDr.YNM
 
Transient response of RC , RL circuits with step input
Transient response of RC , RL circuits  with step inputTransient response of RC , RL circuits  with step input
Transient response of RC , RL circuits with step inputDr.YNM
 
CISC & RISC ARCHITECTURES
CISC & RISC ARCHITECTURESCISC & RISC ARCHITECTURES
CISC & RISC ARCHITECTURESDr.YNM
 
Lect 4 ARM PROCESSOR ARCHITECTURE
Lect 4 ARM PROCESSOR ARCHITECTURELect 4 ARM PROCESSOR ARCHITECTURE
Lect 4 ARM PROCESSOR ARCHITECTUREDr.YNM
 
Lect 3 ARM PROCESSOR ARCHITECTURE
Lect 3  ARM PROCESSOR ARCHITECTURE Lect 3  ARM PROCESSOR ARCHITECTURE
Lect 3 ARM PROCESSOR ARCHITECTURE Dr.YNM
 
Microprocessor Architecture 4
Microprocessor Architecture  4Microprocessor Architecture  4
Microprocessor Architecture 4Dr.YNM
 
Lect 2 ARM processor architecture
Lect 2 ARM processor architectureLect 2 ARM processor architecture
Lect 2 ARM processor architectureDr.YNM
 
Microprocessor Architecture-III
Microprocessor Architecture-IIIMicroprocessor Architecture-III
Microprocessor Architecture-IIIDr.YNM
 
LECT 1: ARM PROCESSORS
LECT 1: ARM PROCESSORSLECT 1: ARM PROCESSORS
LECT 1: ARM PROCESSORSDr.YNM
 
Microprocessor architecture II
Microprocessor architecture   IIMicroprocessor architecture   II
Microprocessor architecture IIDr.YNM
 

Mais de Dr.YNM (20)

Introduction to DSP.ppt
Introduction to DSP.pptIntroduction to DSP.ppt
Introduction to DSP.ppt
 
Atmel.ppt
Atmel.pptAtmel.ppt
Atmel.ppt
 
PIC Microcontrollers.ppt
PIC Microcontrollers.pptPIC Microcontrollers.ppt
PIC Microcontrollers.ppt
 
Crystalstructure-.ppt
Crystalstructure-.pptCrystalstructure-.ppt
Crystalstructure-.ppt
 
Basics of OS & RTOS.ppt
Basics of OS & RTOS.pptBasics of OS & RTOS.ppt
Basics of OS & RTOS.ppt
 
Introducion to MSP430 Microcontroller.pptx
Introducion to MSP430 Microcontroller.pptxIntroducion to MSP430 Microcontroller.pptx
Introducion to MSP430 Microcontroller.pptx
 
Microcontroller-8051.ppt
Microcontroller-8051.pptMicrocontroller-8051.ppt
Microcontroller-8051.ppt
 
Introduction to ASICs.pptx
Introduction to ASICs.pptxIntroduction to ASICs.pptx
Introduction to ASICs.pptx
 
VHDL-PRESENTATION.ppt
VHDL-PRESENTATION.pptVHDL-PRESENTATION.ppt
VHDL-PRESENTATION.ppt
 
Basics of data communications.pptx
Basics of data communications.pptxBasics of data communications.pptx
Basics of data communications.pptx
 
CPLD & FPGA Architectures and applictionsplications.pptx
CPLD & FPGA Architectures and applictionsplications.pptxCPLD & FPGA Architectures and applictionsplications.pptx
CPLD & FPGA Architectures and applictionsplications.pptx
 
Transient response of RC , RL circuits with step input
Transient response of RC , RL circuits  with step inputTransient response of RC , RL circuits  with step input
Transient response of RC , RL circuits with step input
 
CISC & RISC ARCHITECTURES
CISC & RISC ARCHITECTURESCISC & RISC ARCHITECTURES
CISC & RISC ARCHITECTURES
 
Lect 4 ARM PROCESSOR ARCHITECTURE
Lect 4 ARM PROCESSOR ARCHITECTURELect 4 ARM PROCESSOR ARCHITECTURE
Lect 4 ARM PROCESSOR ARCHITECTURE
 
Lect 3 ARM PROCESSOR ARCHITECTURE
Lect 3  ARM PROCESSOR ARCHITECTURE Lect 3  ARM PROCESSOR ARCHITECTURE
Lect 3 ARM PROCESSOR ARCHITECTURE
 
Microprocessor Architecture 4
Microprocessor Architecture  4Microprocessor Architecture  4
Microprocessor Architecture 4
 
Lect 2 ARM processor architecture
Lect 2 ARM processor architectureLect 2 ARM processor architecture
Lect 2 ARM processor architecture
 
Microprocessor Architecture-III
Microprocessor Architecture-IIIMicroprocessor Architecture-III
Microprocessor Architecture-III
 
LECT 1: ARM PROCESSORS
LECT 1: ARM PROCESSORSLECT 1: ARM PROCESSORS
LECT 1: ARM PROCESSORS
 
Microprocessor architecture II
Microprocessor architecture   IIMicroprocessor architecture   II
Microprocessor architecture II
 

Último

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Último (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Python Programming Language

  • 2. What is Python? • Python is a general purpose interpreted interactive object oriented and high level 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 10/27/15 yayavaram@yahoo.com
  • 3. contd.. • Python is multi-paradigm 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. 10/27/15 yayavaram@yahoo.com
  • 4. 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. 10/27/15 yayavaram@yahoo.com
  • 5. 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. 10/27/15 yayavaram@yahoo.com
  • 6. Why to Learn Python • There are large number of high-level programming languages like C ,C++,Java 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. 10/27/15 yayavaram@yahoo.com
  • 7. 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. 10/27/15 yayavaram@yahoo.com
  • 8. 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. 10/27/15 yayavaram@yahoo.com
  • 9. contd.. • The website appears as shown below. 10/27/15 yayavaram@yahoo.com
  • 10. contd.. • From the website you can download the suitable version based on • your OS (whether the OS is Windows ,MacOS or Linux). • And the Processor 32 bit or 64 bit. • For ex: if you are using 64-bit Windows system ,you are likely to download Windowsx86-64MSI Installer. • So just click on the link and download and install the Python Interpreter. 10/27/15 yayavaram@yahoo.com
  • 11. 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. 10/27/15 yayavaram@yahoo.com
  • 12. 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. 10/27/15 yayavaram@yahoo.com
  • 13. 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. 10/27/15 yayavaram@yahoo.com
  • 14. 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. 10/27/15 yayavaram@yahoo.com
  • 15. contd.. • The Screenshot for IDLE will be as shown below. The >>> is the prompt, telling you Idle is waiting for you to type something. 10/27/15 yayavaram@yahoo.com
  • 16. Your First Program • To develop the Python program ,click on the File and select NewFile. • This will open a new text editor where you can write your first program. • # Prints the words Hello Python print(“Hello Python”) print(“Its nice learning Python”) print(“Python is easy to learn”) 10/27/15 yayavaram@yahoo.com
  • 17. 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 press either F5 or click on Run module. 10/27/15 yayavaram@yahoo.com
  • 18. contd.. • After execution you find the output as Hello Python Its nice learning Python Python is easy to learn. 10/27/15 yayavaram@yahoo.com
  • 19. 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. 10/27/15 yayavaram@yahoo.com
  • 20. 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’ 10/27/15 yayavaram@yahoo.com
  • 21. 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 10/27/15 yayavaram@yahoo.com
  • 22. 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 (-). 10/27/15 yayavaram@yahoo.com
  • 23. 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. 10/27/15 yayavaram@yahoo.com
  • 24. 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 10/27/15 yayavaram@yahoo.com
  • 25. 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 . 10/27/15 yayavaram@yahoo.com
  • 26. 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? 10/27/15 yayavaram@yahoo.com
  • 27. 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 10/27/15 yayavaram@yahoo.com
  • 28. 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) 10/27/15 yayavaram@yahoo.com
  • 29. Additional assignment Operators • +=: x+= 2 is same as equal to x=x+2 • Similarly for subtraction: x-=2 is same as x=x-2 10/27/15 yayavaram@yahoo.com
  • 30. 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 10/27/15 yayavaram@yahoo.com
  • 31. 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 10/27/15 yayavaram@yahoo.com
  • 32. contd.. • Multiple substrings can be combined by using the concatenate sign(+) • Ex:”Peter”+ “Lee” is equivalent to the string “PeterLee” 10/27/15 yayavaram@yahoo.com
  • 33. 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 10/27/15 yayavaram@yahoo.com
  • 34. 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” 10/27/15 yayavaram@yahoo.com
  • 35. LIST • A List in Python is a collection data which are normally related. • Instead of storing a data as separate variables ,it can be stored as a LIST. • For ex: to store the age of 4 users , instead of storing them as user1Age,user2Age,user3Age and user4Age we can create a List of this data. • To some extent, lists are similar to arrays in C. Difference between them is that all the items belonging to a list can be of different data type.10/27/15 yayavaram@yahoo.com
  • 36. contd.. • To declare a List: ListName=[initial values]. Note ,always square brackets[] are used to declare a List. userAge =[20,42,23,25] • A List can also be declared without assigning any initial value to it. • listName=[]. This is an empty list with no items in it. 10/27/15 yayavaram@yahoo.com
  • 37. contd.. • To add items to the List ,we use append(). • The individual items of the List are accessed by their indexes.The index always starts from 0. • For ex; useAge=[20,25,35,45,65,55] here userAge[0]= 20,userAge[2]=35. • Similarly the index -1 denotes the last item • userAge[-1]=55 and userAge[-2]=65 10/27/15 yayavaram@yahoo.com
  • 38. SLICE • To access a set of items in a List we use Slice. • The notation used is x:y. • Whenever we use slice notation inPython, the item at the start index is always included ,but the item at the end is always excluded i.e y-1 is considered. • For ex:userAge=[15,25,30,45,50.65.55] the userAge[0:4] gives values from index 0 to 3 i.e 15,25,30,45 10/27/15 yayavaram@yahoo.com
  • 39. Add and Remove items • To add items the append() function is useful. • For ex :userAge.append(100) will add the value 100 to the List at the end. Now the new List is userAge=[15,25,30,45,50.65.55,100] • To remove any value from the List we write dellistName[index of item to be deleted] • For ex: del userAge[2] will give a new List userAge=[15,25,45,50,65,55,100] 10/27/15 yayavaram@yahoo.com
  • 40. Program • # declare the list myList[2,5,4,5,”Ram”] • # to print the entire list print(‘myList’) • # to print the third item print(myList[3]) The output is “Ram” • # to print the last but one item print(myList[-2]) 10/27/15 yayavaram@yahoo.com
  • 41. Tuple • Tuples are also a type of Lists.But the difference is they can’t be modified. • A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses(). • The main differences between lists and tuples are: • Lists are enclosed in brackets [ ] and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. • Tuples can be thought of as read-only lists. 10/27/15 yayavaram@yahoo.com
  • 42. contd.. • Declaring a Tuple tupleName=( ‘Raju',786 , 2.23, ‘cdef',70.2 ) monthsOfYear(“Jan”,”Feb”,”March”,”April”) • monthsOfYear[0]=“Jan” • monthsOfYear[-1]= “April” 10/27/15 yayavaram@yahoo.com
  • 43. contd.. • print tuple: # Prints complete list print • tuple[0] : # Prints first element of the list • print tuple[1:3]: # Prints elements starting from 2nd till 3rd print • tuple[2:] : # Prints elements starting from 3rd element • print tinytuple * 2 : # Prints list two times 10/27/15 yayavaram@yahoo.com
  • 44. Dictionary • Dictionary is a collection of related data PAIRS. • The general Syntax is dictionaryName={dictionarykey:data} The same dictionary key should not be used twice • For Ex: to store the username and age of 4 users we can write • myDictionary={“peter”:25,”Ram”:15,”Carl”:5 0,”Kundan”: 20} 10/27/15 yayavaram@yahoo.com
  • 45. contd… • Dictionary can also be declared using “dict()” method. • userNameAndAge=dict(peter=25,Ram=20,Carl =30, Krish=“not available”) • Here round brackets parenthesis) are used instead of curly brackets. • dictionaryName={ } denotes an empty dictionary with no items init 10/27/15 yayavaram@yahoo.com
  • 46. Add items to Dictionary • To add items to a dictionary the syntax is dictionaryName[dictionarykey]=data. To add “Sam”=40 to the dictionary , userNameAndAge[“Sam”]=40 • Now the dictionary will become userNameAndAge=dict(peter=25,Ram=20,Car l=30, Krish=“not available”,Sam=40) 10/27/15 yayavaram@yahoo.com
  • 47. contd.. • To delete or remove items from a dictionary the syntax is del dictionaryName[dictionarykey] • Ex: To remove “Ram”:20 the syntax is del usernameAndAge[‘’Ram”] • Now the dictionary is userNameAndAge={“peter”:25,”Carl”:30, “Krish”:“not available”,”Sam”:40} 10/27/15 yayavaram@yahoo.com
  • 48. Declare Dictionary –Alternative way • Dictionary can also be declared by alternative method • myDict={“one”:1.45,5.8:”TwopointFive”,3:”+”,4.5:2} print(mydict) The output is {2.5:’TwopointFive’,3:’+’:4.5,4.5:2} 10/27/15 yayavaram@yahoo.com
  • 49. 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. 10/27/15 yayavaram@yahoo.com
  • 50. 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 10/27/15 yayavaram@yahoo.com
  • 51. 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. 10/27/15 yayavaram@yahoo.com
  • 52. If statement • 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 10/27/15 yayavaram@yahoo.com
  • 53. Program • Open your Idle and type the program • userInput=input(“Enter 1 or 2”) if userInput == “1”: print(“Hello Python”) print(“how are you”) elif userInput == “2”: print(“python great”) print(“I Love Python”) else: print(“ you entered invalid number”) 10/27/15 yayavaram@yahoo.com
  • 54. 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) 10/27/15 yayavaram@yahoo.com
  • 55. contd.. • Ex: pets = [‘cats’,’dogs’,’rabbits’,’hamsters’] for myPets in pets: print(myPets) In this program,first we declared the list pets and give the members ‘cats’,’dogs’,’rabbits’ and ‘hamsters’.Next the statement for myPets: loops through the pets list and assigns each member in the list to the variable myPets. 10/27/15 yayavaram@yahoo.com
  • 56. 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,myPets in enumerate(pets): • print(index,myPets) 10/27/15 yayavaram@yahoo.com
  • 57. contd.. • The output is: 0 cats 1 dogs 2 rabbits 3 hamsters 10/27/15 yayavaram@yahoo.com
  • 58. 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) 10/27/15 yayavaram@yahoo.com
  • 59. 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] 10/27/15 yayavaram@yahoo.com
  • 60. 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 10/27/15 yayavaram@yahoo.com
  • 61. While Loop • A while loop repeatedly executes instructions inside the loop while a certain condition remains true. • The syntax of a while loop is while the condition is true do the Task A For Ex: Counter= 5 While counter > 0: 10/27/15 yayavaram@yahoo.com
  • 62. contd.. • print(‘counter=‘,counter) counter = counter-1 When you run the program the output will be counter=5 counter=4 counter=3 counter=2 counter=1 10/27/15 yayavaram@yahoo.com
  • 63. 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 10/27/15 yayavaram@yahoo.com
  • 64. 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 reaches the value 6 . 10/27/15 yayavaram@yahoo.com
  • 65. 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 10/27/15 yayavaram@yahoo.com
  • 66. 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 j=6 When j=6,the line after the continue keyword is not printed. 10/27/15 yayavaram@yahoo.com
  • 67. 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 occurs 10/27/15 yayavaram@yahoo.com
  • 68. 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 remaining of the try block is ignored and the statement in the except block is executed. 10/27/15 yayavaram@yahoo.com
  • 69. Functions-Modules • Functions are pre-written codes that perform a dedicated task. • For ex: the function sum() add the numbers. • Some function require us to pass data in for them to perform their task.These data are known as parameters and we pass them to the function by enclosing their values in parenthesis() separated by commas. • The print() function is used to display the text on the screen. 10/27/15 yayavaram@yahoo.com
  • 70. contd.. • replace() is another function used for manipulating the text strings. • For Ex: “helloworld”.replace(“world”,”Universe”) here “world” and “universe” are the parameters.The string before the Dot is the string that will be affected.So,”hello world” will be changed to “hello Universe” 10/27/15 yayavaram@yahoo.com
  • 71. Your own Functions • Python has has flexibility to define your own functions and can be used them in the program. • The syntax is: def functionName(parameters): code for what the function should do return[expression] The two keywords here are “def” and “return” 10/27/15 yayavaram@yahoo.com
  • 72. contd.. • def tells the program that the indented code from the next line onwards is part of the function and return is the keyword that is used to return an answer from the function. • Once the function executes a return statement ,it will exit. • If your function need not return any value you can write return or return None. 10/27/15 yayavaram@yahoo.com
  • 73. contd.. • Ex:def checkIfPrime(numberToCheck): for x in range(2,numberToCheck): if(numberToCheck%x==0); return False return True The above function will check whether the given number is a prime number or not.If the number is not a prime number it will return False otherwise return True. 10/27/15 yayavaram@yahoo.com
  • 74. Variable Scope • An important concept to understand while defining a function is the concept of variable scope. • Variables defined inside a function are treated differently from variables defined outside. • Any variable defined inside a function is only accessible within the function and such functions are known as local variables. • Any variable declared outside a function is known as global variable and it is accessible anywhere in the program. 10/27/15 yayavaram@yahoo.com
  • 75. Importing Modules • Python provides a large number of built-in functions and these are saved in files known as modules. • To use the modules in our program ,first we have to import them into our programs. and this is done by using the keyword import. Ex: To import the module random we write import random 10/27/15 yayavaram@yahoo.com
  • 76. contd.. • To use the randrange() function in the random module we use random.randrange(1,10). This can also be written as r.randrange(1,10). • If we want to import more than one functions we separate them with a comma • To import the randrange() and randint() functions we write from random import randrange,randint. 10/27/15 yayavaram@yahoo.com
  • 77. Creating own Module • Creating a module is simple and it can be done by saving the file with a .py extension and put it in the same folder as the python file that you are going to import it from. • Suppose you want to use the checkIfPrime()function defined earlier in another Python script.First save the code above as prime.ph on your desktop. 10/27/15 yayavaram@yahoo.com
  • 78. contd.. • The prime.py should have the following code. def checkIfPrime(numberToCheck): for x in range(2,numberToCheck): if(numberToCheck%x==0): return False return True Next create another python file and name it useCheckIfPrime.py This should have the following code 10/27/15 yayavaram@yahoo.com
  • 79. contd.. • Import prime answer = prime.checkIfPrime(17) print(answer) • Now run useCheckIfPrime.py. • You get the output as True • Suppose you want to store prime.py and useCheckIfPrime.py in different folders, you have to give the python’s system path. 10/27/15 yayavaram@yahoo.com
  • 80. contd.. • Create a folder called ‘MyPythonModules’ in the C drive to store prime.py. • Add the following code to the top of your useCheckIfPrime.py file. (i.e before the import prime line) • Import sys if’C:MyPythonModules’not in sys.path: sys.path.append(‘C:MyPythonModules’) here sys.path refers to python’s system path. 10/27/15 yayavaram@yahoo.com
  • 81. contd.. • The code above appends the folder’C:MyPythonModules’ to your system path. • Now you can put prime.py in C:MyPythonModules and checkIfPrime.py in any other folder of your choice. 10/27/15 yayavaram@yahoo.com
  • 82. Handling Files • The basic type of a file is a text file.It consists of multiple lines of text.To create a text file type some lines of text like “I am learning Python programming. Python is an interesting language” . save this text file as myfile.txt on your desktop. Next open Idle and type the code below. 10/27/15 yayavaram@yahoo.com
  • 83. contd.. • f= open(‘myfile.txt’,’r’) firstline=f.readline() secondline=f.readline() print(firstline) print(secondline) f.close() Save this code as fileOperation.py on your desktop. • To open a file we can use open() function. 10/27/15 yayavaram@yahoo.com
  • 84. contd.. • The open function require two parameters:The first one is the path to the file and the second parameter is the mode. • The commonly used modes are • ‘r’mode: For reading only • ‘w’mode: For writing only. • ‘a’ mode: For appending .If the specified file does not exist ,it will be created and if the file exist ,any data written to the file is automatically added at the end of the file. 10/27/15 yayavaram@yahoo.com
  • 85. contd.. • ‘r+’mode:For both reading and writing. • After opening the file firstline=f.readline() reads the firstline in the file and assigns it to the variable firstline. Each time the readline() function is called ,it reads a new line from the file. When you run the program the output will be I am learning Python programming. Python is an interesting language. 10/27/15 yayavaram@yahoo.com
  • 86. contd.. • In the output ,you can observe that a line break is inserted after each line. • Because the function readline() adds the ‘n’ characters to the end of each line. • If you don’t want the extra line between each line of text ,you can wrte print(firstline,end=‘’).This will remove the ‘n’ characters • f.close() function closes the file.One should always close the file after reading is done.It will freeup any system resources. 10/27/15 yayavaram@yahoo.com
  • 87. For Loop to Read Text Files • For loop can also be used to read a text file. • For ex: f = open(‘myfile.txt’,’r’) for line in f: print(line,end=‘’) f.close() The for loop helps to read the text file line by line. 10/27/15 yayavaram@yahoo.com
  • 88. Opening and reading Text files by Buffer size • To avoid the too much usage of memory we can use the read() function instead of readline() function. • Ex: msg=inputfile.read(10) The program reads only the next 19 bytes and keeps doing it until the entire file is read. 10/27/15 yayavaram@yahoo.com
  • 89. Deleting and re-naming the Files • remove() and rename() are the two important functions available as modules which have to be imported before they are used in a program. • The remove() function deletes a file.the syntax is remove(filename) • Ex: remove(‘myfile.txt’) • To rename a file the function rename() is used. • The syntax is rename(old name,new name) • rename(‘oldfile.txt,’newfile.txt’) will rename oldfile.txt to newfile.txt 10/27/15 yayavaram@yahoo.com
  • 90. Simple Examples-1 • Python code to find the area of a triangle: • First open Idle and type the code • a = float(input(‘Enter first side:’)) b= float(input(‘Enter first side:’)) c= float(input(‘Enter first side:’)) s=(a+b+c)/2 area=(s*(s-a)*(s-b)*(s-c))**0.5 print(‘The area of the triangle is %0.2f’%area) 10/27/15 yayavaram@yahoo.com
  • 91. Simple Examples-2 • Python code to find Square root num=float(input(‘Enter a number:’)) num_sqrt=num**0.5 print(‘The square root of %0.3f is % 0.3f% (num,num_sqrt)) This program is saved with .py extension and executed .the out will ask to enter a number and on entering a number it gives the squre root of the number. 10/27/15 yayavaram@yahoo.com
  • 92. Simple Examples-3 • Python code for factorial of a number • Num= int(input(‘Enter a number:’)) factorial = 1 if num < 0: print(‘sorry ,factorial does not exist for negative numbers’) elif num == 0; print(“The factorial of 0 is 1”) 10/27/15 yayavaram@yahoo.com
  • 93. contd.. • else for i in range(1,num+1): factorial = factorial*i print(“The factorial of “,num,”is”,factorial) • Save the program with .py extension and run module or press F5. • The program will ask to enter a number • After entering the number you get the output 10/27/15 yayavaram@yahoo.com
  • 94. Simple Examples-4 • Print all the Prime numbers in an Interval. • Lower=int(input(‘Enter lower range:’)) upper=int(input(‘Enter upper range)) for num in range(lower,upper+1): if num>1: for i in range(2,num): if(num%i)==0: break else: print(num) 10/27/15 yayavaram@yahoo.com
  • 95. Simple Examples-5 • Code to swap two numbers • x= input(‘Enter value of x:’) y=input(‘Enter value of y:’) temp = x x=y y= temp print(‘The value of x after swapping: { }’format(x)) print(‘The value of y after swapping: { }’format(y)). Run the code and observe the output 10/27/15 yayavaram@yahoo.com
  • 96. Simple Examples-6 • Solve a quadratic equation ax2+bx+c=0 • Import cmath # add complex math module a= float(input(‘Enter a:’)) b= float(input(‘Enter b:’)) c= float(input(‘Enter c:’)) d= (b**2)-(4*a*c) //calculate discriminant sol1=(-b-cmath.sqrt(d))/(2*a) sol2=(-b+cmath.sqrt(d))/(2*a) print(‘The solutions are {0} and {1}.format(sol1,sol2)) 10/27/15 yayavaram@yahoo.com
  • 97. Simple Examples-7 • To find ASCII value of a given characters • # Take character from user c = input("Enter a character: ") print("The ASCII value of '" + c + "' is",ord(c)) Note: here ord(c) is a builtin function available in Python to find the ASCII value of a character 10/27/15 yayavaram@yahoo.com
  • 98. ACKNOWLEDGEMENT • I don’t claim any ownership for this lecture as it is the collection from many books &web resources • I thank the authors of the books and web resources from where I collected the information and code. • The sole objective behind this effort is only to encourage and inspire if possible some young minds towards this wonderful programming language -Python 10/27/15 yayavaram@yahoo.com
  • 99. References • Learn Python in One Day and Learn It Well - Jamie Chan. • Sams Teach Yourself Python Programming for Raspberry. • Programming Python, 5th Edition,O'Reilly Media. • Python Cook Book O'Reilly Media. 10/27/15 yayavaram@yahoo.com