GautamDharamrajChouh
31 views
32 slides
Aug 21, 2024
Slide 1 of 32
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
About This Presentation
.
Size: 227.8 KB
Language: en
Added: Aug 21, 2024
Slides: 32 pages
Slide Content
What is Python? Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation. Python is Interpreted: Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP. Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter directly to write your programs. Python is Object-Oriented: Python supports Object-Oriented style or technique of programming that encapsulates code within objects. Python is a Beginner's Language: Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games. 1
History of Python Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands. Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages. 2
Features of Python Easy-to-learn : few keywords, simple structure, and a clearly defined Easy-to-read: code is more clearly defined and visible to the eyes. Easy-to-maintain: source code is fairly easy-to-maintain A broad standard library: Bulk of the library compatible on UNIX, Windows, and Macintosh. Interactive Mode: interactive testing and debugging of snippets Portable: can run on a wide variety of hardware platforms Extendable: add low-level modules to the Python interpreter. Databases: provides interfaces to all major commercial databases. GUI Programming: supports GUI applications Scalable: provides a better structure and support for large programs 3
Getting Python Official Website for Download https:// www.python.org/ Official Website for Documentation https:// www.python.org/doc/ 4
First Python Program There are two ways to execute of Python program Interactive Mode : Invoking the interpreter without passing a script file as a parameter brings up the following prompt. Scripting Mode: 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. Interactive Mode Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> print("Welcome to class") Welcome to class >>> Scripting Mode : write a simple Python program in a script and save the file with . py ex t ension. 5
Python Identifiers A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9). Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, World and world are two different identifiers in Python. Cl a s s names star t wit h an u pper c ase lett e r . Al l o th e r id e n t i fi e rs star t wi t h a lowercase letter. 6
Reserved Words And Exec not assert Finally or Break For Pass Class From Print Continue Global Raise Def If Return Del import Try Else L a m bda Elif Is y i e ld In W i t h while ex c ept 7
Lines and Indentation Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced. E.g. if True: print ( " True " ) else: print ( " False “ ) However, the following block generates an error if True: print ( " Answer “ ) print ( " True " ) else: print ( " Answer “ ) print ( " False " ) 8
Multi-Line Statements Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. E.g. a = 10 b = 20 c = 30 total = a + \ b + \ c print(total) Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example − days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] print(days) 9
Quotation in Python Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string. The triple quotes are used to span the string across multiple lines. For example, all the following are legal − word = 'word' sentence = "This is a sentence." paragraph = """This is a paragraph. It is made up of multiple lines and sentences.""" print(word) print(sentence) prin t (par a graph) 10
Comments in Python A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them. Single line Comment # First comment print "Hello, Python!" # second comment Multiline Comment ''' This is a multiline comment. ''' print('Hello...') 11
Run Time Input var= input('Enter your name\n') # Return String Value print('Welcome '+var) OR var= input("Enter your name\n") print("Welcome"+var) Multiple Statements on a Single Line import sys; x = 'foo'; sys.stdout.write(x + '\n') 12
Variable Assignment rollNo = 100 height = 5.6 # An integer assignment # A floating point name = "John" # A string print (rollNo) print (height) print (name) Type Casting rollNo = 100 height = 5.6 name = "John" # An integer assignment # A floating point # A string print ('Your roll no. is '+str(rollNo)) print ('Your height is '+str(height)) print ('Your name is '+name) 13
Variable Multiple Assignment: e.g. a = b = c = 1 print('The value of a : '+str(a)) print('The value of b : '+str(b)) print('The value of c : '+str(c)) e.g. a,b,c = 1,2,"john" print('The value of a : '+str(a)) print('The value of b : '+str(b)) print('The value of c : '+c) 14
Data Types Python has five standard data types − Numbers String List Tuple Dictionary Python Numbers Number data types store numeric values. Number objects are created when you assign a value to them. For example − var1 = 1 var2 = 10 Note: You can also delete the reference to a number object by using the del statement. The syntax of the del statement is − del var1[ , var2[ , var3[ . .. .,varN ]]] ] OR del var del var_a , var_b 15
Data Types String Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end. “+” Concatenation Operator “*” (asterisk) Repetition Operator str = 'Hello World!' print str print str[0] print str[2:5] print str[2:] print str * 2 print str + "TEST" # Prints complete string # Prints first character of the string # Prints characters starting from 3rd to 5th # Prints string starting from 3rd character # Prints string two times # Prints concatenated string 16
Data Types Python Lists Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type. list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print list print list[0] print list[1:3] print list[2:] print tinylist * 2 print list + tinylist # Prints complete list # Prints first element of the list # Prints elements starting from 2nd till 3rd # Prints elements starting from 3rd element # Prints list two times # Prints concatenated lists 17
Data Types Python Tuples: A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses. The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their e lements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) tinytuple = (123, 'john') print tuple print tuple[0] print tuple[1:3] print tuple[2:] print tinytuple * 2 print tuple + tinytuple # Prints complete list # Prints first element of the list # Prints elements starting from 2nd till 3rd # Prints elements starting from 3rd element # Prints list two times # Prints concatenated lists 18
Data Types Python Dictionary: Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. dict = {} dict['one'] = "This is one" dict[2] = " This i s two“ tinydict = {'name': 'john','code':6734, 'dept': 'sales'} print tinydict.values() print dict['one'] print dict[2] print tinydict print tinydict.keys() # Prints value for 'one' key # Prints value for 2 key # Prints complete dictionary # Prints all the keys # Prints all Values 19
Operator Python language supports the following types of operators- Arithmetic Operators (basic operator + new // and **operators) Comparison (Relational) Operators Assignment Operators Logical Operators Bitwise Operators Membership Operators Identity Operators 20
Operator Note: We have learn about first five operator in previous classes Membership Operators: Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below- E.g. a = 10 b = 20 list = [1, 2, 3, 4, 5 ] if ( a in list ): print ("Line 1 - a is available in the given list") else: print ("Line 1 - a is not available in the given list") if ( b not in list ): print ("Line 2 - b is not available in the given list") else: print ("Line 2 - b is available in the g iven list") 21
Operator Learn first five operator from tutorials. Identity Operators: Identity operators compare the memory locations of two objects. There are two Identity operators is and is not. a = 20 b = 20 print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b)) if ( a is b ): print ("Line 2 - a and b have same identity") else: print ("Line 2 - a and b do not have same identity ") if ( id(a) == id(b) ): print ("Line 3 - a and b have same identity") else: print ("Line 3 - a and b do not have same identity") b = 30 print ('Line 4','a=',a,':',id(a), 'b=',b,':',id(b)) if ( a is not b ): print ("Line 5 - a and b do not have same identity ") else: print ("Line 5 - a and b have same identity ") 22
Decision Making 23
Decision Making If Else number= int(input("Enter the number :")) if(number<0): print("Negative Number") else: print("Positive Number") Elif mark= int(input("Enter the Marks\n")) if(mark>=40 and mark<50): print("Grade 'C'") elif (mark>=50 and mark<60): print("Grade 'B'") elif(mark>=60 and mark<75): print("Grade 'A'") elif(mark>=75 and mark<=100): print("Grade 'A+'") else: prin t (" F a i l“) 24
Loop Syntax: while test_expression: Body of while 25
Loop Type of Loop: While Loop For Loop Nested Loop While Loop: E.g. number= int(input("Enter the range :")) Su m =0 i=1 while i<=number: Sum= Sum+i i=i+1 if(Sum%2==0): print("The calculated sum "+str(Sum)+" is an even number") else: print("The calculated sum "+ str (Sum)+" is anodd number") 26
Loop For Loop : The for loop in Python is used to iterate over a sequence ( list , tuple , string ) or other iterable objects. Iterating over a sequence is called traversal. Syntex: for val in sequence: Body of for 27
Loop For Loop : The for loop in Python is used to iterate over a sequence ( list , tuple , string ) or other iterable objects. Iterating over a sequence is called traversal. Syntex: for val in sequence: Body of for # Program to find the sum of all numbers stored in a list # List of numbers # variable to store the sum # iterate over the list # Output: The sum is 48 numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] sum = for val in numbers: sum = sum+val print("The sum is", sum) 28
Loop Range Function: The built-in function range() is the right function to iterate over a sequence of numbers. It generates an iterator of arithmetic progressions. for counter in range(1,16,2): print(counter) Nested Loop: Python programming language allows the use of one loop inside another loop. Syntax: While expression: while expression: sta t ement(s) statement(s) for iterating_var in sequence: for iterating_var in sequence: sta t ements(s) statements(s) 29
Loop E.g. for i in range(1,11): for j in range(1,11): k=i*j print (k, end=' ') print() Using else Statement with Loops P y t h o n s u pp o rts h a v i n g an els e s t a t e me n t as s o c i a t e d w i t h a l oop statement. If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list. If the else statement is used with a while loop, the else statement is executed when the condition becomes false. 30
Loop E.g. count = while count < 5: print (count, " is less than 5") count = count + 1 else: print (count, " is not less than 5") Break Statement The break statement is used for premature termination of the current loop. 31
Loop E.g. no=int(input('any number: ')) numbers=[11,33,55,39,55,75,37,21,23,41,13] for num in numbers: if num==no: print ('number found in list') break else: print ('number not found in list') Continue Statement: var = 10 while var > 0: var = var -1 if var == 5: continue print ('Current variable value :', var) print ("Good bye!") 32