- Information
- AI Chat
Python 3 tutorial
python programming (cs8151)
Anna University
Recommended for you
Preview text
About the Tutorial
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985 – 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). Python is named after a TV Show called ‘Monty Python’s Flying Circus’ and not after Python-the snake.
Python 3 was released in 2008. Although this version is supposed to be backward incompatibles, later on many of its important features have been backported to be compatible with the version 2. This tutorial gives enough understanding on Python 3 version programming language. Please refer to this link for our Python 2 tutorial.
Audience
This tutorial is designed for software programmers who want to upgrade their Python skills to Python 3. This tutorial can also be used to learn Python programming language from scratch.
Prerequisites
You should have a basic understanding of Computer Programming terminologies. A basic understanding of any of the programming languages is a plus.
Execute Python Programs
For most of the examples given in this tutorial you will find Try it option, so just make use of it and enjoy your learning.
Try the following example using Try it option available at the top right corner of the below sample code box −
#!/usr/bin/python
print ("Hello, Python!")
Copyright & Disclaimer
Copyright 2016 by Tutorials Point (I) Pvt. Ltd.
All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, please notify us at contact@tutorialspoint
- Parsing Command-Line Arguments
- Python 3 – Variable Types
- Assigning Values to Variables
- Multiple Assignment
- Standard Data Types......................................................................................................................................
- Python Numbers
- Python Strings................................................................................................................................................
- Python Lists
- Python Tuples
- Python Dictionary
- Data Type Conversion
- Python 3 – Basic Operators
- Types of Operator
- Python Arithmetic Operators
- Python Comparison Operators
- Python Assignment Operators
- Python Bitwise Operators
- Python Logical Operators
- Python Membership Operators
- Python Identity Operators
- Python Operators Precedence
- Python 3 – Decision Making
- IF Statement
- IF...ELIF.. Statements
- Nested IF Statements
- Single Statement Suites
- Python 3 – Loops.....................................................................................................................................
- while Loop Statements
- for Loop Statements
- Nested loops
- Loop Control Statements
- break statement
- continue Statement
- pass Statement
- Iterator and Generator
- Python 3 – Numbers
- Mathematical Functions
- Number abs() Method
- Number ceil() Method
- Number exp() Method
- Number fabs() Method
- Number floor() Method
- Number log() Method....................................................................................................................................
- Number log10() Method
- Number max() Method
- Number min() Method
- Number modf() Method
- Number pow() Method
- Number round() Method
- Number sqrt() Method
- Random Number Functions
- Number choice() Method
- Number randrange() Method
- Number random() Method
- Number seed() Method
- Number shuffle() Method
- Number uniform() Method
- Trigonometric Functions
- Number acos() Method
- Number asin() Method
- Number atan() Method
- Number atan2() Method
- Number cos() Method
- Number hypot() Method
- Number sin() Method
- Number tan() Method
- Number degrees() Method
- Number radians() Method
- Mathematical Constants
- Python 3 – Strings
- Accessing Values in Strings
- Updating Strings
- Escape Characters
- String Special Operators
- String Formatting Operator
- Triple Quotes
- Unicode String
- String capitalize() Method
- String center() Method
- String count() Method
- String decode() Method
- String encode() Method
- String endswith() Method
- String expandtabs() Method........................................................................................................................
- String find() Method
- String index() Method
- String isalnum() Method
- String isalpha() Method
- String isdigit() Method
- String islower() Method
- String isnumeric() Method
- String isspace() Method
- String istitle() Method
- String isupper() Method
- String join() Method
- String len() Method
- String ljust() Method
- String lower() Method
- Tuple min() Method
- Tuple tuple() Method
- Python 3 – Dictionary
- Accessing Values in Dictionary
- Updating Dictionary.....................................................................................................................................
- Delete Dictionary Elements
- Properties of Dictionary Keys
- Built-in Dictionary Functions & Methods
- Dictionary len() Method
- Dictionary str() Method
- Dictionary type() Method
- Dictionary clear() Method
- Dictionary copy() Method
- Dictionary fromkeys() Method
- Dictionary get() Method
- Dictionary items() Method
- Dictionary keys() Method
- Dictionary setdefault() Method
- Dictionary update() Method
- Dictionary values() Method
- Python 3 – Date & Time
- What is Tick?................................................................................................................................................
- What is TimeTuple?
- Getting current time
- Getting formatted time
- Getting calendar for a month
- The time Module
- Time altzone() Method
- Time asctime() Method
- Time clock() Method
- Time ctime() Method
- Time gmtime() Method
- Time localtime() Method
- Time mktime() Method
- Time sleep() Method
- Time strftime() Method
- Time strptime() Method
- Time time() Method
- Time tzset() Method
- The calendar Module
- Other Modules & Functions
- Python 3 – Functions.............................................................................................................................
- Defining a Function......................................................................................................................................
- Calling a Function
- Pass by Reference vs Value
- Function Arguments
- Required Arguments....................................................................................................................................
- Keyword Arguments
- Default Arguments
- Variable-length Arguments
- The Anonymous Functions
- The return Statement
- Global vs. Local variables
- Python 3 – Modules
- The import Statement
- The from.. Statement
- The from.. * Statement:
- Executing Modules as Scripts
- Locating Modules
- The PYTHONPATH Variable
- Namespaces and Scoping
- The dir( ) Function
- The globals() and locals() Functions............................................................................................................
- The reload() Function
- Packages in Python
- Python 3 – Files I/O
- Printing to the Screen
- Reading Keyboard Input
- The input Function
- Opening and Closing Files
- The open Function
- The file Object Attributes
- The close() Method
- Reading and Writing Files
- The write() Method
- The read() Method
- File Positions
- Renaming and Deleting Files
- The rename() Method
- The remove() Method
- Directories in Python
- The mkdir() Method
- The chdir() Method
- The getcwd() Method
- The rmdir() Method
- File & Directory Related Methods
- File Methods
- File close() Method
- File flush() Method
- File fileno() Method
- File isatty() Method
- File next() Method
- File read() Method
- File readline() Method
- File readlines() Method
- File seek() Method
- File tell() Method
- File truncate() Method
- os() Method
- os_float_times() Method
- os() Method
- os() Method
- os() Method
- os() Method
- os() Method
- os() Method
- os() Method
- os() Method
- os() Method
- os() Method
- os() Method
- os() Method
- Python 3 – Exceptions Handling
- Standard Exceptions
- Assertions in Python
- What is Exception?
- Handling an Exception
- The except Clause with No Exceptions
- The except Clause with Multiple Exceptions
- The try-finally Clause
- Argument of an Exception
- Raising an Exception
- User-Defined Exceptions
- PYTHON 3 – ADVANCED TUTORIAL
- Python 3 – Object Oriented...................................................................................................................
- Overview of OOP Terminology
- Creating Classes
- Creating Instance Objects
- Accessing Attributes
- Built-In Class Attributes
- Destroying Objects (Garbage Collection)
- Class Inheritance
- Overriding Methods
- Base Overloading Methods
- Overloading Operators
- Data Hiding
- Python 3 – Regular Expressions.............................................................................................................
- The match Function
- The search Function
- Matching Versus Searching
- Search and Replace
- Regular Expression Modifiers: Option Flags
- Regular Expression Patterns
- Regular Expression Examples
- Character classes
- Special Character Classes
- Repetition Cases
- Nongreedy Repetition
- Grouping with Parentheses
- Backreferences
- Alternatives
- Anchors
- Special Syntax with Parentheses
- Python 3 – CGI Programming
- What is CGI?
- Web Browsing
- CGI Architecture Diagram
- Web Server Support and Configuration
- First CGI Program.........................................................................................................................................
- HTTP Header
- CGI Environment Variables
- GET and POST Methods
- Passing Information using GET method
- Simple URL Example – Get Method
- Simple FORM Example – GET Method
- Passing Radio Button Data to CGI Program
- Passing Text Area Data to CGI Program.......................................................................................................
- Passing Drop Down Box Data to CGI Program
- Using Cookies in CGI
- How It Works?
- Setting up Cookies
- Retrieving Cookies
- File Upload Example
- How To Raise a "File Download" Dialog Box?
- Python 3 – MySQL Database Access
- What is PyMySQL?
- How do I Install PyMySQL?
- Database Connection
- Creating Database Table..............................................................................................................................
- INSERT Operation
- READ Operation
- Update Operation
- DELETE Operation
- Performing Transactions
- COMMIT Operation
- ROLLBACK Operation
- Disconnecting Database
- Handling Errors
- Python 3 – Network Programming
- What is Sockets?
- The socket Module
- Server Socket Methods
- Client Socket Methods
- General Socket Methods
- Tkinter Relief styles
- Tkinter Bitmaps
- Tkinter Cursors
- Geometry Management
- Tkinter pack() Method
- Tkinter grid() Method
- Tkinter place() Method
- Python 3 – Extension Programming with C
- Pre-Requisites for Writing Extensions
- First look at a Python Extension
- The Header File Python
- The C Functions
- The Method Mapping Table
- The Initialization Function
- Building and Installing Extensions
- Importing Extensions
- Passing Function Parameters
- The PyArg_ParseTuple Function
- Returning Values
- The Py_BuildValue Function
Python 3
1
Python 3 – Basic Tutorial
Python 3
3
something:'10' #eentered data is treated as string >>> x '10' >>> x=raw_input("something:") something:10 #entered data is treated as string even without '' >>> x '10' >>> x=raw_input("something:") something:'10' #entered data treated as string including '' >>> x "'10'" In Python 3 >>> x=input("something:") something: >>> x '10' >>> x=input("something:") something:'10' #entered data treated as string with or without '' >>> x "'10'" >>> x=raw_input("something:") # will result NameError Traceback (most recent call last): File "", line 1, in
x=raw_input("something:") NameError: name 'raw_input' is not defined
Integer Division
In Python 2, the result of division of two integers is rounded to the nearest integer. As a result, 3/2 will show 1. In order to obtain a floating-point division, numerator or denominator must be explicitly used as float. Hence, either 3/2 or 3/2 or 3.0/2 will result in 1.
Python 3 evaluates 3 / 2 as 1 by default, which is more intuitive for new programmers.
Unicode Representation
Python 2 requires you to mark a string with a u if you want to store it as Unicode.
Python 3 stores strings as Unicode, by default. We have Unicode (utf-8) strings, and 2 byte classes: byte and byte arrays.
Python 3
4
xrange() Function Removed
In Python 2 range() returns a list, and xrange() returns an object that will only generate the items in the range when needed, saving memory.
In Python 3, the range() function is removed, and xrange() has been renamed as range(). In addition, the range() object supports slicing in Python 3 and later.
raise exceprion
Python 2 accepts both notations, the 'old' and the 'new' syntax; Python 3 raises a SyntaxError if we do not enclose the exception argument in parenthesis.
raise IOError, "file error" #This is accepted in Python 2 raise IOError("file error") #This is also accepted in Python 2 raise IOError, "file error" #syntax error is raised in Python 3 raise IOError("file error") #this is the recommended syntax in Python 3
Arguments in Exceptions
In Python 3, arguments to exception should be declared with 'as' keyword.
except Myerror, err: # In Python except Myerror as err: #In Python 3
next() Function and .next() Method
In Python 2, next() as a method of generator object, is allowed. In Python 2, the next() function, to iterate over generator object, is also accepted. In Python 3, however, next( as a generator method is discontinued and raises AttributeError.
gen = (letter for letter in 'Hello World') # creates generator object next(my_generator) #allowed in Python 2 and Python 3 my_generator() #allowed in Python 2. raises AttributeError in Python 3
2to3 Utility
Along with Python 3 interpreter, 2to3 script is usually installed in tools/scripts folder. It reads Python 2 source code and applies a series of fixers to transform it into a valid Python 3 code.
Here is a sample Python 2 code (area): def area(x,y=3): a=yxx print a return a
Python 3
6
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently whereas the other languages use punctuations. It has fewer syntactical constructions than other languages.
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.
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.
Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL).
Python is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing its progress.
Python 1 was released in November 1994. In 2000, Python 2 was released. Python 2.7 is the latest edition of Python 2.
Meanwhile, Python 3 was released in 2008. Python 3 is not backward compatible with Python 2. The emphasis in Python 3 had been on the removal of duplicate programming constructs and modules so that "There should be one -- and preferably only one -- obvious way to do it." Python 3.5 is the latest version of Python 3.
2. Python 3 – Overview
Python 3
7
Python Features
Python's features include-
Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This allows a student to pick up the language quickly.
Easy-to-read: Python code is more clearly defined and visible to the eyes.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
A broad standard library: Python's bulk of the library is very portable and cross- platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode: Python has support for an interactive mode, which allows interactive testing and debugging of snippets of code.
Portable: Python can run on a wide variety of hardware platforms and has the same interface on all platforms.
Extendable: You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient.
Databases: Python provides interfaces to all major commercial databases.
GUI Programming: Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix.
Scalable: Python provides a better structure and support for large programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good features. A few are listed below-
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building large applications.
It provides very high-level dynamic data types and supports dynamic type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Python 3 tutorial
Course: python programming (cs8151)
University: Anna University
- Discover more from: