Lecture_TWP_Python_A01_1a_Introduction
Lecture_TWP_Python_A01_1a_Introduction
Nirjhar Dhang
√
Version : 1.732 : 3
Created on : March 09, 2011
Last revision : January 11, 2025
Introduction to Python
Students are encouraged to use Python
for preparation of assignments of the following subjects:
Please note:
print "Hello"
Classic Hello program
print "Hello"
Hello
Classic Hello program : Python 3
print("Hello")
Classic Hello program : Python 3
print("Hello")
Hello
Variables
Variables
No need to declare
Need to assign (initialize)
use of uninitialized variable raises exception
Everything is a "variable": even functions, classes, modules
Not typed
if support == ’fixed’:
displacement=0.0
else:
displacement=’undefined’
Variables
x = 10
y = ’Sapiens’
print(x)
print(y)
10
Sapiens
Numbers
Python Numbers
There are three numeric types in Python:
int
float
complex
x = 1
y = 2.1
z = 3j
print(type(x))
print(type(y))
print(type(z))
<class ’int’>
<class ’float’>
<class ’complex’>
Usage of [] {} () in Python
Usage of [] {} () in Python
[] List L=[1,2,3,’A’,’B’]
{} Dictionary D={’id’:1,’x’:5.0,’y’:2.0}
() Tuple P=(1,2,3)
Condition
Condition
For loop
for i in range(5):
print ( i,i*i )
>>>
0 0
1 1
2 4
3 9
4 16
Loop
While loop
i=0
while i < 5:
print ( i,i*i )
i=i+1
>>>
0 0
1 1
2 4
3 9
4 16
Loop
>>> >>>
0 0 0 0
1 1 1 1
2 4 2 4
3 9 3 9
4 16 4 16
Function
Function
def Grade(marks):
if marks >= 90:
grade=’Ex’
elif marks >= 80:
grade=’A’
elif marks >= 70:
grade=’B’
elif marks >= 60:
grade=’C’
elif marks >= 50:
grade=’D’
elif marks >= 35:
grade=’P’
else:
grade=’F’
return grade
Class
Class
from math import sqrt
class Triangle(object):
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
def area(self):
s=0.5*(self.a+self.b+self.c)
A=sqrt(s*(s-self.a)*(s-self.b)*(s-self.c))
return A
A=Triangle(a=3,b=4,c=5)
print ( A.area() )
Class
class Triangle(object):
def __init__(self,**kwargs):
for key, value in kwargs.items():
vars(self)[key]=value
def area(self):
s=0.5*(self.a+self.b+self.c)
A=sqrt(s*(s-self.a)*(s-self.b)*(s-self.c))
return A
A=Triangle(a=3,b=4,c=5)
print ( A.area() )
Class
File:test.dat
1 0.0 0.0 0.0
2 5.0 0.0 0.0
3 5.0 4.0 0.0
fout=open(’test.out’,’w’)
with open(’test.dat’,’r’) as datafile:
for line in datafile:
nums=line.split()
nid=int(nums[0])
x=float(nums[1])
y=float(nums[2])
z=float(nums[3])
print ( nid,x,y,z )
fout.write(’%3d %8.3f %8.3f %8.3f\n’%(nid,x,y,z))
fout.close()
How Python is Compiled?
How Python is Compiled?
Lexer -> token stream
Uses a stack to parse whitespace!
Parser -> concrete syntax tree
Simple & LL(1) parsing engine
Filter -> abstract syntax tree (uses ASDL)
Pass 1 -> symbol table
Pass 2 -> bytecode
Bytecode is in-memory objects
Saving to disk (.pyc file) is just a speed hack
Try Python 3
using Spyder or Jupyter Notebook under Anaconda 3
Spyder 3
Spyder 3
Jupyter
Python 3
In other words, do not use the same name as your import name
You will get import error and will struggle for days to find the
solution.
Summary
Summary