Download presentation
Presentation is loading. Please wait.
1
Betsy Manuel Trainer Foursteps Solutions
Python Programming Betsy Manuel Trainer Foursteps Solutions 4/3/2019
2
Getting Started with PYTHON
What is PYTHON: Invented by Guido van Rossum in the 1990s Named after the comedy group Monty Python Open source from the beginning Managed by Python software foundation (PSF ) Aim – intelligence could be taught quickly and effectively. 4/3/2019
3
Powerful Standard library
Python Features: Few Keywords, simple structure and clear defined syntax Easy to Learn Let you get more done with less code and less time Rapid Development Strength of Python is the bulk of the library is portable and cross platform compactable Powerful Standard library 4/3/2019
4
Who use Python today ? 4/3/2019
5
Python vs other popular language
Python C/C++ JAVA PHP Faster to learn Faster Faster Portable code Much smaller and compact code More powerful standard library More versatile Huge installed base 4/3/2019
6
Python vs other popular languages
4/3/2019
7
Python CLE and IDLE Editor
IDLE (Integrated DeveLopment Environment) Completely written in Python and the Tkinter GUI toolkit 4/3/2019
8
Python Interpreter 4/3/2019
9
Awesome Standard Library
4/3/2019
10
Program Structure for Python
4/3/2019
11
Basic syntax Rules Python is case sensitive. Hence a variable with name yoyostudytonight is not same as yoYoStudytonight For path specification, python uses forward slashes. Hence if you are working with a file, the default path for the file in case of Windows OS will have backward slashes, which you will have to convert to forward slashes to make them work in your python script. For window's path C:\folderA\folderB relative python program path should be C:/folderA/folderB 3. In python, there is no command terminator, which means no semicolon ; or anything. 4/3/2019
12
In one line only a single executable statement should be written and the line change act as command terminator in python. To write two separate executable statements in a single line, you should use a semicolon ;to separate the commands. For example, In python, you can write comments in your program using a # at the start. A comment is ignored while the python script is executed. Line Continuation: To write a code in multiline without confusing the python interpreter, is by using a backslash \ at the end of each line to explicitly denote line continuation. For example, sum = \ 456 + \ 789 4/3/2019
13
Blank lines in between a program are ignored by python.
This is the most important rule of python programming. In programming language like Java, C or C++, generally curly brackets { } are used to define a code block, but python doesn't use brackets, then how does python knows It is recommended to use tab for indentation if True: print "Yes, I am in if block" # the above statement will not be # considered inside the if block 4/3/2019
14
Program with main and function definition
Reused code Function Definition Main program 4/3/2019
15
Blocks and Indentation
>>> Def add(a): b=0 b = a+b return b >>> Add(a) >>> Def add(a): b=0 b = a+b return b Add(a) 4/3/2019
16
Print Statements Before we do anything, we need a way to look at values using the print command. print < expression > 4/3/2019
17
Comments A comment is used to enter freehand text, usually for documentary purposes Use a single hashmark to comment # Comment ends with new line # this is a comment def sum(): # this is the sum function 4/3/2019
18
Variables, Operators and Expression
4/3/2019
19
Variable as String 4/3/2019
20
Variable as number 4/3/2019
21
Operators of python 4/3/2019
22
Python for Comparison Operators
4/3/2019
23
Python Arithmetic operators
4/3/2019
24
Python for Logical Operators
4/3/2019
25
Python for Assignment Operators
4/3/2019
26
Built in Automatic Data types
Numbers, lists, strings, tuples, tuples, dictionaries, etc. Numbers: Integers 5, -8, 43, -234, 99933 Floats 6.8, 24e12, -4e-2 #2e3 = 2000, scientific notation Complex numbers: 4+3j, j Booleans True, False 4/3/2019
27
Precedence Built in functions
>>> round (7.78) >>> int (230.5) >>> float (230) >>> int (3e3) >>> type (151.0) >>> type (151) >>> type ('Python') >>> 5-2*3/4 >>> 50/2+2**3-8/2 4/3/2019
28
Precedence Built in functions
>>> round (7.78) # Built-in function returns: 8 >>> int (230.5) # Built-in converts to integer, returns: 230 >>> float (230) # Built-in converts to float, returns: 230.0 >>> int (3e3) # returns: 3000 >>> type (151.0) # returns: <type 'float'> >>> type (151) # returns: <type 'int'> >>> type ('Python') # returns: <type 'str'> >>> 5-2*3/4 4 # same as 5-((2*3)/4) >>> 50/2+2**3-8/ # (50/2)+(2**3)-(8/2) # For equal precedence go from left to right! # first power, then left division, then add them, # then right division, then subtraction 4/3/2019
29
Calling Python’s Library functions in module
>>> import math # imports the math module # now we can use math’s functions >>> math.pi # call a math library constant >>> math.ceil (3.14) 4 # call a module function () >>> math.sqrt (64) # call square-root function >>> import random # import the random module >>> x = random.uniform (1, 5) # returns a float between 1 and 5 >>> x >>> x = random.randint (1, 5) # returns an integer between 1 and 5 >>> x 1 4/3/2019
30
Built in numeric function – Examples
>>> range (6, 18, 3) >>> range (10) >>> abs (-17) >>> max (12, 89) >>> round (12.7) >>> hex (10) >>> oct (10) 4/3/2019
31
Built in numeric function – Examples
>>> range (6, 18, 3) # returns: [6, 9, 12, 15] >>> range (10) # returns: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> abs (-17) # returns: 17 >>> max (12, 89) # returns: 89 >>> round (12.7) # returns: 13.0 >>> hex (10) # returns: '0xa‘ >>> oct (10) # returns: '012' 4/3/2019
32
Use built in function 4/3/2019
33
Conditional statements, Loop and Iterations
4/3/2019
34
Conditions in PYTHON 4/3/2019
35
If … else statements for python
the program evaluates the test expression and will execute statement(s) only if the text expression is True. Syntax : If test expression : Statement(s) Examples: >>>a=6 >>> if a>0: print (a “is positive number”) >>> a=-1 4/3/2019
36
Python if...else Statement
Syntax: if test expression: Body of if else: Body of else Example : >>> a=9 >>> if a>5: print (a “is greater than 5”) else : print (a, ”is less than 5”) 4/3/2019
37
Python if...elif...else statements
Syntax : if test expression: Body of if elif test expression: Body of elif else: Body of else Try by yourself 4/3/2019
38
FOR LOOP for PYTHON 4/3/2019
39
Print out the weeks names in our for loop
LOOPs for Python For - Loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. Print out the weeks names in our for loop 4/3/2019
40
(cont’d) For loop in range limit >>> for a in range(3, 10)
print a For loop with BREAK point >>> for i in range(3, 10): if(i==7): break print i For loop for continue statement >>> for x in range(10, 20): if (x%5 ==0): continue print x For loop with enumeration >>> months= ["jan", "feb", "mar", "april", "May", "june"] >>> for i, m in enumerate(months): print I, m 4/3/2019
41
(cont’d) For loop in range limit >>> for a in range(3, 10)
print a result : 3, 4,5 , 6, 7, 8, 9, 10 For loop with BREAK point >>> for i in range(3, 10): if(i==7): break print i result: 3, 4, 5, 6 For loop for continue statement >>> for x in range(10, 20): if (x%5 ==0): continue print x result : 11, 12, 13, 14,16, 17, 18, 19 For loop with enumeration >>> months= ["jan", "feb", "mar", "april", "May", "june"] >>> for i, m in enumerate(months): print I, m 0 jan Feb Mar April May June 4/3/2019
42
While LOOP for PYTHON Syntax of while Loop in Python
While test_expression: Body of while Example : >>> n=10 >>> s=0 >>> i=1 >>> while i<=n: s=s+i i=i+1 >>> print s 4/3/2019
43
While LOOP for PYTHON Syntax of while Loop in Python
While test_expression: Body of while Example : >>> n=10 >>> s=0 >>> i=1 >>> while i<=n: s=s+i i=i+1 >>> print s Print : 55 4/3/2019
44
while loop with else Same as that of for loop
The else part is executed if the condition in the while loop evaluates to False. Examples: >>> a=0 >>> while a<3: print "inside" a=a+1 >>> else: print “outside” 4/3/2019
45
Python for conditional operators
4/3/2019
46
EXERCISE Greatest of three numbers
to check whether an integer is a prime number or not using for loop and if...else statement to check whether a number entered by the user is even or odd. 4/3/2019
47
Dictionary & List 4/3/2019
48
Lists – Lets play with LIST
List is an ordered collection of objects List is modifiable They can have elements of different types Elements are comma separated in list >>> names = [mala, lala, kala ] # assigns to the rivers list >>> x = ['apple', 3, [4.0, 5.0]] # multi-type list 4/3/2019
49
List indices X = [ ‘josh ‘sibi’ Athi Mohan barathi ] + index 1 2 3 4
Lists start counting from 0 on the left side (using + numbers) and -1 from the right side >>> x = [‘josh', ‘sibi', ‘Athi', ‘mohan', ‘barathi'] >>> X[2] >>> X[-5] >>> x[:3] >>> X[0:3] >>> x[3:10] >>> x[3:] X = [ ‘josh ‘sibi’ Athi Mohan barathi ] + index 1 2 3 4 - Index -5 -4 -3 -2 -1 4/3/2019
50
List indices X = [ ‘josh ‘sibi’ Athi Mohan barathi ] + index 1 2 3 4
Lists start counting from 0 on the left side (using + numbers) and -1 from the right side >>> x = [‘josh', ‘sibi', ‘Athi', ‘mohan', ‘barathi'] >>> X[2] ‘Athi’ >>> X[-5] ‘josh’ >>> x[:3] [ josh', ‘sibi', ‘athi'] >>> X[0:3] [ josh', ‘sibi', ‘athi'] # includes 0 but excludes 3 >>> x[3:10] [‘mohan', ‘barathi'] # ignores if the items don’t exist >>> x[3:] [‘mohan', ‘barathi'] # index 3 and higher X = [ ‘josh ‘sibi’ Athi Mohan barathi ] + index 1 2 3 4 - Index -5 -4 -3 -2 -1 4/3/2019
51
(cont’d) >>> lang = ['P', ‘Y', 'T', 'H', 'O', 'N'] >>> lang[3] 'H‘ >>> lang[-1] 'N‘ >>> lang[-6] 'P‘ >>> lang[-8] Traceback (most recent call last): File "<interactive input>", line 1, in <module>IndexError: list index out of range >>> lang[:3] ['P', ‘Y', 'T'] >>> lang [-3:] ['H', 'O', 'N'] P Y T H O N 1 2 3 4 5 6 -6 -5 -4 -3 -2 -1 4/3/2019
52
(cont’d) >>> x [:-2] -> [‘hydroxide’, ‘phosphate’, ‘carbonate’] # up to, but not including index -2, i.e., gets rid of the last two >>> x [2:] -> [‘carbonate’, ‘oxide’, ‘silicate’] # values from position 2 to the end (inclusive) 4/3/2019
53
List with mixed data types
The len () functions returns the number of elements in a list >>> x = [1, 2, 3, [3, 4]] ; len (x) Returns 4 4/3/2019
54
List Built- in functions
Insert Remove Pop Del Sort Append Extend 4/3/2019
55
List can change >>> x = ['River', 'Lake', 'Rock']
>>> x[1] = 'Horse‘ >>> x[0:] ['River', 'Horse', 'Rock'] >>> y = x[:] # copies all x’s elements and assigns to y >>> y[0] = 'Timber‘ # substitute >>> y[2] = 'Lumber‘ # substitute >>> y[0:] #show y from the beginning ['Timber', 'Horse', 'Lumber'] 4/3/2019
56
List can change >>> x = ['River', 'Lake', 'Rock'] >>> x[1] = 'Horse‘ >>> x[0:] ['River', 'Horse', 'Rock'] >>> y = x[:] # copies all x’s elements and assigns to y >>> y[0] = 'Timber‘ # substitute >>> y[2] = 'Lumber‘ # substitute >>> y[0:] #show y from the beginning 4/3/2019
57
Modify List >>> x=[1,2,3,4] >>> y=[5,6]
>>> x.append(y) # adds y as an element (in this case a list) to the end of x >>> print x [1, 2, 3, 4, [5, 6]] >>> y = [5,6] >>> x.extend(y) # adds the items to the end of an existing list >>> print x [1, 2, 3, 4, 5, 6] >>> x.insert(2, 'Hello') # inserts an element after a given index; always needs two arguments >>> print x [1, 2, 'Hello', 3, 4, 5, 6] >>> x.insert(0, 'new') # insert at the beginning (at index 0) an new item >>> print x ['new', 1, 2, 'Hello', 3, 4, 5, 6] 4/3/2019
58
Sorting lists >>> x = [ 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'] >>> x.sort() >>> print x ['Earth', 'Jupiter', 'Mars', 'Mercury', 'Neptune', 'Saturn', 'Uranus', 'Venus'] >>> x=[2, 0, 1,'Soon', “man"] [0, 1, 2, 'Man', 'Soon'] 4/3/2019
59
Min, Max, index and count functions
#returns the index for ‘-3’ >>> x.index(65) 4 #returns the index for ‘45’ >>> x = [6, 9, 4, 7, 9, 2, 9] >>> x.count(9) 3 >>> x = [‘car’, van, bike, scotty] >>> min (x) ‘bike‘ >>> max (x) ‘van‘ >>> x = [6, 1, -5, 15, 78] >>> min (x) -5 >>> max (x) 78 4/3/2019
60
Dictionaries – {} Called dictionary because they allow mapping from arbitrary objects Values in a dictionary are accessed via keys that are not just numbers Both lists and dictionaries store elements of different types Values in a list are implicitly ordered by their indices Those in dictionaries are unordered >>> x = {} # create an empty dictionary >>> x[0] = 'Mercury‘ # assigns a value to a dictionary variable as if it is a list 4/3/2019
61
(cont’d) >>> x = {} # declare x as a dictionary
>>> x[“aa"] = 2 # indexing with non numbers (in this case string) >>> y = {} >>> y[bb'] = 5 >>> x[‘aa'] * y [‘bb'] # this cannot be done with lists (need int indices) 10 >>> phone = {} # declare phone as a dictionary # dictionaries are great for indexing lists by names (lists cannot do it) >>> phone [‘baby'] = >>> print phone[‘baby'] 4/3/2019
62
(cont’d) >>> emp= {} # new dictionary
>>> emp[“name"] = “Mohan“ # uses list format >>> emp[" 'COM "] = “HCL“ >>> emp["RES"] = “Tambaram“ >>> print emp {‘name': Mohan', 'RES': tambaram', 'COM': HCL'} >>> del emp[“name"] >>> print emp {'IND': ‘HCL', 'RES': Tambaram'} >>> emp.keys() ['IND', 'RES'] 4/3/2019
63
Tuples Tuples are as same as List, but tuples are immutable and cannot be changed Difference between tuple and list are , the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets. It is declared with the syntax X = (x1,x2) 4/3/2019
64
Operations that can be done with tuple
Addition : possible to add more data to a tuple. This can be done using the addition operator. t = (1, 2, 3, 4, 5) t = t + (7,) print t Deletion: to delete a tuple, the del keyword is used del t Slicing: Slicing in tuples, works exactly the same like in the case of lists >>> t = (1, 2, 3, 4) >>> t[2:4] 4/3/2019
65
In keyword: It is used to check, if any element is present in the sequence or not. It returns True if the element is found, otherwise False. For example, >>> t = (1, 2, 3, 6, 7, 8) >>> 2 in t >>> 5 in t True False Len() cmp() max() and min() 4/3/2019
66
Functions and Functions Arguments
4/3/2019
67
Function definitions User defined function object
func_def : "def" func_name "(" [parameter_list] ")" ":“ parameter_list: (def parameter ",") Syntax for function : def function name(): 4/3/2019
68
Self describe function
Exercise : Self describe function Simple Function format: >>> def simple(): print “Function is done" >>> simple() Return : Function is done Functions with arguments : >>> def mul (a, d): print (a*d) >>> add(2, 4) Return : 8 4/3/2019
69
Multiple Function Parameters
>>> def add(x, y): sum = x+y print sum >>> def main(): add(2, 3) add(22.3, 55.6) a=int(input("enter the integer1")) b=int(input("enter the integer2")) add(a, b) >>> main() enter the integer1: 12 enter the integer2: 2 14 4/3/2019
70
Return the function values
Return the value for the main function def sum(a): return a+5 print sum(3) print : 8 print (sum(4)+sum(5)) print : 19 4/3/2019
71
Global vs. Local variables
Variable defined inside the function is LOCAL SCOPE and those defined outside the function is GLOBAL SCOPE >> sum= 0 # global variable >> def f(x1, x2): # function declaration sum = x1+x2 Print sum return sum >> f(100, 200) print : 300 (local variable) >> print (sum) print : 0 (global variable) 4/3/2019
72
The Anonymous Functions
Anonymous is not declared in the standard manner by using the def keyword Lambda forms can take any number of arguments but return just one value in the form of an expression. Cannot access other variable other than those in parameters list Syntax : lambda [arg1, arg2,,,,argn ]: expression Example: >>Sum = lambda a1, a2: a1+a2 >>Sum(10, 20) print : 30 4/3/2019
73
Write a Programs with function module
Factorial program using function module # Python program to find the factorial of a number provided by the user.# change the value for a different result num = 4 factorial = 1 for i in range(1,num + 1): factorial = factorial*I print("The factorial of", num ,"is", factorial) 4/3/2019
74
Thank you 4/3/2019
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.