Python is an interpreted high-level programming language for general-purpose programming. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, and a syntax that allows programmers to express concepts in fewer lines of code,[25][26] notably using significant whitespace. It provides constructs that enable clear programming on both small and large scales.
Python features a dynamic type system and automatic memory management. It supports multiple programming paradigms, including object-oriented, imperative, functional and procedural, and has a large and comprehensive standard library.
Python interpreters are available for many operating systems. CPython, the reference implementation of Python, is open source software and has a community-based development model, as do nearly all of its variant implementations. CPython is managed by the non-profit Python Software Foundation.
Python allows programmers to define their own types using classes, which are most often used for object-oriented programming. New instances of classes are constructed by calling the class (for example,
Before version 3.0, Python had two kinds of classes: old-style and new-style. The syntax of both styles is the same, the difference being whether the class
The long term plan is to support gradual typing and from Python 3.5, the syntax of the language allows specifying static types but they are not checked in the default implementation, CPython. An experimental optional static type checker named mypy supports compile-time type checking.
Try following example using Try it option available at the top right corner of the below sample code box −
Python features a dynamic type system and automatic memory management. It supports multiple programming paradigms, including object-oriented, imperative, functional and procedural, and has a large and comprehensive standard library.
Python interpreters are available for many operating systems. CPython, the reference implementation of Python, is open source software and has a community-based development model, as do nearly all of its variant implementations. CPython is managed by the non-profit Python Software Foundation.
Statements and control flow
Python's statements include (among others):- The assignment statement (token '=', the equals sign). This operates differently than in traditional imperative programming languages, and this fundamental mechanism (including the nature of Python's version of variables) illuminates many other features of the language. Assignment in C, e.g.,
x = 2
, translates to "typed variable name x receives a copy of numeric value 2". The (right-hand) value is copied into an allocated storage location for which the (left-hand) variable name is the symbolic address. The memory allocated to the variable is large enough (potentially quite large) for the declared type. In the simplest case of Python assignment, using the same example,x = 2
, translates to "(generic) name x receives a reference to a separate, dynamically allocated object of numeric (int) type of value 2." This is termed binding the name to the object. Since the name's storage location doesn't contain the indicated value, it is improper to call it a variable. Names may be subsequently rebound at any time to objects of greatly varying types, including strings, procedures, complex objects with data and methods, etc. Successive assignments of a common value to multiple names, e.g.,x = 2
;y = 2
;z = 2
result in allocating storage to (at most) three names and one numeric object, to which all three names are bound. Since a name is a generic reference holder it is unreasonable to associate a fixed data type with it. However at a given time a name will be bound to some object, which will have a type; thus there is dynamic typing. - The
if
statement, which conditionally executes a block of code, along withelse
andelif
(a contraction of else-if). - The
for
statement, which iterates over an iterable object, capturing each element to a local variable for use by the attached block. - The
while
statement, which executes a block of code as long as its condition is true. - The
try
statement, which allows exceptions raised in its attached code block to be caught and handled byexcept
clauses; it also ensures that clean-up code in afinally
block will always be run regardless of how the block exits. - The
class
statement, which executes a block of code and attaches its local namespace to a class, for use in object-oriented programming. - The
def
statement, which defines a function or method. - The
with
statement (from Python 2.5), which encloses a code block within a context manager (for example, acquiring a lock before the block of code is run and releasing the lock afterwards, or opening a file and then closing it), allowing Resource Acquisition Is Initialization (RAII)-like behavior. - The
pass
statement, which serves as a NOP. It is syntactically needed to create an empty code block. - The
assert
statement, used during debugging to check for conditions that ought to apply. - The
yield
statement, which returns a value from a generator function. From Python 2.5,yield
is also an operator. This form is used to implement coroutines. - The
import
statement, which is used to import modules whose functions or variables can be used in the current program. There are two ways of using import:from <module name> import *
orimport <module name>
. - The
print
statement was changed to theprint()
function in Python 3.
Expressions
Some Python expressions are similar to languages such as C and Java, while some are not:- Addition, subtraction, and multiplication are the same, but the
behavior of division differs. There are two types of divisions in
Python. They are floor division and integer division. Python also added the
**
operator for exponentiation. - From Python 3.5, it enables support of matrix multiplication with the
@
operator. - In Python,
==
compares by value, versus Java, which compares numerics by value and objects by reference. (Value comparisons in Java on objects can be performed with theequals()
method.) Python'sis
operator may be used to compare object identities (comparison by reference). In Python, comparisons may be chained, for examplea <= b <= c
. - Python uses the words
and
,or
,not
for its boolean operators rather than the symbolic&&
,||
,!
used in Java and C. - Python has a type of expression termed a list comprehension. Python 2.4 extended list comprehensions into a more general expression termed a generator expression.
- Anonymous functions are implemented using lambda expressions; however, these are limited in that the body can only be one expression.
- Conditional expressions in Python are written as
x if c else y
(different in order of operands from thec ? x : y
operator common to many other languages). - Python makes a distinction between lists and tuples. Lists are written as
[1, 2, 3]
, are mutable, and cannot be used as the keys of dictionaries (dictionary keys must be immutable in Python). Tuples are written as(1, 2, 3)
, are immutable and thus can be used as the keys of dictionaries, provided all elements of the tuple are immutable. The+
operator can be used to concatenate two tuples, which does not directly modify their contents, but rather produces a new tuple containing the elements of both provided tuples. Thus, given the variablet
initially equal to(1, 2, 3)
, executingt = t + (4, 5)
first evaluatest + (4, 5)
, which yields(1, 2, 3, 4, 5)
, which is then assigned back tot
, thereby effectively "modifying the contents" oft
, while conforming to the immutable nature of tuple objects. Parentheses are optional for tuples in unambiguous contexts. - Python features sequence unpacking where multiple expressions, each evaluating to anything that can be assigned to (a variable, a writable property, etc.), are associated in the identical manner to that forming tuple literals and, as a whole, are put on the left hand side of the equal sign in an assignment statement. The statement expects an iterable object on the right hand side of the equal sign that produces the same number of values as the provided writable expressions when iterated through, and will iterate through it, assigning each of the produced values to the corresponding expression on the left.[citation needed]
- Python has a "string format" operator
%
. This functions analogous toprintf
format strings in C, e.g."spam=%s eggs=%d" % ("blah", 2)
evaluates to"spam=blah eggs=2"
. In Python 3 and 2.6+, this was supplemented by theformat()
method of thestr
class, e.g."spam={0} eggs={1}".format("blah", 2)
, Python 3.6 added "f-strings":f'spam={"blah"} eggs={2}'
. - Python has various kinds of string literals:
- Strings delimited by single or double quote marks. Unlike in Unix shells, Perl
and Perl-influenced languages, single quote marks and double quote
marks function identically. Both kinds of string use the backslash (
\
) as an escape character. String interpolation became available in Python 3.6 as "formatted string literals". - Triple-quoted strings, which begin and end with a series of three single or double quote marks. They may span multiple lines and function like here documents in shells, Perl and Ruby.
- Raw string varieties, denoted by prefixing the string literal with an
r
. Escape sequences are not interpreted; hence raw strings are useful where literal backslashes are common, such as regular expressions and Windows-style paths. Compare "@
-quoting" in C#.
- Strings delimited by single or double quote marks. Unlike in Unix shells, Perl
and Perl-influenced languages, single quote marks and double quote
marks function identically. Both kinds of string use the backslash (
- Python has array index and array slicing expressions on lists, denoted as
a[key]
,a[start:stop]
ora[start:stop:step]
. Indexes are zero-based, and negative indexes are relative to the end. Slices take elements from the start index up to, but not including, the stop index. The third slice parameter, called step or stride, allows elements to be skipped and reversed. Slice indexes may be omitted, for examplea[:]
returns a copy of the entire list. Each element of a slice is a shallow copy.
- List comprehensions vs.
for
-loops - Conditional expressions vs.
if
blocks - The
eval()
vs.exec()
built-in functions (in Python 2,exec
is a statement); the former is for expressions, the latter is for statements.
a = 1
cannot form part of the conditional expression of a conditional
statement. This has the advantage of avoiding a classic C error of
mistaking an assignment operator =
for an equality operator ==
in conditions: if (c = 1) { ... }
is syntactically valid (but probably unintended) C code but if c = 1: ...
causes a syntax error in Python.Methods
Methods on objects are functions attached to the object's class; the syntaxinstance.method(argument)
is, for normal methods and functions, syntactic sugar for Class.method(instance, argument)
. Python methods have an explicit self
parameter to access instance data, in contrast to the implicit self
(or this
) in some other object-oriented programming languages (e.g., C++, Java, Objective-C, or Ruby).Typing
Python uses duck typing and has typed objects but untyped variable names. Type constraints are not checked at compile time; rather, operations on an object may fail, signifying that the given object is not of a suitable type. Despite being dynamically typed, Python is strongly typed, forbidding operations that are not well-defined (for example, adding a number to a string) rather than silently attempting to make sense of them.Python allows programmers to define their own types using classes, which are most often used for object-oriented programming. New instances of classes are constructed by calling the class (for example,
SpamClass()
or EggsClass()
), and the classes are instances of the metaclass type
(itself an instance of itself), allowing metaprogramming and reflection.Before version 3.0, Python had two kinds of classes: old-style and new-style. The syntax of both styles is the same, the difference being whether the class
object
is inherited from, directly or indirectly (all new-style classes inherit from object
and are instances of type
).
In versions of Python 2 from Python 2.2 onwards, both kinds of classes
can be used. Old-style classes were eliminated in Python 3.0.The long term plan is to support gradual typing and from Python 3.5, the syntax of the language allows specifying static types but they are not checked in the default implementation, CPython. An experimental optional static type checker named mypy supports compile-time type checking.
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 following example using Try it option available at the top right corner of the below sample code box −
#!/usr/bin/python print "Hello, Python!"
No comments:
Post a Comment