You are on page 1of 29

Module 1

Introduction To Python

Text Book - Allen Downey, Jeffrey Elkner, Chris Meyers, “ How to think like a Computer Scientist-
Learning with Python”, Green Tea Press, First edition, 2002.
Module 1 Topics 9 Hours
• Introduction To Python:
• Understanding Python-identifiers, variables, keywords, expressions and
statements.
• Evaluation of expressions
• Operators and operands
• Operator precedence
• Indentation
• Python Program Flow Control:
• Decision making- if, if..else, elif.
• Loops - for, while, for...else, while...else
• Control statements using pass, continue, break.
The Python programming language
• Python is an example of a high-level language
• Other high-level languages you might have heard of are C, C++, Perl, and Java.
• Like high-level language there are also low-level languages, sometimes referred to
as machine languages or assembly languages.
• Computers can only execute programs written in low-level languages.
• Thus, programs written in a high-level language have to be processed before they can
run. This extra processing takes some time, which is a small disadvantage of high-
level languages.
ADVANTAGES OF HIGH-LEVEL LANGUAGES
• It is much easier to program in a high-level language.
• Programs written in a high-level language take less time to write
• They are shorter and easier to read, and they are more likely to be correct.
• High-level languages are portable, meaning that they can run on different kinds of
computers with few or no modifications.
• Low-level programs can run on only one kind of computer and have to be
rewritten to run on another. So almost all programs are written in high-level
languages and Low-level languages are used only for a few specialized
applications.
Converting high-level languages into low-level languages
• Two kinds of programs are available
1. Interpreters
2. Compilers.
• An interpreter reads a high-level program and executes it, meaning that it
does what the program says.
• It processes the program a little at a time, alternately reading lines and
performing computations.
• A compiler reads the program and translates it completely before the
program starts running.
• In this case, the high-level program is called the source code, and the
translated program is called the object code or the executable.
• Once a program is compiled, you can execute it repeatedly without further
translation.
• Python is considered an interpreted language because Python programs are
executed by an interpreter.
• There are two ways to use the interpreter
• Command-line mode
• Script mode.
• In command-line mode, you type Python programs and the interpreter prints
the result:

>>> print (1 + 1)
2
• We can write a program in a file and use the interpreter to execute the
contents of the file. Such a file is called a script.
• Files that contain Python programs have names that end with.py.
• To execute the program, we have to tell the interpreter the name of the script:
>>> python add.py
Print Statement
• It displays a value on the screen.
• Eg: print (“ Hello, world !”)
• The quotation marks in the program mark the beginning and end of the
value; they don’t appear in the result.

>>> print (“Hello, world !”)

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

output -> Hello, world!


Taking input in Python
• Python provides us with the inbuilt functions input() to read the input from
the keyboard.
How the input function works in Python :
• When input() function executes program flow will be stopped until the user
has given an input.
• The text or message display on the output screen to ask a user to enter input
value is optional i.e. the prompt, will be printed on the screen is optional.
• Whatever you enter as input, input function convert it into a string. if you
enter an integer value still input() function convert it into a string. You need
to explicitly convert it into an integer in your code using typecasting.
Values and types
• A Value is one of the fundamental things- like a letter or a number, that a
program manipulates.
Eg: 2, Hello, world!
• These values belong to different types:
• 2 is an integer
• "Hello, World!" is a string,
• Value types are means to identify the type of the value. If we are not sure
what type a value has, the interpreter can tell us.
• Eg: >>> type(‘hello, world’)
<type ’str’>
>>> type(17)
<type ’int’>
>>> type(3.2)
<type ’float’>
>>> type(‘17’)
<type ‘str’>
>>> type(‘3.2’)
<type ‘str’>
• They look like numbers, but they are in quotation marks like strings

• When we type a large integer, we use commas between groups of three digits, as
in 1,000,000. This is not a legal integer in Python, but it is a legal expression:
>>> print (1,000,000)
100
• Python interprets 1,000,000 as a comma-separated list of three integers, which it
prints consecutively.
Exercise Questions
To Familiarize Command-line mode
1. Python Program to Print Hello world
2. Python Program to Add Two Numbers
3. Python Program to Subtract Two Numbers
4. Python Program to read and display a string
5. Python Program to Add Two Numbers using input method
6. Python Program to Subtract Two Numbers using input method
To Familiarize Script mode
8. Python Program to read and display a string
9. Python Program to read and Add Two Numbers
10. Python Program to read and Multiply Two Numbers
Variables or Identifiers
• An Identifiers or Variable is a sequence of characters invented by the
programmer to identify or name a specific object.
• The sequence of characters include letters, digits and underscore.
The following are five rules for naming Identifiers
1. Variable names are case sensitive
eg: A variable named ‘NUMBER’ is not same as the variable named ‘number’.
This two refers to different variables.
2. The first character must be an alphabetic character or an underscore ‘_’.
3. A numeric digit should not be used as the first character of an Identifier.
4. Identifiers may be of any reasonable length, generally eight to ten
characters long. >>> _a=1
5. The identifier name should not be a keyword of Python. >>> print(_a)
1
>>> 76trombones = ‘big parade’
Syntax Error: invalid syntax

>>> more$ = 1000000


Syntax Error: invalid syntax

>>> class = ‘Computer Science 101’


Syntax Error: invalid syntax

• 76trombones is illegal because it does not begin with a letter.


• more$ is illegal because it contains an illegal character, the dollar sign.
• class is one of the Python keywords.
Keywords
• Keywords are the words that convey a special meaning to the language
interpreter.
• These are reserved for special purpose and cannot be used for any other
purpose in a Python program.
• We cannot use a keyword as a variable name, function name or any other
identifier.
• The Python contains the following 35 keywords.
>>> import keyword
>>> print(keyword.kwlist)

• ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class’,
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global’,
'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return’,
'try', 'while', 'with', 'yield']
Statements
• A statement is an instruction that the Python interpreter can execute.
• We have seen two kinds of statements:
print and assignment.
• Print statement
• When you type a statement on the command line, Python executes it and
displays the result.
• The result of a print statement is a value.

• Assignment statement
• Assignment statements don’t produce a result.
• A script usually contains a sequence of statements.
• If there is more than one statement, the results appear one at a time as the
statements execute.
• For example, the script
print 1
x=2
print x
• produces the output
1
2
Evaluating expressions
• An expression is a combination of values, variables, and operators.
• If you type an expression on the command line, the interpreter evaluates it
and displays the result:
>>> 1 + 1*5
6

>>> 17
17
• evaluating an expression is not quite the same thing as printing a value.

>>> message = ‘Hello, World!’


>>> message
‘Hello, World!’

>>> print message


Hello, World!
Operators and operands
• Operators are special symbols that represent computations like addition,
substraction, multiplication etc…
• The values the operator uses are called operands.
• The asterisk (*) is the symbol for multiplication, and ** is the symbol for
exponentiation.
• When a variable name appears in the place of an operand, it is replaced with its
value before the operation is performed.
Order of operations
• When more than one operator appears in an expression, the order of evaluation
depends on the rules of precedence.
• Python follows the same precedence rules for its mathematical operators that
mathematics does.
• The acronym PEMDAS is a useful way to remember the order of operations:
• Parentheses have the highest precedence and can be used to force an
expression to evaluate in the order you want.
• Since expressions in parentheses are evaluated first,
2 * ( 3-1) is 4, and
(1+1)**(5-2) is 8.
• Exponentiation has the next highest precedence,
so 2**1 +1 is 3 and not 4,
and 3*1**3 is 3 and not 27.
• Multiplication and Division have the same precedence, which is higher
than Addition and Subtraction, which also have the same precedence.
• So 2 * 3 - 1 yields 5 rather than 4, and
2 / 3 - 1 is -1, not 1 (remember that in integer division, 2/3=0).
• Operators with the same precedence are evaluated from left to right.
• So in the expression minute * 100 / 60, the multiplication happens first,
yielding 5900/60, which in turn yields 98.
Operations on strings
• In general, you cannot perform mathematical operations on strings, even if
the strings look like numbers. The following are illegal
• Message - 1 ‘Hello’ / 123 message * ‘Hello’ ‘15’+2
• For strings, the + operator represents concatenation.
>>> fruit = ‘banana’ >>> fruit='banan'
>>> bakedgood=' nut bread'
>>>bakedGood = ‘nut bread’ >>> print (fruit + bakedgood)
banan nut bread
>>>
>>> print fruit + bakedGood
• The output of this program is banana nut bread.
• The * operator also works on strings; it performs repetition.
• For example, ’Fun’*3 is ’FunFunFun’. Where one of the operands has to be
a string; the other has to be an integer.
Comments
• Comment is a line of text inserted in the program body to understand the
program easier.
• Single line comments are marked with the # symbol:
• Multi line comments ‘‘‘ ’’’ (three single commas)

Eg: # program to find the factorial of given number


• You can also put comments at the end of a line:
• percentage = (minute * 100) / 60 # caution: integer division
• Everything from the # to the end of the line is ignored—it has no effect on
the program.
Composition
• One of the most useful features of programming languages is their ability to
take small building blocks and compose them.
• For example, we know how to add numbers and we know how to print; it
turns out we can do both at the same time:
>>> print (17 + 3)
20
• In reality, the addition has to happen before the printing, so the actions aren’t
actually happening at the same time.
>>> hour=1
>>> minute=2
>>> print ('number of minutes since midnight -’ , hour*60+minute )
number of minutes since midnight - 62
Indentation
• Indentation refers to the spaces at the beginning of a code line.
• Where in other programming languages the indentation in code is for readability
only, the indentation in Python is very important.
• Python uses indentation to indicate a block of code.
if 5 > 2:
print("Five is greater than two!")
• python will give you an error if you skip the indentation:
• The number of spaces is up to you as a programmer, but it has to be at least one.
• We have to use the same number of spaces in the same block of code, otherwise
Python will give you an error:
The modulus operator
• In Python, the modulus operator is a percent sign (%).
• It always find the remainder.
• This operator return an integer value.
remainder = 7 % 3
>>> print remainder
1
Boolean expressions
• A boolean expression is an expression that is either true or false.
• One way to write a boolean expression is to use the operator ==, which
compares two values and produces a boolean value:
>>> 5 == 5
True
>>> 5 == 6
False
• In the first statement, the two operands are equal, so the value of the
expression is True;
• In the second statement, 5 is not equal to 6, so we get False.
• The == operator is one of the comparison operators; the others are:
x != y # x is not equal to y
x > y # x is greater than y X=5,
x < y # x is less than y Statement
Y=2 Result
x >= y # x is greater than or equal to y
X>Y True
x <= y # x is less than or equal to y
X<Y False
>>> X=5 X! =Y True
>>> Y=6
>>> X<Y X>=Y True
True
X<=Y False
Logical operators
• There are three logical operators: and, or and not.
• Any nonzero number is interpreted as “true.”
>>> x = 5
>>> x and 1
1
>>> y = 0
>>> y and 1
0
x =1 y=o
>>> not x
False
>>> not y
True

You might also like