Python Strings


Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes.

Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator.

For example −

#!/usr/bin/python

str = 'Hello World!'

print str          # Prints complete string
print str[0]       # Prints first character of the string
print str[2:5]     # Prints characters starting from 3rd to 5th
print str[2:]      # Prints string starting from 3rd character
print str * 2      # Prints string two times
print str + "TEST" # Prints concatenated string

This will produce the following result −

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Python Numbers


Number data types store numeric values. Number objects are created when you assign a value to them.

For example −

var1 = 1
var2 = 10

You can also delete the reference to a number object by using the del statement.

The syntax of the del statement is −

del var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects by using the del statement.

For example −

del var
del var_a, var_b

Python supports four different numerical types −

  • int (signed integers)
  • long (long integers, they can also be represented in octal and hexadecimal)
  • float (floating point real values)
  • complex (complex numbers)

Examples

Here are some examples of numbers −

int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j
  • Python allows you to use a lowercase l with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.
  • A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.

Python – Standard Data Types


Python has various standard data types that are used to define the operations possible on them and the storage method for each of them. The data stored in memory can be of many types. For example, a person’s age is stored as a numeric value and his or her address is stored as alphanumeric characters.

Python has five standard data types −

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

Python Variable Types


Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable.

For example −

#!/usr/bin/python

distance = 100          # An integer assignment
area     = 1000.0       # A floating point
name     = "Clinton"    # A string

print distance
print area
print name

Here, 100, 1000.0 and “John” are the values assigned to distancearea, and name variables, respectively. This produces the following result −

100
1000.0
Clinton

Multiple Assignment

Python allows you to assign a single value to several variables simultaneously.

For example −

a = b = c = 1

Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables.

For example −

a,b,c = 1,2,"john"

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value “john” is assigned to the variable c.

Python – Lines and Indentation


Python programing language provides no braces ( like in C++ or Javascript ) to indicate blocks of code. Blocks of code are denoted by line indentation, which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount.

For example the below code snippet is correct

if True:
    print "The Value is True"
else:
  print "False"

However, the following block generates an error −

if True:
    print "Answer"
    print "True"
else:
    print "Answer"
  print "False"

Thus, in Python all the continuous lines indented with same number of spaces would form a block. The following example has various statement blocks −

#!/usr/bin/python

import sys

try:
  # open file stream
  file = open(file_name, "w")
except IOError:
  print "There was an error writing to", file_name
  sys.exit()
print "Enter '", file_finish,
print "' When finished"
while file_text != file_finish:
  file_text = raw_input("Enter text: ")
  if file_text == file_finish:
    # close the file
    file.close
    break
  file.write(file_text)
  file.write("\n")
file.close()
file_name = raw_input("Enter filename: ")
if len(file_name) == 0:
  print "Next time please enter something"
  sys.exit()
try:
  file = open(file_name, "r")
except IOError:
  print "There was an error reading file"
  sys.exit()
file_text = file.read()
file.close()
print file_text

Multi-Line Statements

Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example −

total = item_one + \
        item_two + \
        item_three

Statements contained within the [] -Lists, {} – Dictionary , or () – Tuples brackets do not need to use the line continuation character. For example −

days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']

Quotation in Python

Python accepts single (‘), double (“) and triple (”’ or “””) quotes to denote string literals, as long as the same type of quote starts and ends the string.The triple quotes are used to span the string across multiple lines. For example, all the following are legal −

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

Comments in Python

A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.

#!/usr/bin/python

# First comment
print "Hello, Python!" # second comment

This produces the following result −

Hello, Python!

You can type a comment on the same line after a statement or expression −

name = "Madisetti" # This is again comment

You can comment multiple lines as follows −

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

Using Blank Lines

A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it.

 

Reserved Words (Python)


Python keywords are reserved words that cannot used as constant or variable or any other identifier names.

All the Python keywords contain lowercase letters only. The following are the list of reserved keywords.

and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

Python Identifiers


An identifier in Python is a name used to identify a variable, function, class, module or other object. It ( identifier ) starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).

Python does not allow special characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, Hello and hello are two different identifiers in Python.

The following are naming conventions for Python identifiers −

  • Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
  • Starting an identifier with a single leading underscore indicates that the identifier is private.
  • Starting an identifier with two leading underscores indicates a strongly private identifier.
  • If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.

Hello Python !


It’s time to create your first program.

Here we shall use the “print” command to print the line “Hello, Python!”.

Type the following text at the Python prompt and press the Enter:

hello-python

You shall see “Hello, Python !” printed out on to the screen, Congratulations !!! you have now created the worlds simplest python script.

Getting Started with Python IDE


Python comes in two major versions, Python 2 and Python 3. Both are quite different. Here in this website i shall teach you Python 2, at the time of this writing Python 2.7.10 in the latest version. I shall be using Mac to show the samples and vim as the editor for writing the scripts for later on the tutorials. Python comes by default in Mac and almost every flavors  of linux. ( If you are using windows then you need to install python 2.7 )

If  you are on Mac or Linux the just fire up your Terminal and type “python”

python_terminal

after pressing enter you shall be presented with the following screen ( your’s may be a little different )

python-ide

 

Python Basics


Python is a high-level, interpreted, interactive and object-oriented scripting language. 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 designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.

Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.

Advantages of Python

  • Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.
  • Python is Interpreted: Python is processed at runtime by the interpreter. You do not need to compile your program before executing it.
  • 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.

Whether you are an experienced programmer or not, this website is intended for everyone who want to learn the Python programming language.