The Python Tutorial
Introduction
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed. Often, programmers fall in love with Python because of the increased productivity it provides. Since there is no compilation step, the edit-test-debug cycle is incredibly fast. Debugging Python programs is easy: a bug or bad input will never cause a segmentation fault. Instead, when the interpreter discovers an error, it raises an exception. When the program doesn't catch the exception, the interpreter prints a stack trace. A source level debugger allows inspection of local and global variables, evaluation of arbitrary expressions, setting breakpoints, stepping through the code a line at a time, and so on. The debugger is written in Python itself, testifying to Python's introspective power. On the other hand, often the quickest way to debug a program is to add a few print statements to the source: the fast edit-test-debug cycle makes this simple approach very effective.
Variables
Variables are containers for storing data values. Python has no
command for declaring a variable. A variable is created the moment
you first assign a value to it. A Python variable is a name given to
a memory location. It is the basic unit of storage in a program. The
value stored in a variable can be changed during program execution.
Varibles of type int:
x = 5
Variable of type str:
y = "John"
Varible of type float:
z = 12.345
Variables of type boolean:
a = true
Lists
Python knows a number of compound data types, used to group together
other values. The most versatile is the list, which can be written
as a list of comma-separated values (items) between square brackets.
Lists might contain items of different types, but usually the items
all have the same type. Lists are one of 4 built-in data types in
Python used to store collections of data.
Defining a List:
a = [1, 2, 3]
A list can contain elements of multiple data types:
b = [4, 5, 6, "apple", "mango", 4.5, true]
Dictionaries
Another useful data type built into Python is the dictionary. Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
It is best to think of a dictionary as a set of key: value pairs,
with the requirement that the keys are unique (within one
dictionary). A pair of braces creates an empty dictionary: {}.
Placing a comma-separated list of key:value pairs within the braces
adds initial key:value pairs to the dictionary; this is also the way
dictionaries are written on output.
Defining a Dictionary:
d = {"name":"John", "age":23, "sex":"male",
"location":"california"}
Sets
Python also includes a data type for sets. A set is an unordered
collection with no duplicate elements. Basic uses include membership
testing and eliminating duplicate entries. Set objects also support
mathematical operations like union, intersection, difference, and
symmetric difference. Curly braces or the set() function can be used
to create sets. Note: to create an empty set you have to use set(),
not {}; the latter creates an empty dictionary, a data structure
that we discuss in the next section.
Defining a set:
s = ("apple", "mango", "banana", 28)
The print() function
The print() function prints the specified message to the screen, or
other standard output device. The message can be a string, or any
other object, the object will be converted into a string before
written to the screen. Though it is not necessary to pass arguments
in the print() function, it requires an empty parenthesis at the end
that tells python to execute the function rather calling it by name.
Now, let’s explore the optional arguments that can be used with the
print() function.
print("Hello World!")
print(28)
if..elif..else statement
if…elif…else are conditional statements that provide you with the decision making that is required when you want to execute code based on a particular condition. The if…elif…else statement used in Python helps automate that decision making process.
The if condition is considered the simplest of the three and makes a
decision based on whether the condition is true or not. If the
condition is true, it prints out the indented expression. If the
condition is false, it skips printing the indented expression.
if condition:
expression
The if-else condition adds an additional step in the decision-making
process compared to the simple if statement. The beginning of an
if-else statement operates similar to a simple if statement;
however, if the condition is false, instead of printing nothing, the
indented expression under else will be printed.
expression
else:
expression
The for loop
The for statement in Python differs a bit from what you may be used
to in C or Pascal. Rather than always iterating over an arithmetic
progression of numbers (like in Pascal), or giving the user the
ability to define both the iteration step and halting condition (as
C), Python’s for statement iterates over the items of any sequence
(a list or a string), in the order that they appear in the sequence.
words = ['cat', 'window', 'defenestrate']
for i in words :
print(i)
The while loop
The while statement is used for repeated execution as long as an
expression is true. The while loop requires relevant variables to be
ready, in this example we need to define an indexing variable, i,
which we set to 1. With the break statement we can stop the loop
even if the while condition is true:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Functions
A function is a block of code which only runs when it is called. You
can pass data, known as parameters, into a function. A function can
return data as a result.
def my_function():
print("Hello from a function")
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function()
Reference
For more info visit Python Docs.