Python fundamentals
System Requirements
➢Python runs on Windows, Linux / Unix, Mac OS X, and
has been ported to the Java and .NET virtual machines
also.
➢No special hardware requirement
Downloading and Installation
•Log on to www.python.org
• The home page looks as .....
➢Click on Download Python Now Hyperlink or
Download option from the side menu..
➢ The Download Python Page appears. Click on the version of
Python that you want to install (Python 2.7 or Python 3.3)
➢ We shall be working with Python 2.7.4
Choose the required format for download
(Windows x86 MSI Installer (2.7.4))
Installation in Progress………
Installation Complete
To Start working in
Python
Welcome Screen of Python IDLE
Python Shell
Interactive Mode Script Mode
Interactive Mode
➢ Commands are executed directly at the prompt
Examples :-
>>> print 5+8
13
>>>6+10
16
>>>Print “Welcome to the world of Python”
Welcome to the world of Python
>>> (10+5)/3
5
Interactive Mode : Sequence of commands
Example 1 Example 2
>>> x=10 >>> a=10
>>>y=40 >>>a+1 , a-1
>>>Z=x+y (11,9)
>>>print Z
50
❑ to repeat the prior command in the
interactive window , use to scroll
backward through the command history
and key to scroll forward.
To leave the interpreter and
return to shell
•Ctrl+D or
•Type quit ()
Script Mode
➢File New
➢Type Python program in a file
➢ Save it . Default extension is .py
➢ then use interpreter to execute the
contents from the file by
▪Can use Run option or press F5
▪type the function name at command
prompt
Variables / Objects in Python
Every object/variable has
Identity Type Value
Identity
❑ Variable’s address in memory
❑ does not change once it has been
created.
The id() command gives the identity number of a
variable, it’s unique for each variable
Syntax : id(variable)
Example :
>>>id(x)
4325671
Type (Data Type)
A set of values and the
allowable operations on
those values.
Data types supported by Python
Number Data Type
1. Number
1.Integer & Long
Example
>>>a=10
>>>b=1234567L
>>>print a,b
10, 123456L
2. Floating Point ‘j’ i
su
Example i m agi sed f
nar or
>>>y=12.89 yp
>>>print y art
12.89
3. Complex
Example
>>>x= 1+0j
>>>print x.real , x.imag
1.0, 0.0
Type Conversion
•Automatic type conversion from int to float if required
>>> f=78.90876
>>> i=9
>>> i=i+f
>>> print i
87.90876
• very big integer is automatically converted to long
•To know the datatype of a variable use type()
>>> var=1234
>>> type(var)
<type 'int'>
>>> var=var*98765432
>>> type(var)
<type 'long'>
Integers (contd)
4. Boolean
•Boolean Type consists of a two values : True & False
•Boolean True is non zero, non null and non empty
Example
>>> flag=True
>>> type(flag)
<type 'bool'>
>>> flag=False
>>> type(flag)
<type 'bool'>
2. None
used to signify the absence of value / false in a situation
3.Sequence
•Ordered collection of items , indexed by integers
• Combination of mutable and non mutable data types
Sequence Data Type
String Lists Tuple
•An ordered • A sequence of • are sequence of
sequence of letters values of any type values of any type
and characters
•Values in the list •Are indexed by
•Enclosed in “ “ or ‘ are called items integers
‘ and are indexed
•Are immutable
•Are immutable •Are mutable
•Are enclosed in ()
Example •Are enclosed in [] Example
Example (2,4)
>>>a=“Ram” [‘spam’ , 20, 13.5]
Data Types (contd.)
4.Sets :
•an unordered collection of values of any type
•No duplicate entries allowed
•Are immutable
Example
S=set([1,2,3,4])
5.Mapping
• an unordered data type for eg: dictonaries
•A dictonary can store any number of Python objects
enclosed in curly brackets
Example :
D= {1:’a’ , 2:’b’, 3:’c’}
Value of an object(variable)
to bind value to a variable assignment operator(=)
can be used
Example :
>>>x=1256
Mutable and Immutable Variables
Mutable Variable :
one whose value may change in place
Immutable Variable :
# Change of value will not happen in place.
# Modifying an immutable variable will rebuild the
same variable.
Example
>>>x=5
will create a value 5 referenced by x
x 5
>>>y=x
will make y refer to 5 of x
x
5
y
>>>x=x+y
RHS results to 10
value assigned to LHS (x)
x rebuilds to 10
x 10
y 5
Example
x = something # immutable type
y=x
print x
// some statement that operates on y
print x # prints the original value of x
x = something # mutable type
y=x
print x
// some statement that operates on y
print x # might print something different
Example
Immutable variable - x
x = 'foo'
y=x
print x # foo
y += 'bar'
print x # foo
Mutable Variable - x
x = [1, 2, 3]
y=x
print x # [1, 2, 3]
y += [3, 2, 1]
print x # [1, 2, 3, 3, 2, 1]
Points to remember about variables……
•Are created when they are first assigned a value
•Refer to an object
•Must be assigned a value before using them in
any expression
•Keywords cannot be used as variable names
Operators
Arithmetic Assignme
nt
Relational Logical
Operators when applied to operands form an expression
Arithmetic Operators
Symbol Description Example 1 Example 2
>>>55+45 >>> ‘Good’ + ‘Morning’
+ Addition
100 GoodMorning
>>>55-45 >>>30-80
- Subtraction
10 -50
>>>55*45 >>> ‘Good’* 3
* Multiplication
2475 GoodGoodGood
>>>17/5
3 >>>28/3
/ Division*
>>>17/5.0 9
3.4
Remainder/Modul >>>17%5 >>> 23%2
%
o 2 1
>>>2**3 >>>2**8
** Exponentiation 256
8
>>>7.0//2 >>>3/ / 2
// Integer Division
3.0 1.0
Relational Operators
Symbol Description Example 1 Example 2
>>>7<10
True >>>‘Hello’< ’Goodbye’
< Less than >>> 7<5 False
False >>>'Goodbye'< 'Hello'
>>> 7<10<15 True
True
>>>7>5 >>>‘Hello’> ‘Goodbye’
> Greater than True True
>>>10<10 >>>'Goodbye'> 'Hello'
False False
>>> 2<=5 >>>‘Hello’<= ‘Goodbye’
<= less than equal to True False
>>> 7<=4 >>>'Goodbye' <= 'Hello'
False True
>>>10>=10 >>>’Hello’>= ‘Goodbye’
>= greater than equal to True True
>>>10>=12 >>>'Goodbye' >= 'Hello'
False False
>>>10!=11 >>>’Hello’!= ‘HELLO’
! =, <> not equal to True True
>>>10!=10 >>> ‘Hello’ != ‘Hello’
False False
>>>10==10 >>>“Hello’ == ’Hello’
== equal to True True
>>>10==11 >>>’Hello’ == ‘Good Bye’
False False
Logical Operators
Symbol Description
If any one of the operand is true,
or
then the condition becomes true.
If both the operands are true,
and
then the condition becomes true.
Reverses the state of
not
operand/condition.
Assignment Operator
Symbol Description Example Explanation
>>>x=12* *we will use it as initial
Assigned values from right side
= >>>y=’greeting value of x for following
operands to left variable
s’ examples.
Added and assign back the result to left Will change the value of x to
+= >>>x+=2
operand 14
Subtracted and assign back the result
-= x-=2 x will become 10
to left operand
Multiplied and assign back the result to
*= x*=2 x will become 24
left operand
Divided and assign back the result to
/=
left operand x/=2 x will become 6
Taken modulus using two operands x will become 0
%=
and assign the result to left operand x%=2
Performed exponential (power) x will become 144
**= calculation on operators and assign x**=2
value to the left operand
Performed floor division on operators x / /= 2 x will become 6
//=
and assign value to the left operand
Points to remember about operators...
✓Same operator may perform a different function
depending on the data type of the operands
❑ Division operator ( / )behaves differently with
integers and floats
❑ Multiplication operator( * ) and addition operator
( + ) behave differently on integers and strings
Expressions and Statements
Expression:
A consists of values i.e. constants or variables
and operators
❑ Examples
2+x
50.8/4+(20-4)
Statement:
A unit of code that a python interpreter can
execute
❑ Examples
>>>print 90 # print statement
>>>x=60+40 # addition/assignment statement
Points to remember about Expressions…….
❖In case of operands with different data types ,
implicit typecasting occurs.
❑ Examples
>>> print 0.8/4+(20-4)
16.2
All integers are promoted to floats and the final
result of the expression is a float value
❖ In case of multiple sub expressions in a single
expression , general precedence rules apply
Precedence of Operators
Operator Description
** Exponentiation (raise to the power)
+,- unary plus and minus
Multiply, divide, modulo and floor
* , /, %, //
division
+,- Addition and subtraction
relational operators for
<, <=, >, >=
comparision
==, != Equality operators
%=,/ =, //=, - = , + =, * = , ** = Assignment operators
not; and; or Logical operators
While working in Python……
✓ Write one python statement per line (Physical Line).
✓ Comment starts with ‘#’ and ends at the end of a line.
✓ When entering statement(s) in interactive mode, an
extra blank line is treated as the end of the indented
block.
✓ White space in the beginning of line is part of
indentation, elsewhere it is not significant
✓If a statement runs into multiple physical lines , a ‘ \’ is
used at the end of a physical line.
Input-Output Facility
• Helps to interact with end user to accomplish
the desired task.
• Functions available for input are :
❑ raw_input()
❑ input ( )
raw_input()
• Syntax
raw_input ([prompt])
• e.g. (in interactive mode)
>>>x=raw_input (‘Enter your name : ’)
Enter your name : ABC
Concatenation of strings using
raw_input( ) method
>>>Input1=raw_input(“Enter the first Name: ”)
Enter the first Name: KVS
>>>Input2=raw_input(“Enter the second Name: ”)
Enter the second input: DELHI
>>>Input1+Input2
>>>’KVS DELHI’
Addition of two numbers
using raw_input( ) method
>>>Input1=raw_input(“Enter the first input:”)
Enter the first input: 78
>>>Input2=raw_input(“Enter the second
input:”)
Enter the second input: 100
i red
>>>Input1+Input2 not t
hed e s
i s
his
>>>’78100’ O o p s! T
ut.
o u t p
Addition of two numbers using
raw_input( ) method
>>>Input1=int(raw_input(“Enter the first input:”))
Enter the first input: 78
>>>Input2=int(raw_input(“Enter the second input:”))
Enter the second input: 100
>>>Input1+Input2
>>>178
raw_input() –Numeric data
• typecast the string data accepted from user to appropriate
Numeric type.
• e.g.
>>>y=int(raw_input(“enter your roll no”))
• E.g.
• >>>z = float(raw_input(“ enter the float value”)
input()
• Syntax
input ([prompt])
• Eg:
x= input (‘enter data:’)
Enter data: 2+ 1/2.0
Will supply 2.5 to x
Output
• For output in Python we use ‘print ’.
• Syntax:
print expression/constant/variable
• Example:
>>> print “Hello”
Hello
>>> print 5.5
5.5
>>> print 4+6
10
Basic Input Output and Process
1. WAP to add 2 numbers.[R=a+b]
2. WAP to add 4 numbers.[R=a+b+c+d]
3. WAP to multiply 3 numbers.[R=a*b*c]
4. WAP to find average 5 numbers[R=(a+b+c+d+e)/5]
5. WAP to display age after 15 years.[nage =age+15]
6. WAP to display a3 numbers [R=a*a*a]
7. WAP to find the area of squire. [A=a*a]
8. WAP to find the area of rectangle [A=a*b]
9. WAP to find the result XN pow()
10. WAP to find the perimeter of rectangle[A=2*(l+ b) ]
11. WAP to find the area of circle [A=3.14*r*r]
12. WAP to find the circumference of circle [C=2*3.14*r]
13. WAP to swap the values of two variables.[a= a + b; b=a – b; a= a – b;]
14. WAP to input Hours, Minutes and Seconds and display in seconds.
[TS=H*60*60+M*60+S]
15. WAP to input cost and display cost after increasing 25% [cost+(cost*25)/100]
THANKS