Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore Python Tutorial

Python Tutorial

Published by chetan.135, 2018-03-31 00:58:24

Description: Python Tutorial

Search

Read the Text Version

Dot TechnologiesPYTHON 1

Dot TechnologiesPython Tutorial Python Introduction What is Python, Python Features, Python History, Python Version, Python Applications, Python Install, Python Path, Python Example, Execute Python, Python Variables, Python Keywords, Python Identifiers, Python Literals, Python Operators, Python Comments Control Statement Python If, Python If else, Python else if, Python nested if, Python for loop, Python while loop Python do while, Python break, Python continue, Python pass Python Strings Python Lists Python Tuples Python Dictionary Python Functions Python Files I/O Python Modules Python Date Python Exceptions Python OOPs Python OOPs, ConceptsPython , Object Class, Python Constructors , Python Inheritance , Multilevel Inheritance, Multiple Inheritance 2

Dot TechnologiesPython TutorialPython is a simple, easy to learn, powerful, high level and object-oriented programminglanguage. Python is an interpreted scripting language also. Guido Van Rossum is knownas the founder of python programming.Introduction to PythonIt covers the topics such as python programming, features, history, versions, how toinstall, example, how to execute, variables, keywords, identifiers, literals, operators andcomments.Control StatementThe control statement in python covers if statement, for loop, while loop, do while loop,break statement, continue statement and pass statement.Python StringsThe string chapter in python provides the full functionality to work on strings such asaccessing string, applying string operators, details of slice notation, applying differentfunctions etc.Python ListsThe list chapter in python covers the data structure part such as storing data in list,accessing data, manipulating data etc.Python TuplesA sequence of immutable objects is known as tuple, it covers accessing tuple, addingtuple, replacating tuple, updating tuple etc.Python DictionaryThe python dictionary provides details about dictionary operations. 3

Dot TechnologiesPython FunctionsIt provides a list of python functions with its implementations.Python Files I/OHow to write data into file and read data from file in python?Python ModulesWhat is python module? What are the usage of modules?Python IntroductionPython is a general purpose, dynamic, high level and interpreted programminglanguage. It supports Object Oriented programming approach to develop applications.It is simple and easy to learn and provides lots of high-level data structures.Python is easy to learn yet powerful and versatile scripting language which makes itattractive for Application Development.Python's syntax and dynamic typing with its interpreted nature, makes it an ideallanguage for scripting and rapid application development.Python supports multiple programming pattern, including object oriented, imperativeand functional or procedural programming styles.Python is not intended to work on special area such as web programming. That is whyit is known as multipurpose because it can be used with web, enterprise, 3D CAD etc.We don't need to use data types to declare variable because it is dynamically typed sowe can write a=10 to assign an integer value in an integer variable.Python makes the development and debugging fast because there is no compilation stepincluded in python development and edit-test-debug cycle is very fast. 4

Dot TechnologiesPython FeaturesPython provides lots of features that are listed below.1) Easy to Learn and UsePython is easy to learn and use. It is developer-friendly and high level programminglanguage.2) Expressive LanguagePython language is more expressive means that it is more understandable and readable.3) Interpreted LanguagePython is an interpreted language i.e. interpreter executes the code line by line at atime. This makes debugging easy and thus suitable for beginners.4) Cross-platform LanguagePython can run equally on different platforms such as Windows, Linux, Unix andMacintosh etc. So, we can say that Python is a portable language.5) Free and Open SourcePython language is freely available at offical web address.The source-code is alsoavailable. Therefore it is open source.6) Object-Oriented LanguagePython supports object oriented language and concepts of classes and objects come intoexistence.7) ExtensibleIt implies that other languages such as C/C++ can be used to compile the code and thusit can be used further in our python code. 5

Dot Technologies8) Large Standard LibraryPython has a large and broad library and prvides rich set of module and functions forrapid application development.9) GUI Programming SupportGraphical user interfaces can be developed using Python.10) IntegratedIt can be easily integrated with languages like C, C++, JAVA etc. 6

