3 March 2018 Ieee Ece Traning Presentation
3 March 2018 Ieee Ece Traning Presentation
3 March 2018 Ieee Ece Traning Presentation
1. Go to www.python.org
2. Click on Downloads
3. From the drop down list, click on Windows
4. Then click on Latest Python 3 Release - Python 3.6.3
5. In the page that opens i.e.
https://www.python.org/downloads/release/python-363/
Scroll down to Files Section
6.For 64 bit Windows click on Windows x86-64 executable installer
7 For 32 bit windows click on Windows x86 executable installer
Stepwise Install Instructions
Guido van Rossum needed a name that was short, unique, and slightly
mysterious, so he decided to call the language Python.
The logo was later matched to the name being synonymous with Snake.
Python Prompt and IDLE
Python prompt is >>>. It is command line interpreter for Python code,
executes one line of code at a time.
IDLE: Python’s Integrated Development and Learning Environment.
Coded in 100% pure python using tkinter GUI toolkit
Cross platform- works same on Windows, Unix and Mac
It is python shell window(interactive interpreter)with colorizing of code input,
output and error messages.
Multi-window text editor with multiple undo, colorizing , smart indent, call
tips, auto completion.
Search and replace, debugger, configuration, browsers and other dialogs
Comments
Explicit - Using \ character we can join two or more physical lines into one
logical line
If 1900 < year < 2100 and 1<=month <=12 \
and 1<= day<= 31 and 0<= hour<24\
and 0<=minute<60 and 0<=second < 60:
return 1
Implicit – Expressions in parentheses, square brackets or curly braces can be
split over more than one physical line without using backslashes.
Month_names=[‘Jan’,’feb’,’mar’,’apr’,
‘may’,’jun’,’jul’,’aug’,
‘sep’,’oct’,’nov’,’dec’]
Indentation
Everything is an object in Python, so there are types like module, function, class,
method, file, and even compiled code
Try Boolean
>>> size = 1
>>> size < 0
False
>>> size = 0
>>> size < 0
False
>>> size = -1
>>> size < 0
True
Numbers
Python supports both integers and floating point numbers. There’s no type
declaration to distinguish them;
Python tells them apart by the presence or absence of a decimal point.
>>> type(1)
<class 'int'>
>>> isinstance(1, int)
True
>>> 1 + 1
2.0
>>> type(2.0)
<class 'float'>
Type Casting
>>> float(2)
2.0
>>> int(2.0)
2
>>> int(2.5)
2
>>> int(-2.5)
-2
>>> type(1000000000000000)
<class 'int'>
FRACTIONS
A list in python can store elements of different datatypes and its size can
grow arbitrarily.
It is mutable
Creating a list is easy: use square brackets to wrap a comma-separated list of
values.
>>> a_list = ['a', 'b', 'mpilgrim', 'z', 'example']
>>> a_list
['a', 'b', 'mpilgrim', 'z', 'example']
>>> a_list[0]
'a'
>>> a_list[4]
'example‘
>>> a_list[-1]
'example‘
>>> a_list[-3]
'mpilgrim'
Slicing a List
Once you’ve defined a list, you can get any part of it as a new list. This is
called slicing the list.
>>> a_list
['a', 'b', 'mpilgrim', 'z', 'example']
>>> a_list[1:3]
['b', 'mpilgrim']
>>> a_list[1:-1]
['b', 'mpilgrim', 'z']
>>> a_list[0:3]
['a', 'b', 'mpilgrim']
>>> a_list[3:]
['z', 'example']
>>> a_list[:]
['a', 'b', 'mpilgrim', 'z', 'example']
>>> a_list[:3]
['a', 'b', 'mpilgrim']
Adding items to list
>>> a_list = ['a']
>>> a_list = a_list + [2.0, 3]
>>> a_list
['a', 2.0, 3]
>>> a_list.append(True)
>>> a_list ['a', 2.0, 3, True]
>>> a_list.extend(['four', 'Ω'])
>>> a_list ['a', 2.0, 3, True, 'four', 'Ω']
>>> a_list.insert(0, 'Ω')
>>> a_list
['Ω', 'a', 2.0, 3, True, 'four', 'Ω']
SEARCHING FOR VALUES IN A LIST
>>> a_list.count('new')
2
>>> 'new' in a_list
True
>>> 'c' in a_list
False
>>> a_list.index('mpilgrim')
3
>>> a_list.index('new')
2
>>> a_list.index('c') #see output
REMOVING ITEMS FROM A LIST
List methods append(), extend(), insert(), remove(), pop() don’t work fro Tuples.
We can slice a tuple, it creates new tuples, we can check if tuple contains a
particular value.
Tuple Vs List
•If you’re defining a constant set of values , use a tuple instead of a list.
•It makes your code safer if you “write-protect” data that doesn’t need to be changed.
•Using a tuple instead of a list is like having an implied assert statement that shows this data is constant
• Some tuples can be used as dictionary keys (specifically, tuples that contain immutable values
like strings, numbers, and other tuples).
• Lists can never be used as dictionary keys, because lists are mutable.
>>> a_set = {2, 4, 5, 9, 12, 21, 30, 51, 76, 127, 195}
>>> 30 in a_set
True
>>> 31 in a_set
False
>>> b_set = {1, 2, 3, 5, 6, 8, 9, 12, 15, 17, 18, 21}
>>> a_set.union(b_set)
{1, 2, 195, 4, 5, 6, 8, 12, 76, 15, 17, 18, 3, 21, 30, 51, 9, 127}
>>> a_set.intersection(b_set)
{9, 2, 12, 5, 21}
>>> a_set.difference(b_set)
{195, 4, 76, 51, 30, 127}
>>> a_set.symmetric_difference(b_set)
{1, 3, 4, 6, 8, 76, 15, 17, 18, 195, 127, 30, 51}
DICTIONARIES
A dictionary is an unordered set of key-value pairs. When you add a key
to a dictionary, you must also add a value for that key
•s[1:4] is 'ell' -- chars starting at index 1 and extending up to but not including index 4
•s[1:] is 'ello' -- omitting either index defaults to the start or end of the string
•s[:] is 'Hello' -- omitting both always gives us a copy of the whole thing (this is the pythonic way
to copy a sequence like a string or list)
•s[1:100] is 'ello' -- an index that is too big is truncated down to the string length
s[-1] is 'o' -- last char (1st from the end)
s[-4] is 'e' -- 4th from the end
s[:-3] is 'He' -- going up to but not including the last 3 chars.
s[-3:] is 'llo' -- starting with the 3rd char from the end and extending to the end of the string
String %
Python has a printf()-like facility to put together a string.
The % operator takes a printf-type format string on the left (%d int, %s string,
%f/%g floating point), and the matching values in a tuple on the right (a tuple is
made of values separated by commas, typically grouped inside parentheses):
text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow
down')
Input / Output
>>> x = 5; y = 10
>>> num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
If - else
num = -5
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
If-elif-else
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Nested if
# Python program to check if the input year is a leap year or notyear = 2000# To get year
(integer input) from the user#
year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
To Display Calendar
import calendar
yy = 2014
mm = 11
# To ask month and year from the user#
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
# display the calendar
print(calendar.month(yy, mm))
Looping
a=0
While a<5 :
print(a)
a=a+1
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
for val in numbers:
sum = sum+val
print("The sum is", sum)
For with else
A for loop can have an optional else block as well. The else part is executed if
the items in the sequence used in for loop exhausts
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.").
Range()
>>> print(range(10))
print(list(range(2, 8)))
print(list(range(2, 20, 3)))
genre = ['pop', 'rock', 'jazz']
# iterate over the list using index
for i in range(len(genre)):
print("I like", genre[i])
While – Program to print sum of n
natural numbers
# Program to add natural numbers upto n, sum = 1+2+3+...+n
n = int(input("Enter n: "))
10
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1
print("The sum is", sum)
While with else
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
Break and continue statement
Break
To indicate no operation.
Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.
def greet(name):
"""This function greets to the person passed in as parameter"""
print("Hello, " + name + ". Good morning!")
>>> greet('Paul')
Hello, Paul. Good morning!
>>> print(greet("May"))
Hello, May. Good morning!
None
Example to print absolute value
def absolute_value(num):
"""This function returns the absolute value of the entered number"""
if num >= 0:
return num
else:
return -num
# Output: 2
print(absolute_value(2))
# Output: 4
print(absolute_value(-4))
How functions work
HCF of two numbers
def computeHCF(x, y):
# choose the smaller number
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))
Python Package
Just as Similar files are kept in the same directory, analogous to this, Python
has packages for directories and modules for files.
Module=collection of similar files
Package=collection of similar directories
A directory must contain a file named __init__.py in order for Python to
consider it as a package. This file can be left empty but we generally place
the initialization code for that package in this file.
Similar, as a directory can contain sub-directories and files, a Python package
can have sub-packages and modules.
Import module from package
Import Game.Level.start
Now if this module contains a function named select_difficulty(), we must use the full name
to reference it.
Game.Level.start.select_difficulty(2)
Or, we can import the module without the package prefix as follows.
from Game.Level import start
We can now call the function simply as follows.
start.select_difficulty(2)
Yet another way of importing just the required function (or class or variable) form a module
within a package would be as follows.
from Game.Level.start import select_difficulty
Now we can directly call this function.
select_difficulty(2)
Files
When we want to read from or write to a file we need to open it first. When
we are done, it needs to be closed, so that resources that are tied with the
file are freed.
The default is reading in text mode. In this mode, we get strings when reading
from the file.
On the other hand, binary mode returns bytes and this is the mode to be used
when dealing with non-text files like image or exe files.
Modes
Mode Description
We need to be careful with the 'w' mode as it will overwrite into the file if it already exists.
All previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using write() method. This
method returns the number of characters written to the file.
try:
print(1/0)
except ZeroDivisionError:
print("You can't divide by zero”)
Example
import sys
try:
number = int(input("Enter a number between 1 - 10 "))
except ValueError:
print("Err.. numbers only")
sys.exit()
The else clause in a try , except statement must follow all except clauses,
and is useful for code that must be executed if the try clause does not raise
an exception.
try:
data = something_that_can_go_wrong
except IOError:
handle_the_exception_error
else:
doing_different_exception_handling
Try ... finally clause
The finally clause is optional. It is intended to define clean-up actions that must
be executed under all circumstances
try:
raise KeyboardInterrupt
finally:
print 'Goodbye, world!'
...
Goodbye, world!
KeyboardInterrupt
A finally clause is always executed before leaving the try statement, whether an
exception has occurred or not.
Example
try:
handler=open("trees.txt")
tree_numbers=0
for line in handler:
split_line=line.split(",")
tree_numbers=tree_numbers+split_line[2]
except:
print "An error has been caught!"
Anaconda