Introduction to Python


By: Mahgul Afzali

1)What is python programming language?

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.

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C++ or Java.

2)What sort of language is Python?

The naïve view of computer languages is that they come as either compiled languages or interpreted languages. At the strictly compiled end languages like C, C++ or Fortran are “compiled” (converted) into raw machine code for your computer. You point your CPU at that code and it runs. Slightly separate from the strictly compiled languages are languages like Java and C# (or anything running in the .net framework). You do need to explicitly compile these programming languages but they are compiled to machine code for a fake CPU which is then emulated on whichever system you run on. Then there is Python. Python does not have to be explicitly compiled but behind the scenes there is a system that compiles Python into an intermediate code which is stashed away to make things faster in future. But it does this without you having to do anything explicit yourself. So from the point of view of how you use it you can treat it as a purely interpreted language like the shell or Perl.

3)who uses Python and what for?

Python is used for everything! For example: “massively multiplayer online role-playing games” like Eve Online, science fiction’s answer to World of Warcraft, web applications written in a framework built on Python called “Django”, desktop applications like Blender, the 3-d animation suite which makes considerable use of Python scripts, the Scientific Python libraries (“SciPy”), instrument control and embedded systems.

4)What are the features of python?

1)Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language in a relatively short period of time.

2) Easy-to-read: Python code is much more clearly defined and visible to the eyes.

3) Easy-to-maintain: Python’s success is that its source code is fairly easy-to-maintain.

4)A broad standard library: One of Python’s greatest strengths is the bulk of the library is very portable and cross-platform compatible on UNIX, Windows and Macintosh.

5)Interactive Mode: Support for an interactive mode in which you can enter results from a terminal right to the language, allowing interactive testing and debugging of snippets of code.

A first Python command

Python prompt

>>> print(‘Hello, world!’) Python command

Hello, world! Output

>>> Python prompt

4)What is a program?

A program is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, such as solving a system of equations or finding the roots of a polynomial, but it can also be a symbolic

computation, such as searching and replacing text in a document or (strangely enough) compiling a program.

The details look different in different languages, but a few basic instructions appear in just about every language

5)what is input?

Get data from the keyboard, a file, or some other device.

6)what is output?

Display data on the screen or send data to a file or other device

7)what is conditional execution?

Check for certain conditions and execute the appropriate sequence of statements.

8)What is debugging?

Programming is error-prone. For whimsical reasons, programming errors are called bugs and the process of tracking them down is called debugging.

Three kinds of errors can occur in a program:

1)syntax errors, 2)runtime errors, 3) semantic errors.

It is useful to distinguish between them in order to track them down more quickly.

1)What is Syntax errors:

Python can only execute a program if the syntax is correct; otherwise, the interpreter displays an
error message.Syntax refers to the structure of a program and the rules about that structure.For
example, parentheses have to come in matching pairs, so (1 + 2) is legal.

3)what is Semantic errors?

The third type of error is the semantic error. If there is a semantic error in your program, it will run successfully in the sense that the computer will not generate any error messages, but it will not do the right thing. It will do something else. Specifically, it will do what you told it to do.

The problem is that the program you wrote is not the program you wanted to write. The meaning of
the program (its semantics) is wrong. Identifying semantic errors can be tricky because it requires
you to work backward by looking at the output of the program and trying to figure out what it is

The first program Traditionally, the first program you write in a new language is called “Hello, World!” because all it does is display the words, “Hello, World!” In Python, it looks like this: print ‘Hello, World!’ This is an example of a print statement2 , which doesn’t actually print anything on paper. It displays a value on the screen. In this case, the result is the words Hello, World! The quotation marks in the program mark the beginning and end of the text to be displayed; they don’t appear in the result. Some people judge the quality of a programming language by the simplicity of the “Hello, World!” program. By this standard, Python does about as well as possible.

9)What is interpreter?

An interpreter is a computer program that executes instructions written in a programming language. It can either execute the source code directly or translates the source code in a first step into a more efficient representation and executes this code