Dot TechnologiesPython History o Python laid its foundation in the late 1980s. o The implementation of Python was started in the December 1989 by Guido Van Rossum at CWI in Netherland. o In February 1991, van Rossum published the code (labeled version 0.9.0) to alt.sources. o In 1994, Python 1.0 was released with new features like: lambda, map, filter, and reduce. o Python 2.0 added new features like: list comprehensions, garbage collection system. o On December 3, 2008, Python 3.0 (also called \"Py3K\") was released. It was designed to rectify fundamental flaw of the language. o ABC programming language is said to be the predecessor of Python language which was capable of Exception Handling and interfacing with Amoeba Operating System. o Python is influenced by following programming languages: o ABC language. o Modula-3 7

Dot TechnologiesPython VersionPython programming language is being updated regularly with new features andsupports. There are lots of updations in python versions, started from 1994 to currentrelease.A list of python versions with its released date is given below. Python Version Released DatePython 1.0 January 1994Python 1.5 December 31, 1997Python 1.6 September 5, 2000Python 2.0 October 16, 2000Python 2.1 April 17, 2001Python 2.2 December 21, 2001Python 2.3 July 29, 2003Python 2.4 November 30, 2004Python 2.5 September 19, 2006Python 2.6 October 1, 2008 8

Dot TechnologiesPython 2.7 July 3, 2010Python 3.0 December 3, 2008Python 3.1 June 27, 2009Python 3.2 February 20, 2011Python 3.3 September 29, 2012Python 3.4 March 16, 2014Python 3.5 September 13, 2015Python 3.6 December 23, 2016Python 3.6.4 December 19, 2017 9

Dot TechnologiesPython Applications AreaPython is known for its general purpose nature that makes it applicable in almost eachdomain of software development. Python as a whole can be used in any sphere ofdevelopment.Here, we are specifing applications areas where python can be applied.1) Web ApplicationsWe can use Python to develop web applications. It provides libraries to handle internetprotocols such as HTML and XML, JSON, Email processing, request, beautifulSoup,Feedparser etc. It also provides Frameworks such as Django, Pyramid, Flask etc todesign and delelop web based applications. Some important developments are:PythonWikiEngines, Pocoo, PythonBlogSoftware etc.2) Desktop GUI ApplicationsPython provides Tk GUI library to develop user interface in python based application.Some other useful toolkits wxWidgets, Kivy, pyqt that are useable on several platforms.The Kivy is popular for writing multitouch applications.3) Software DevelopmentPython is helpful for software development process. It works as a support language andcan be used for build control and management, testing etc.4) Scientific and NumericPython is popular and widely used in scientific and numeric computing. Some usefullibrary and package are SciPy, Pandas, IPython etc. SciPy is group of packages ofengineering, science and mathematics.5) Business Applications 10

Dot TechnologiesPython is used to build Bussiness applications like ERP and e-commerce systems. Trytonis a high level application platform.6) Console Based ApplicationWe can use Python to develop console based applications. For example: IPython.7) Audio or Video based ApplicationsPython is awesome to perform multiple tasks and can be used to develop multimediaapplications. Some of real applications are: TimPlayer, cplay etc.8) 3D CAD ApplicationsTo create CAD application Fandango is a real application which provides full features ofCAD.9) Enterprise ApplicationsPython can be used to create applications which can be used within an Enterprise oran Organization. Some real time applications are: OpenErp, Tryton, Picalo etc.10) Applications for ImagesUsing Python several application can be developed for image. Applications developedare: VPython, Gogh, imgSeek etc.There are several such applications which can be developed using Python 11

Dot TechnologiesHOW TO INSTALL PYTHONTo start with Python, first make sure that the Python is installed on local computer.To install Python, visit the official site and download Python from the download section.To install Python on Ubuntu operating system, visit our installation section where wehave provided detailed installation process.For Windows operating system, the installation process is given below.1. To install Python, firstly download the Python distribution fromwww.python.org/download.2. After downloading the Python distribution, double click on the downloaded softwareto execute it. Follow the following installtion steps. 12

Dot Technologies 13

Dot TechnologiesClick the Finish button and Python will be installed on your system. 14

