The document provides an overview of the Python programming language. It discusses why Python is useful for students and professionals, its major features like being object-oriented and having a large standard library. The document also covers Python's history, how to install it and set the environment variables, basic syntax like variables and data types, operators, and common programming constructs like conditionals and loops.
Why to LearnPython? Python is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Web Development Domain. I will list down some of the key advantages of learning Python: 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.
Area where pythonis used Web development Software development Machine Learning, IOT Data analysis App Development Game Development
6.
History Python is developedby Guido van Rossum in 1989 at the National Research Institute for Mathematics and Computer Science in the Netherlands it was the successor to ABC and capable of exception handling and interfacing with the Amoeba operating system Python is derived from: Modula-3, C, C++ Unix shell Other scripting languages. Python is available under the GNU General Public License (GPL). The GNU General Public License is a free, copyleft license for software and other kinds of works.
7.
Features 1. Easy-to-learn andunderstand 2.. A broad standard library 3.Open Source 4. Interactive Mode 5. Portable (Platform in dependent) 6. Extendable 7. Databases 8. GUI Programming 9. Object Oriented Programming. 10. It can be used as a scripting language
8.
Features 9. Object OrientedProgramming. 10. It can be used as a scripting language 11. It provides very high-level dynamic data types and supports dynamic type checking. 12.It supports automatic garbage collector. 13. Less line of code Python uses two strategies for memory Management: Reference counting: Garbage collection:
9.
Python is available Unix,Linux Win 9x/NT/2000 Macintosh (Intel, PPC, 68K) OS/2 DOS (multiple versions) Palm OS Nokia mobile phones(Symbian)
10.
Python Installation 1. Goto www.python.org 2. Go to Download menu 3. Click on windows menu 4. Download Python (what ever version you want. 5. Double click on downloaded Python.exe file and install it
11.
Set environment variable Right click on My computer Click on Properties Then click on advance system setting In left hand side of the windows screen. Then click on Set Environment variables Now click on first New button and Add following
12.
Set environment variable 1.Select “path” variable in system variables 2. Click on edit button 3. Add following path in the path variable C:Users[Your_Current_User_Name]AppDataLocalProgramsPythonPython36; 4. Then click on ok Button. 5. Now open command prompt and type python If python shall is running then environment variable is set properly.
13.
Python Basic syntax Python Identifiers Reserved Words Comments in Python Input output In Python Variable Types Delete variable in python
14.
1. Python Identifiers APython identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with: Python does not allow A letter A to Z or a to z An underscore (_) followed by zero more letters, Underscores and digits (0 to 9). @, $, and % within identifiers. Python is a case sensitive programming language. White specs not in b/w the catheters E.g. My Name=“mukul”
15.
Reserved Words and fromwhile assert finally yield break for with class from try continue global return def If Raise elif Import print else In pass is Except or del lambda not
16.
2. Multi-Line Statements Statementsin Python end with a new line. Even though, allow the use of the line continuation character () to denote that the line should continue. For example − • total = item_one + • item_two + • item_three
17.
3. Comments inPython A hash sign (#) is used to define a comment in python .Python compile ignore the line, which are started from # 1. Single line comment Eg. # Python is a awesome language. 2. Multiline comment Eg. “”” Python is a awesome language isn’t it”””
18.
4. Input outputIn Python Input: User can give the input to python program by input keyword Ex. i=input() #in python 3.6 Ex. i=raw_input () # in python 2.7 Output: Print keyword is used for print something on monitor Ex. print(“Python is a awesome language”)# in python version 3.6 Print “Python is a awesome language” # in python version 2.7
19.
5. Variable Declaration Variablesreserved the memory locations to store values. Assignee value to variable counter = 500 # An integer assignment miles = 6000.0 # A floating point name = “Mukul Kirti Verma” # A string Note:- 1.In python no need to define main(). 2.In python no need to define data type for variables.
20.
6. Multiple Assignment single value to several variables a = b = c = 1 Multiple objects to multiple variables a, b, c = 1,2,"john"
21.
Delete variable inpython To delete the reference to a number object by using the del statement. Syntax of the del statement is − del var1,var2,var3,…..,varN Ex x,y,z=6,7,8 del x,y,z
22.
Python Data types 1.Int 2. Float 3. Complex 4. Boolean 5. String 6. List 7. Tuple 8. Dictionary
23.
Types of Operator Pythonsupports the following types of operators: 1.Arithmetic Operators 2.Comparison (Relational) Operators 3.Assignment Operators 4.Logical Operators 5.Bitwise Operators 6.Membership Operators 7.Identity Operators
Comparison Operators Operator Example ==compare two values that they are equal or not (a==d) return True if they are equal ,return False if they are not equal != compare two values that they are equal or not (a==d) return False if they are equal ,return True if they are not equal <> Similar to != Similar to != > Compare that left side value is greater then the right side value a>b return true if a is greater then b < Compare that right side value is greater then left side value a<b return true if b is greater then b >= Compare that left side value is greater then or equal to right side value a>=b return true if a is greater then b or equal to b <= Compare that right side value is greater then or equal to left side value a<=b return true if a is Lesser then b or equal to b
26.
Assignment Operators = Example =c=a+b it will assigns a+b value to c += c+=a it is equivalent to c=c+a -= c-=a it is equivalent to c=c-a *= c*=a it is equivalent to c=c*a /= c/=a it is equivalent to c=c/a %= c%=a it is equivalent to c=c%a **= c**=a it is equivalent to c=c**a //= c//=a it is equivalent to c=c//a
27.
Bitwise Operators Operator Example &Binary AND 1 & 0 = 0 | Binary OR 1 | 0 = 0 ^ Binary XOR 1 ^ 0 = 1 ~ Binary Ones complement ~001=1010 >> Binary Right Shift a=2; 2>>1 =1; << Binary Left shift a=2; a<<1=4;
Membership Operators Operator Example InReturn true if it finds a variable in the specified sequence and false if not finds 2 in (2,3,5,6) return true not in Return true if it finds a variable in the specified sequence and false if not finds 2 not in (2,3,5,6) return false
30.
Identity Operators Operator Example IsReturn true if the variables on either side of the operator point to the same object and false otherwise x is y return True if id(x) == d(y) Is not Return false if the variables on the either side of the operator point to the same object and true otherwise X is not y return true if id(x)!=id(y)
31.
Operators Precedence S. No.Operator Description (1. Has max prescience and7. has lowest prescience ) 1 peranthsis //(floor division) ** Exponentiation %(Modulo), 2 ~ (complement) 3 (Multiply), /(Division 4 + (Addition) ,-- (subtraction) 5 >>,<< (Right and left bitwise shift) 6 & (Bitwise ‘AND’) 7 ^ (Bitwise XOR), | (regular ‘OR’)
Python Type Conversionand Type Casting The process of converting the value of one data type (integer, string, float, etc.) to another data type is called type conversion. Python has two types of type conversion. 1.Implicit Type Conversion 2.Explicit Type Conversion
34.
Key Points toRemember: In python type Conversion is the conversion of object from one data type to another data type. Implicit Type Conversion is automatically performed by the Python interpreter. Python avoids the loss of data in Implicit Type Conversion. Explicit Type Conversion is also called Type Casting, the data types of object are converted using predefined function by user. In Type Casting loss of data may occur as we enforce the object to specific data type.
Python - Loops Loopallow us to execute the set of statement for multiple times. In python three types of loops are define 1. for 2. while 3. nested loop 4. for else 5. while else
40.
Continue…. It has theability to iterate over the items of any sequence, such as a list or a string. Syntax: for i in sequence: statements(s)
41.
While Loop A whileloop statement in Python programming language repeatedly executes a target statement as long as a given condition is true. Syntax: while expression: statement(s)
Numbers in python Numberdata types store numeric values. They are immutable data types, means that changing the value of a number data type results in a newly allocated object. var1 = 1 var2 = 10 Python supports Three different numerical types − int (signed integers) float (floating point real values) complex (complex numbers)
45.
Mathematical Function Function Description abs()Return absolute value of x exp() exp(x)=(e)power(x) Floor() floor(x) :it Return floor value of x Log() log(x) : it return logarithmic value of x Max() max(x1,x2,x3…,xn) : it return max element in a list Min() min(x1,x2,……xn): it return min element in a list Pow() pow(x,y) : it return x**y Ceil() Return ceiling value
46.
Mathematical constraints Sr. No. Constants &Description Example 1 Pi The mathematical constant pi. i=numpy.pi Output : i=3.141592653589793 2 e The mathematical constant e. i=numpy.e Output : i=2.718281828459045
47.
Strings Definition:-String are nothingbut set of character. Ex. • var1 = ‘Hello scimox' • var2 = "Python Programming“ • var3=“””hello my name is mukul kirti verma”””
String Methods Method count returnsoccurrences of substring in string isupper returns if all characters are uppercase characters join Returns a Concatenated String index Returns Index of Substring isalnum Checks Alphanumeric Character isdecimal Checks Decimal Characters Isdigit Checks Digit Characters isprintable Checks Printable Character
String Methods Method Description rindexReturns Highest Index of Substring splitlines Splits String at Line Boundaries rsplit Splits String From Right find Find element in string isspace Checks Whitespace Characters swapcase swap uppercase characters to lowercase; vice versa islower Checks if all Alphabets in a String are Lowercase isnumeric Check whether all element of string in are numeric
52.
String Special Operators OperatorDescription + For Concatenation * Repetition [] Slice [ : ] Range Slice in Membership not in Membership r/R Raw String
53.
Python Lists The listcan be written as a collection of comma-separated values (items) between square brackets. Values can be any type of. Operation 1. Insert 2. Update 3. Delete Eg. list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"]
54.
Some other Operationon list Expression Result list1+list12 It will concatenate list1 and list2 len(list1) It will return length of list1 (‘ok',) * 4 It will return list with 4 element with value ‘ok’ x in (x,y,z) It will check membership of x in list max(list1) It will return max element in list min(list1) It will return min element in list
55.
Tuple In Python Atuple is a sequence of immutable Python objects. Tuples elements cannot be changed Creating a tuple is as simple as putting different comma-separated values in and put in parenthese. Ex. Tuple1=(1,2,3,4,5) Tuple1 = (‘abc', ‘xyz', 1, 3.0); Tuple1 = "a", "b", "c", "d";
56.
Tuples Operations Expression Result tup1+tup2It will concatenate tup1 and tup2 len(tup1) It will return length of tup1 (‘ok',) * 4 It will return tuple with 4 element with value ‘ok’ x in (x,y,z) It will check membership of x in tuple max(tup1) It will return max element in tuple min(tup1) It will return min element in tuple count Count element In tuple index Return index of an element in tuple
57.
Dictionary In Python Inpython, dictionary is similar to hash or maps in c++. It consists key and value pairs. The value can be accessed by unique key in the dictionary. Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.values can be any data type. 1. Insert 2. Update 3. Delete
58.
Built-in Functions &Methods len(dict) Gives the total length of the dictionary. str(dict) it would convert dictionary in string. type() it would return the type of element of a key passed.
59.
Function in python Afunction is a block of code which is run only when, it is called. Creating or defining a Function; def functionname( parameters ): [expression] Ex. def printme(str): print(str) printme(“hi”) Output: ‘hi’
60.
Calling a Function youcan execute function code by calling it from another function or directly from the Python prompt. def printme( str ): print str return; printme(“hi")# Output: ‘hi’ printme(“hello") #Output: ‘hello’
61.
Function Arguments A functioncan be call by using the following types of formal arguments − 1. Required arguments 2. Keyword arguments 3. Default arguments 4. Variable-length arguments
62.
return Statement The statementreturn statement quit a function, and optionally passing back an expression to its caller. A return statement with no arguments returns none. Ex. def sum( arg1, arg2 ): total = arg1 + arg2 print (sum( 5, 5 )); print (sum) Output: 10 10
63.
Scope of Variables Thereare two basic scopes of variables in python 1. Global variables 2. Local variables Ex. total = 0 This is global variable. def sum( arg1, arg2 ): total = arg1 + arg2 print( total ) return total sum( 10, 20 ) print ( total )
64.
Python GUI withTkinter Introduction to tkinter: The tkinter package (“Tk interface”) is the standard Python interface to the Tk GUI toolkit. Both Tk and tkinter are available on most Unix platforms, as well as on Windows systems. (Tk itself is not part of Python; it is maintained at ActiveState.) Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps − Import the Tkinter module. Create the GUI application main window. Add one or more of the above-mentioned widgets to the GUI application. Enter the main event loop to take action against each event triggered by the user.
Tkinter Label This widgetimplements a display box where you can place text or images. The text displayed by this widget can be updated at any time you want.It is also possible to underline part of the text (like to identify a keyboard shortcut) and span the text across multiple lines. Ex: from Tkinter import * root = Tk() var = StringVar() label = Label( root, textvariable=var, relief=RAISED ) var.set("Hey!? How are you doing?") label.pack() root.mainloop()
67.
Tkinter Entry The Entrywidget is used to accept single-line text strings from a user. If you want to display multiple lines of text that can be edited, then you should use the Text widget. If you want to display one or more lines of text that cannot be modified by the user, then you should use the Label widget. Ex: • from Tkinter import * • top = Tk() • L1 = Label(top, text="User Name") • L1.pack( side = LEFT) • E1 = Entry(top, bd =5) • E1.pack(side = RIGHT) • top.mainloop()
68.
Tkinter Button The Buttonwidget is used to add buttons in a Python application. These buttons can display text or images that convey the purpose of the buttons. You can attach a function or a method to a button which is called automatically when you click the button. Example: • import Tkinter • import tkMessageBox • top = Tkinter.Tk() • def helloCallBack(): • tkMessageBox.showinfo( "Hello Python", "Hello World") • B = Tkinter.Button(top, text ="Hello", command = helloCallBack) • B.pack() top.mainloop()