10)what iscompiler?

A compiler is a computer program that transforms (translates) source code of a programming language (the source language) into another computer language (the target language). In most cases compilers are used to transform source code into executable program, i.e. they translate code from high-level programming languages into low (or lower) level languages, mostly assembly ore machine code.  Many languages require you to compile (translate) your program into a form that the machine understands.

11)what is source code?

A program in a high-level language before being compiled.

12)What is object code?

The output of the compiler after it translates the program. executable: Another name for object code that is ready to be executed.

12)What is prompt?

Characters displayed by the interpreter to indicate that it is ready to take input from the user.

13)What is script?

A program stored in a file (usually one that will be interpreted). 14)What is interactive mode?

A way of using the Python interpreter by typing commands and expressions at the prompt.

15)What is script mode?

A way of using the Python interpreter to read and execute statements in a script. program: A set of instructions that specifies a computation.

16)What is bug?

An error in a program. Debugging,The process of finding and removing any of the three kinds of programming errors.

17)What is variable?

Variables are nothing but reserved memory locations to store values. A variable is a name that refers to a value. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory.

One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value. An assignment statement creates new variables and gives them values.

Assigning Values to Variables

Python variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign value to it.


>> message = ‘And now for something completely different’

>>> n = 17

>> pi = 3.1415926535897931 This example makes three assignments. The first assigns a string to a new variable named message; the second gives the integer 17 to n; the third assigns the (approximate) value of π to pi.

18)what is values and type?

A value is one of the basic things a program works with, like a letter or a number. The values we have seen so far are 1, 2, and ‘Hello, World!’. These values belong to different types: 2 is an integer, and ‘Hello, World!’ is a string, so-called because it contains a “string” of letters. You (and the interpreter) can identify strings because they are enclosed in quotation marks. The print statement also works for integers.


>>> print 4 4 If you are not sure what type a value has, the interpreter can tell you.

>>> type(‘Hello, World!’)

>>> type(17) Not surprisingly, strings belong to the type str and integers belong to the type int. Less obviously, numbers with a decimal point belong to a type called float, because these numbers are represented in a format called floating-point.

>>> type(3.2) What about values like ’17’ and ‘3.2’? They look like numbers, but they are in quotation marks like strings.

>>> type(’17’)

>>> type(‘3.2’) 10 Chapter 2. Variables, expressions and statements They’re strings. When you type a large integer, you might be tempted to use commas between groups of three digits, as in 1,000,000. This is not a legal integer in Python, but it is legal: >>> print 1,000,000 1 0 0 Well, that’s not what we expected at all! Python interprets 1,000,000 as a comma-separated sequence of integers, which it prints with spaces between. This is the first example we have seen of a semantic error: the code runs without producing an error message, but it doesn’t do the “right” thing.

19)What is python identifier?

A Python identifier is a name used to identify a variable, function, class, module or other object. An 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 punctuation characters such as @, $ and % within identifiers. Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.

20)What is line indentation in python?

In Python there are no braces to indicate blocks of code for class and function definitions or flow control. 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 .


Valid Block :

if True:

print True:


print false

Invalid block:

if True:

print “Answer”

print True:


print false

print “Answer”

21)what is multi-line statement ?

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.


Total=item one+\

item two+\

item three+\

item four

Statements contained within the [], {} or () brackets do not need to use the line continuation character.


month=[‘january’, ‘february’,’march’,’april’, ‘may’,’jun’,’july’]

22)What are the standard data types in python?

The data stored in memory can be of many types. Python has various standard types that are used to define the operations possible on them and the storage method for each of them.

Python has five standard data types:

Numbers • String • List • Tuple • Dictionary

23)What is python number data type?

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





print var3

Python supports four different numerical types:

1)Integers Generally signed, 32-bit

2)Long Integers Unlimited size Format: L

Example: 4294967296L

Float Platform dependent “double” precision

3)Complex Format: +j

Example: 6+3j

24)What is string data type in python?

Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable.