Dot TechnologiesSETTING PATH IN PYTHONBefore starting working with Python, a specific path is to set. o Your Python program and executable code can reside in any directory of your system, therefore Operating System provides a specific search path that index the directories Operating System should search for executable code. o The Path is set in the Environment Variable of My Computer properties: o To set path follow the steps:Right click on My Computer ->Properties ->Advanced System setting ->EnvironmentVariable ->NewIn Variable name write path and in Variable value copy path up to C://Python(i.e., pathwhere Python is installed). Click Ok ->Ok.Path will be set for executing Python programs.1. Right click on My Computer and click on properties.2. Click on Advanced System settings 15

Dot Technologies3. Click on Environment Variable tab.4. Click on new tab of user variables. 16

Dot Technologies5. Write path in variable name6. Copy the path of Python folder7. Paste path of Python in variable value. 17

Dot Technologies8. Click on Ok button:9. Click on Ok button: 18

Dot Technologies Python Example Python is easy to learn and code and can be execute with python interpreter. We can also use Python interactive shell to test python code immediately. A simple hello world example is given below. Write below code in a file and save with .py extension. Python source file has .pyextension. hello.py1. print(\"hello world by python!\") Execute this example by using following command.1. Python3 hello.py After executing, it produces the following output to the screen. Output hello world by python! Python Example using Interactive Shell Python interactive shell is used to test the code immediately and does not require to write and save code in file. Python code is simple and easy to run. Here is a simple Python code that will print \"Welcome to Python\". A simple python example is given below. >>> a=\"Welcome To Python\" >>> print a Welcome To Python >>> 19

Dot TechnologiesExplanation: o Here we are using IDLE to write the Python code. Detail explanation to run code is given in Execute Python section. o A variable is defined named \"a\" which holds \"Welcome To Python\". o \"print\" statement is used to print the content. Therefore \"print a\" statement will print the content of the variable. Therefore, the output \"Welcome To Python\" is produced.Python 3.4 ExampleIn python 3.4 version, you need to add parenthesis () in a string code to print it. >>> a=(\"Welcome To Python Example\") >>> print a Welcome To Python Example >>> 20

Dot TechnologiesHow to execute pythonTo execute Python code, we can use any approach that are given below.1) Interactive ModePython provides Interactive Shell to execute code immediatly and produce outputinstantly. To get into this shell, write python in the command prompt and start workingwith Python.Press Enter key and the Command Prompt will appear like:Now we can execute our Python commands.Eg: 21

Dot Technologies2) Script ModeUsing Script Mode, we can write our Python code in a separate file of any editor in ourOperating System.Save it by .py extension. 22

Dot TechnologiesNow open Command prompt and execute it by :NOTE: Path in the command prompt should be location of saved file.where you havesaved your file. In the above case file should be saved at desktop.3) Using IDE (Integrated Development Environment)We can execute our Python code using a Graphical User Interface (GUI).All you need to do is:Click on Start button -> All Programs -> Python -> IDLE(Python GUI) 23

Dot TechnologiesWe can use both Interactive as well as Script mode in IDE.1) Using Interactive mode:Execute our Python code on the Python prompt and it will display result simultaneously.2) Using Script Mode:i) Click on Start button -> All Programs -> Python -> IDLE(Python GUI)ii) Python Shell will be opened. Now click on File -> New Window.A new Editor will be opened. Write our Python code here. 24

Dot TechnologiesClick on file -> save asRun code by clicking on Run in the Menu bar.Run -> Run ModuleResult will be displayed on a new Python shell as: 25

Dot TechnologiesPython KeywordsPython Keywords are special reserved words which convey a special meaning to thecompiler/interpreter. Each keyword have a special meaning and a specific operation.These keywords can't be used as variable. Following is the List of Python Keywords.True False None and asasset def class continue breakelse finally elif del exceptglobal for if from importraise try or return passnonlocal in not is lambda 26

