Basics of Python
S.Madhumalar
Assistant Professor
C.P.A College, Bodinayakanur
1. Python Overview
Compiling and interpreting
compile
execute
output
source code
Hello.java
byte code
Hello.class
interpret
output
source code
Hello.py
History of Python:
Python Features
Python Features (cont’d)
Python Environment
2. Python - Basic Syntax
>>> print "Hello, Python!";
Hello, Python!
>>> 3+4*5;
23
Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active.
For example, put the following in one test.py, and run,
print "Hello, Python!";
print "I love COMP3050!";
The output will be:
Hello, Python!
I love COMP3050!
Python Identifiers:
Python Identifiers (cont’d)
Reserved Words:
and | exec | not |
assert | finally | or |
break | for | pass |
class | from | |
continue | global | raise |
def | if | return |
del | import | try |
elif | in | while |
else | is | with |
except | lambda | yield |
Keywords contain lowercase letters only.
Lines and Indentation:
if True:
print "Answer“;
print "True" ;
else:
print "Answer“;
print "False"
Multi-Line Statements:
total = item_one + \
item_two + \
item_three
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
Quotation in Python:
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is made up of multiple lines and sentences."""
Comments in Python:
Using Blank Lines:�
Multiple Statements on a Single Line:
import sys; x = 'foo'; sys.stdout.write(x + '\n')
Multiple Statement Groups as Suites:
Compound or complex statements, such as if, while, def, and class, are those which require a header line and a suite.
Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite.
if expression :
suite
elif expression :
suite
else :
suite
3. Python - Variable Types
Assigning Values to Variables:
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print miles
print name
Multiple Assignment:
a = b = c = 1
a, b, c = 1, 2, "john"
Standard Data Types:
Python has five standard data types:
Python Numbers:
var1 = 1
var2 = 10
Python supports four different numerical types:
Number Examples:
int | long | float | complex |
10 | 51924361L | 0 | 3.14j |
100 | -0x19323L | 15.2 | 45.j |
-786 | 0122L | -21.9 | 9.322e-36j |
80 | 0xDEFABCECBDAECBFBAEl | 32.3+e18 | .876j |
-490 | 535633629843L | -90 | -.6545+0J |
-0x260 | -052318172735L | -3.25E+101 | 3e+26J |
0x69 | -4721885298529L | 70.2-E12 | 4.53e-7j |
Python Strings:
Example:
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 6th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Lists:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
Output:
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Python Tuples:
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
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
print tuple + tinytuple # Prints concatenated lists
OUTPUT:
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
Python Dictionary:
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two“
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values
OUTPUT:
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Data Type Conversion:
Function | Description |
int(x [,base]) | Converts x to an integer. base specifies the base if x is a string. |
long(x [,base] ) | Converts x to a long integer. base specifies the base if x is a string. |
float(x) | Converts x to a floating-point number. |
complex(real [,imag]) | Creates a complex number. |
str(x) | Converts object x to a string representation. |
repr(x) | Converts object x to an expression string. |
eval(str) | Evaluates a string and returns an object. |
tuple(s) | Converts s to a tuple. |
list(s) | Converts s to a list. |
set(s) | Converts s to a set. |
dict(d) | Creates a dictionary. d must be a sequence of (key,value) tuples. |
frozenset(s) | Converts s to a frozen set. |
chr(x) | Converts an integer to a character. |
unichr(x) | Converts an integer to a Unicode character. |
ord(x) | Converts a single character to its integer value. |
hex(x) | Converts an integer to a hexadecimal string. |
oct(x) | Converts an integer to an octal string. |