For example :

var=”Hello friends”

var1=”Welcome to this tutorial”

25)How to Access Values in Strings?

Python does not support a character type; these are treated as strings of length one, thus also considered a substring.

To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring.

For example :

var=”Hello friends”

var1=”Welcome to this tutorial”

print var[0]

print var1[1:8]

26)How to update strings in python?

To“update” an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether.

For example :

var=”Hello world”

print var[:6]+’friend’

27)What are Special Operators in string?

Followings are some special operators in string.

Operator Description Example
+ Concatenation – Adds values on either side of the operator a + b will give HelloPython
* Repetition – Creates new strings, concatenating multiple copies of the same string a*2 will give -HelloHello
[] Slice – Gives the character from the given index a[1] will give e
[ : ] Range Slice – Gives the characters from the given range a[1:4] will give ell
in Membership – Returns true if a character exists in the given string H in a will give 1
not in Membership – Returns true if a character does not exist in the given string M not in a will give 1
r/R Raw String – Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter “r,” which precedes the quotation marks. The “r” can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark. print r’\n’ prints \n and print R’\n’prints \n
% Format – Performs String formatting See at next section

28)What are the build-in string methods in python?

Python includes the following built-in methods to manipulate strings −

SN Methods with Description
1 capitalize()
Capitalizes first letter of string
2 center(width, fillchar)

Returns a space-padded string with the original string centered to a total of width columns.

3 count(str, beg= 0,end=len(string))

Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.

4 decode(encoding=’UTF-8′,errors=’strict’)

Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding.

5 encode(encoding=’UTF-8′,errors=’strict’)

Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with ‘ignore’ or ‘replace’.

6 endswith(suffix, beg=0, end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.
7 expandtabs(tabsize=8)

Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.

8 find(str, beg=0 end=len(string))

Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.

9 index(str, beg=0, end=len(string))

Same as find(), but raises an exception if str not found.

10 isalnum()

Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.

11 isalpha()

Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.

12 isdigit()

Returns true if string contains only digits and false otherwise.

13 islower()

Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.

14 isnumeric()

Returns true if a unicode string contains only numeric characters and false otherwise.

15 isspace()

Returns true if string contains only whitespace characters and false otherwise.

16 istitle()

Returns true if string is properly “titlecased” and false otherwise.

17 isupper()

Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.

18 join(seq)

Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.

19 len(string)

Returns the length of the string

20 ljust(width[, fillchar])

Returns a space-padded string with the original string left-justified to a total of width columns.

21 lower()

Converts all uppercase letters in string to lowercase.

22 lstrip()

Removes all leading whitespace in string.

23 maketrans()

Returns a translation table to be used in translate function.

24 max(str)

Returns the max alphabetical character from the string str.

25 min(str)

Returns the min alphabetical character from the string str.

26 replace(old, new [, max])

Replaces all occurrences of old in string with new or at most max occurrences if max given.

27 rfind(str, beg=0,end=len(string))

Same as find(), but search backwards in string.

28 rindex( str, beg=0, end=len(string))

Same as index(), but search backwards in string.

29 rjust(width,[, fillchar])

Returns a space-padded string with the original string right-justified to a total of width columns.

30 rstrip()

Removes all trailing whitespace of string.

31 split(str=””, num=string.count(str))

Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given.

32 splitlines( num=string.count(‘\n’))

Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.

33 startswith(str, beg=0,end=len(string))

Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise.

34 strip([chars])

Performs both lstrip() and rstrip() on string

35 swapcase()

Inverts case for all letters in string.

36 title()

Returns “titlecased” version of string, that is, all words begin with uppercase and the rest are lowercase.

37 translate(table, deletechars=””)

Translates string according to translation table str(256 chars), removing those in the del string.

38 upper()

Converts lowercase letters in string to uppercase.

39 zfill (width)

Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).

40 isdecimal()

Returns true if a unicode string contains only decimal characters and false otherwise.



About the author: Mahgul Afzali

Leave a Reply

Your email address will not be published.