Dot TechnologiesIdentifiersIdentifiers are the names given to the fundamental building blocks in a program.These can be variables ,class ,object ,functions , lists , dictionaries etc.There are certain rules defined for naming i.e., Identifiers.I. An identifier is a long sequence of characters and numbers.II.No special character except underscore ( _ ) can be used as an identifier.III.Keyword should not be used as an identifier name.IV.Python is case sensitive. So using case is significant.V.First character of an identifier can be character, underscore ( _ ) but not digit. 27

Dot TechnologiesPython LiteralsLiterals can be defined as a data that is given in a variable or constant.Python support the following literals:I. String literals:String literals can be formed by enclosing a text in the quotes. We can use both singleas well as double quotes for a String.Eg:\"Aman\" , '12345'Types of Strings:There are two types of Strings supported in Python:a).Single line String- Strings that are terminated within a single line are known as Singleline Strings.Eg:1. >>> text1='hello'b).Multi line String- A piece of text that is spread along multiple lines is known as Multipleline String.There are two ways to create Multiline Strings:1). Adding black slash at the end of each line.Eg:>>> text1='hello\user'>>> text1'hellouser'>>> 28

Dot Technologies2).Using triple quotation marks:-Eg: >>> str2='''''welcome to SSSIT''' >>> print str2 welcome to SSSIT >>>II.Numeric literals:Numeric Literals are immutable. Numeric literals can belong to following four differentnumerical types.Int(signed Long(long float(floating Complex(complex)integers) integers) point)Numbers( Integers of Real numbers In the form of a+bj unlimited size where a forms the realcan be both followed by with both part and b forms the lowercase or imaginary part ofpositive and uppercase L integer and complex number. eg: eg: 3.14jnegative) 87032845L fractional partwith no eg: -26.2fractionalpart.eg: 100III. Boolean literals:A Boolean literal can have any of the two values: True or False.IV. Special literals.Python contains one special literal i.e., None. 29

Dot TechnologiesNone is used to specify to that field that is not created. It is also used for end of lists inPython.Eg: >>> val1=10 >>> val2=None >>> val1 10 >>> val2 >>> print val2 None >>>V.Literal Collections.Collections such as tuples, lists and Dictionary are used in Python.List: o List contain items of different data types. Lists are mutable i.e., modifiable. o The values stored in List are separated by commas(,) and enclosed within a square brackets([]). We can store different type of data in a List. o Value stored in a List can be retrieved using the slice operator([] and [:]). o The plus sign (+) is the list concatenation and asterisk(*) is the repetition operator.Eg: >>> list=['aman',678,20.4,'saurav'] >>> list1=[456,'rahul'] >>> list ['aman', 678, 20.4, 'saurav'] >>> list[1:3] [678, 20.4] >>> list+list1 ['aman', 678, 20.4, 'saurav', 456, 'rahul'] >>> list1*2 [456, 'rahul', 456, 'rahul'] >>> 30

Dot Technologies Python Operators Operators are particular symbols that are used to perform operations on operands. It returns result that can be used in application. Example1. 4 + 5 = 9 Here 4 and 5 are Operands and (+) , (=) signs are the operators. This expression produces the output 9. Types of Operators Python supports the following operators 1. Arithmetic Operators. 2. Relational Operators. 3. Assignment Operators. 4. Logical Operators. 5. Membership Operators. 6. Identity Operators. 7. Bitwise Operators. Arithmetic Operators The following table contains the arithmetic operators that are used to perform arithmetic operations. Operators Description // Perform Floor division(gives integer value after division) 31

Dot Technologies + To perform addition - To perform subtraction * To perform multiplication / To perform division % To return remainder after division(Modulus) ** Perform exponent(raise to power)Example >>> 10+20 30 >>> 20-10 10 >>> 10*2 20 >>> 10/2 5 >>> 10%3 1 >>> 2**3 8 >>> 10//3 3 >>>Relational OperatorsThe following table contains the relational operators that are used to check relations. 32

Operators Description Dot Technologies 33 < Less than > Greater than <= Less than or equal to >= Greater than or equal to == Equal to != Not equal to <> Not equal to(similar to !=)eg: >>> 10<20 True >>> 10>20 False >>> 10<=10 True >>> 20>=15 True >>> 5==6 False >>> 5!=6 True >>> 10<>2 True >>>

Dot TechnologiesAssignment OperatorsThe following table contains the assignment operators that are used to assign values tothe variables.Operators Description= Assignment/= Divide and Assign+= Add and assign-= Subtract and Assign*= Multiply and assign%= Modulus and assign**= Exponent and assign//= Floor division and assignExample >>> c=10 >>> c 10 >>> c+=5 >>> c 15 >>> c-=5 >>> c 34

Dot Technologies 10 >>> c*=2 >>> c 20 >>> c/=2 >>> c 10 >>> c%=3 >>> c 1 >>> c=5 >>> c**=2 >>> c 25 >>> c//=2 >>> c 12 >>>Logical OperatorsThe following table contains the arithmetic operators that are used to perform arithmeticoperations. Operators Description and Logical AND(When both conditions are true output will be true) or Logical OR (If any one condition is true output will be true) not Logical NOT(Compliment the condition i.e., reverse)Example a=5>4 and 3>2 print a b=5>4 or 3<2 print b 35

Dot Technologies c=not(5>4) print cOutput: >>> True True False >>>Membership OperatorsThe following table contains the membership operators. Operators Descriptionin Returns true if a variable is in sequence of another variable, elsenot in false. Returns true if a variable is not in sequence of another variable, else false.Example a=10 b=20 list=[10,20,30,40,50]; if (a in list): print \"a is in given list\" else: print \"a is not in given list\" if(b not in list): 36

Dot Technologies print \"b is not given in list\" else: print \"b is given in list\"Output: >>> a is in given list b is given in list >>>Identity OperatorsThe following table contains the identity operators. Operators Descriptionis Returns true if identity of two operands are same, else falseis not Returns true if identity of two operands are not same, else false.Example a=20 b=20 if( a is b): print a,b have same identity else: print a, b are different b=10 if( a is not b): print a,b have different identity else: 37

Dot Technologies print a,b have same identityOutput >>> a,b have same identity a,b have different identity >>> 38

Dot Technologies Python Comments Python supports two types of comments: 1) Single lined comment: In case user wants to specify a single line comment, then comment must start with ?#? Eg:1. # This is single line comment. 2) Multi lined Comment: Multi lined comment can be given inside triple quotes. eg:1. ''''' This2. Is3. Multipline comment''' eg:1. #single line comment2. print \"Hello Python\"3. '''''This is4. multiline comment''' 39

Dot Technologies Programs Python program to print \"Hello Python\" This is the most basic Python program. It specifies how to print any statement in Python. In old python (up to Python 2.7.0), print command is not written in parenthesis but in new python software (Python 3.4.3), it is mandatory to add a parenthesis to print a statement. See this example:1. print ('Hello Python') Output:Python program to do arithmetical operationsThe arithmetic operations are performed by calculator where we can perform addition,subtraction, multiplication and division. This example shows the basic arithmeticoperations i.e.o Additiono Subtractiono Multiplicationo DivisionSee this example: 40

Dot Technologies# Store input numbers:num1 = input('Enter first number: ')num2 = input('Enter second number: ')# Add two numberssum = float(num1) + float(num2)# Subtract two numbersmin = float(num1) - float(num2)# Multiply two numbersmul = float(num1) * float(num2)#Divide two numbersdiv = float(num1) / float(num2)# Display the sumprint('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) # Display the subtraction print('The subtraction of {0} and {1} is {2}'.format(num1, num2, min)) # Display the multiplication print('The multiplication of {0} and {1} is {2}'.format(num1, num2, mul)) # Display the division print('The division of {0} and {1} is {2}'.format(num1, num2, div))Note: Here input numbers are 10 and 20.Output: 41

Dot TechnologiesPython program to find the area of a triangleMathematical formula:Area of a triangle = (s*(s-a)*(s-b)*(s-c))-1/2Here s is the semi-perimeter and a, b and c are three sides of the triangle.See this example: # Three sides of the triangle is a, b and c: a = float(input('Enter first side: ')) b = float(input('Enter second side: ')) c = float(input('Enter third side: ')) 42

Dot Technologies # calculate the semi-perimeter s = (a + b + c) / 2 # calculate the area area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 print('The area of the triangle is %0.2f' %area)Output:Note: %0.2f floating point specifies at least 0 wide and 2 numbers after decimal. If youuse %0.5f then it will give 5 numbers after decimal.See this example: 43

Dot TechnologiesPython program to solve quadratic equationQuadratic equation:Quadratic equation is made from a Latin term \"quadrates\" which means square. It is aspecial type of equation having the form of:ax2+bx+c=0Here, \"x\" is unknown which you have to find and \"a\", \"b\", \"c\" specifies the numbers suchthat \"a\" is not equal to 0. If a = 0 then the equation becomes liner not quadraticanymore.In the equation, a, b and c are called coefficients.Let's take an example to solve the quadratic equation 8x2 + 16x + 8 = 0See this example:# import complex math moduleimport cmatha = float(input('Enter a: ')) 44

Dot Technologies b = float(input('Enter b: ')) c = float(input('Enter c: ')) # calculate the discriminant d = (b**2) - (4*a*c) # find two solutions sol1 = (-b-cmath.sqrt(d))/(2*a) sol2 = (-b+cmath.sqrt(d))/(2*a) print('The solution are {0} and {1}'.format(sol1,sol2))Output:Python program to generate a random numberIn Python programming, you can generate a random integer, doubles, longs etc . invarious ranges by importing a \"random\" class.Syntax:First you have to import the random module and then apply the syntax: 45

Dot Technologies1. import random2. random.randint(a,b) See this example:1. import random2. print(random.randint(100,500)) Output:Python program to convert kilometers to milesHere, we are going to see the python program to convert kilometers to miles. Let'sunderstand kilometers and miles first.Kilometer:The kilometer is a unit of length in the metric system. It is equivalent to 1000 meters.Miles:Mile is also the unit of length. It is equal to 1760 yards.Conversion formula: 46

Dot Technologies 1 kilometer is equal to 0.62137 miles.1. Miles = kilometer * 0.621372. Kilometer = Miles / 0.62137 See this example: # Collect input from the user kilometers = float(input('How many kilometers?: ')) # conversion factor conv_fac = 0.621371 # calculate miles miles = kilometers * conv_fac print('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles)) Output: Python program to convert Celsius to Fahrenheit Celsius: Celsius is a unit of measurement for temperature. It is also known as centigrade. It is a SI derived unit used by most of the countries worldwide. It is named after the Swedish astronomer Anders Celsius. 47

Dot TechnologiesFahrenheit:Fahrenheit is also a temperature scale. It is named on Polish-born German physicistDaniel Gabriel Fahrenheit. It uses degree Fahrenheit as a unit for temperature.Conversion formula:T(℉) = T(℃) x 9/5 + 32Or,T(℉) = T(℃) x 1.8 + 32See this example:# Collect input from the usercelsius = float(input('Enter temperature in Celsius: '))# calculate temperature in Fahrenheitfahrenheit = (celsius * 1.8) + 32print('%0.1f Celsius is equal to %0.1f degree Fahrenheit'%(celsius,fahrenheit))Output:Python program to display calendarIt is simple in python programming to display calendar. To do so, you need to importthe calendar module which comes with Python. 48

Dot Technologies1. import calendar2. And then apply the syntax3. (calendar.month(yy,mm)) See this example: import calendar # Enter the month and year yy = int(input(\"Enter year: \")) mm = int(input(\"Enter month: \")) # display the calendar print(calendar.month(yy,mm)) Output: 49

Dot TechnologiesPython If StatementsThe Python if statement is a statement which is used to test specified condition. We canuse if statement to perform conditional operations in our Python application.The if statement executes only when specified condition is true. We can pass any validexpression into the if parentheses.There are various types of if statements in Python. o if statement o if-else statement o nested if statementPython If Statement Syntaxif(condition): statementsPython If statement flow chartPython If Statement Examplea=10if a==10: print \"Welcome to javatpoint\"Output:Hello User 50


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook