1 - Introduction To Python Programming
1 - Introduction To Python Programming
1.3.3 High Level Language: High level languages are English like statements and programs Written in these
languages are needed to be translated into machine language before execution using a system software such as
compiler. Program written in high level languages are much easier to maintain and modified.
High level language program is also called source code.
Machine language program is also called object code
Merits:
Since it is most flexible, variety of problems could be solved easily
Programmer does not need to think in term of computer architecture which makes them focused on the
problem.
Programs written in this language are portable.
Demerits:
It is easier but needs higher processor and larger memory.
It needs to be translated therefore its execution time is more.
Interpreter Compiler
Translates program one statement at a time. Scans the entire program and translates it into machine
code.
It takes less amount of time to analyze the source code but It takes large amount of time to analyze the source
the overall execution time is slower. code but the overall execution time is comparatively
faster.
No intermediate object code is generated, hence are Generates intermediate object code which further
memory efficient. requires linking, hence requires more memory.
Continues translating the program until the first error is It generates the error message only after scanning the
met, in which case it stops. Hence debugging is easy. whole program. Hence debugging is comparatively
hard.
Programming language like Python, Ruby use interpreters. Programming language like C, C++ use
compilers.
Exercises
1. What is a programming language?
2. Explain different types of programming languages?
3. What is a compiler?
4. What is an interpreter?
5. How is compiled or interpreted code different from source code?
6. Difference between Interpreter and Compiler?
Web Applications
You can create scalable Web Apps using frameworks and CMS (Content Management System) that are built
on Python.
Some of the popular platforms for creating Web Apps are: Django, Flask, Pyramid, Plone, Django CMS.
Sites like Mozilla, Reddit, Instagram and PBS are written in Python.
Scientific and Numeric Computing
There are numerous libraries available in Python for scientific and numeric computing. There are libraries
like: SciPy and NumPy that are used in general purpose computing. And,
there are specific libraries like: EarthPy for earth science, AstroPy for Astronomy and so on.
Also, the language is heavily used in machine learning, data mining and deep learning.
Script Mode
This mode is used to execute Python program written in a file. Such a file is called a script. Scripts can
be saved to disk for future use. Python scripts should have the extension .py, it means that the filename
ends with .py.
For example: helloWorld.py
To execute this file in script mode we simply write python3 helloWorld.py at the command prompt.
$ python3
Python 3.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
Type the following text at the Python prompt and press the Enter:
If you are running new version of Python, then you need to use print statement with parenthesis as in print ("Hello,
IIIT RK Valley");. However in Python version 2.7, this produces the following result:
To write Python programming in script mode we have to use editors. Let us write a simple Python program in a script
mode using editors. Python files have extension .py. Type the following source code in a simple.py file.
Program 2.1 (simple.py) is one of the simplest Python programs that does something
We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows:
$ python3 simple.py
This produces the following result:
Exercise
1. What is Python Programming Language?
2. How many ways can run the Python Programming?
3. What is print statement
4. What is prompt
5. Print “Welcome to Python Programming Language” from interactive Python.
6. Write above statement in exercise1.py to print the same text.
7. Run the modified exercise1.py script.
8. Write the below statements in exercise2.py to print the same below
Module-3 Reserved key words, Identifiers, Variables and Constant
1.14 Keywords
Keywords are the reserved words in Python and we cannot use a keyword as variable name, function name or
any other identifier.
They are used to define the syntax and structure of the Python language.
In Python, keywords are case sensitive.
There are 35 keywords in Python 3.7.3 This number keep on growing with the new features coming in python
All the keywords except True, False and None are in lowercase and they must be written as it is.
The list of all the keywords is given below
We can get the complete list of keywords using python interpreter help utility.
$ python3
>>> help()
help> keywords
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal
yield
break for not
1.15 Identifiers
Identifier is the name given to entities like class, functions, variables etc. in Python. It helps differentiating one entity
from another.
Rules for writing identifiers
Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an
underscore (_).
Names like myClass, var_1 and print_this_to_screen, all are valid example.
An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
Keywords cannot be used as identifiers.
>>> global = 1 File "<interactive input>", line 1
global = 1
^SyntaxError: invalid syntax
We cannot use special symbols like !, @, #, $, % etc. in our identifier. >>> a@ = 0
File "<interactive input>", line 1a@ = 0^
SyntaxError: invalid syntax
Identifier can be of any length.
1.17 Variable
A variable is a location in memory used to store some data.
Variables are nothing but reserved memory locations to store values, this means that when we create a
variable, we reserved some space in memory.
They are given unique names to differentiate between different memory locations.
The rules for writing a variable name are same as the rules for writing identifiers in Python.
We don't need to declare a variable before using it.
In Python, we simply assign a value to a variable and it will exist.
We don't even have to declare the type of the variable. This is handled internally according to the type of
value we assign to the variable.
Variable assignment: We use the assignment operator (=) to assign values to a variable. Any type of value can be
assigned to any valid variable.
a=5
b = 3.2
c = "Hello"
Here, we have three assignment statements. 5 is an integer assigned to the variable a.
Similarly, 3.2 is a floating-point number and "Hello" is a string (sequence of characters) assigned to the variables b
and c respectively.
Multiple assignments:
In Python, multiple assignments can be made in a single statement as follows: a, b, c = 5, 3.2, "Hello"
If we want to assign the same value to multiple variables at once, we can do this as x = y = z = "same"
This assigns the "same" string to all the three variables.
Constants: A constant is a type of variable whose value cannot be changed. It is helpful to think of constants as
containers that hold information which cannot be changed later. You can think of constants as a bag to store some
books which cannot be replaced once placed inside the bag.
Assigning value to constant in Python In Python, constants are usually declared and assigned in a module. Here, the
module is a new file containing variables, functions, etc which is imported to the main file. Inside the module,
constants are written in all capital letters and underscores separating the words.
Example 1: Declaring and assigning value to a constant
Create a constant.py:
PI = 3.14
GRAVITY = 9.8
Create a main.py:
import constant
print(constant.PI)
print(constant.GRAVITY)
Output
3.14
9.8
In the above program, we create a constant.py module file. Then, we assign the constant value to PI and GRAVITY.
After that, we create a main.py file and import the constant module. Finally, we print the constant value.
Note: In reality, we don't use constants in Python. Naming them in all capital letters is a convention to separate them
from variables, however, it does not actually prevent reassignment.
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
8. Assume that we execute the following assignment statements: width = 17, height = 12.0
For each of the following expressions, write the value of the expression and the type (of the value of the
expression).
a. width/2
b. width/2.0
c. height/3
d. 4. 1 + 2 * 5
Write program and also Use the Python interpreter to check your answers.
9. Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and
print out the converted temperature.
10. Will the following lines of code print the same thing? Explain why or why not.
x=6
print(6)
print("6")
11. Will the following lines of code print the same thing? Explain why or why not.
x=7
print(x)
print("x")
12. What happens if you attempt to use a variable within a program, and that variable has not been assigned a
value?
13. What is wrong with the following statement that attempts to assign the value ten to variable x?
10 = x
14. In Python can you assign more than one variable in a single statement?
15. Classify each of the following as either a legal or illegal Python identifier:
a. Flag h. sumtotal
b. if i. While
c. 2x j. x2
d. -4 k. $16
e. sum_total l. _static
f. sum-total m. wilma’s
g. sum total
16. What can you do if a variable name you would like to use is the same as a reserved word?
17. What is the difference between the following two strings? ’n’ and ’\n’?
18. Write a Python program containing exactly one print statement that produces the following output
Example: x = 10;y = 12
print('x > y is',x>y)
1.19.3 Logical (Boolean) Operators
Logical operators are the and, or, not operators
Operator Meaning Example
and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x
Here is an example.
x = True y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
1.19.4 Bitwise Operators
Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name.
For example, 2 is 10 in binary and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Operator Meaning Example
& Bitwise AND x& y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x>> 2 = 2 (0000 0010)
<< Bitwise left shift x<< 2 = 40 (0010 1000)
Example: >>>(40+20)*30/10
Output: 180
Generally input() function is used to retrieve string values from the user.
We can use the above mentioned functions in python 2.x, but not on python 3.x. input() in python 3.x always return a
string. Moreover, raw_input() has been deleted from python 3
python2.x python3.x
raw_input() -------------- input()
input() ------------------- eval(input())
We can simply say in python 3.x only use of the input () function to read value from the user and it assigns a string to a
variable.
x = input()
The parentheses are empty because, the input function does not require any information to do its job.
Program 3.7 (usinginput.py) demonstrates that the input function produces a string value.
The second line shown in the output is entered by the user, and the program prints the first, third, and fourth lines.
After the program prints the message Please enter some text:, the program’s execution stops and waits for the user to
type some text using the keyboard. The user can type, backspace to make changes, and type some more. The text the
user types is not committed until the user presses the Enter (or return) key. In Python 3.X, input() function produces
only strings, by using conversion functions we can change the type of the input value. Example as int(), str() and
float().
Exercise
1. Explain type of operators
2. Find whether these expressions will evaluate to True or False. Then try them in interactive mode and script
mode
a. 4 > 5
b. 12 != 20
c. 4 <= 6
d. 4 => 1
e. 'sparrow' > 'eagle'
f. 'dog' > 'Cat' or 45 % 3 == 0
g. 42+12 < 34//2
h. 60 - 45 / 5 + 10 == 1 and 32*2 < 12
3. Write a python program to find type of the value of below expressions
a. 4 > 23
b. 5+=21
c. 2**=3
4. What is compound assignment operator? Explain with examples?
5. Difference between ‘=’ and ‘==’
6. Difference between ‘/’ and ‘//’
7. Write a python program to prompts the user for x and y operands and find result for all arithmetic operators.
Multiple Choice Questions
1. Python is -------
a) Objected Oriented Programming Language
b) Powerful Programming Language
c) Powerful scripting Language
d) All the above
2. Python is developed by ------------
a) Guido van Rossum.
b) Balaguruswami
c) James Gosling
d) None of the above
3. Which of the following is not a keyword?
a) eval
b) assert
c) nonlocal
d) pass
4. All keywords in Python are in _________
a) lower case
b) UPPER CASE
c) Capitalized
d) None of the mentioned
5. Which of the following is true for variable names in Python?
a) unlimited length
b) all private members must have leading and trailing underscores
c) underscore and ampersand are the only two special characters allowed
d) none of the mentioned
6. Which of the following translates and executes program code line by line rather than the whole program in
one step?
a) Interpreter
b) Translator
c) Assembler
d) Compiler
7. Which of the following languages uses codes such as MOVE, ADD and SUB?
a) assembly language
b) Java
c) Fortarn
d) Machine language
8. What is the output of the following assignment operator?
y = 10
x = y += 2
print(x)
a) 12
b) 10
c) Syntax error
9. What is assignment operator?
a) = =
b) =
c) +=
d) - =
10. What is a correct Python expression for checking to see if a number stored in a variable x is between 0 and 5?
a) x>0 and <5
b) x>0 or x<5
c) x>0 and x<5
Descriptive Questions:
1. Explain about Applications and Features of Python Programming Language?
2. Write short notes on types of operators in python with appropriate examples?
3. Explain about interpreter and compiler?
4. Explain about identifiers
5. Explain about types of modes
6. Explain briefly about:
Constant and variables
keywords and statement
Solved Problems:
1. Evaluate the value of z=x+y*z/4%2-1
x=input(“Enter the value of x= ”)
y=input(“Enter the value of y= “)
z=input(“Enter the value of z= “)
a=y*z
b=a/4
c=b%2
t=x+c-1
print(“the value of z=x+y*z/4%2-1 is”,t)
input: Enter the value of x=2
Enter the value of y=3
Enter the value of z=4
Output: the value of z=x+y*z/4%2-1 is 2
Note: while solving equations follow the BEDMAS or PADMAS Rule
2. Python program to show bitwise operators
a = 10
b=4
# Print bitwise AND operation
print("a & b =", a & b)
# Print bitwise OR operation
print("a | b =", a | b)
# Print bitwise NOT operation
print("~a =", ~a)
# print bitwise XOR operation
print("a ^ b =", a ^ b)
Output:
a&b=0
a | b = 14
~a = -11
a ^ b = 14
Unsolved Problems:
1. Write a program to find out the value of 9+3*9/3?
2. Write a program to find out the value of (50-5*6)/4?
3. Write a program to find out the value of 3*3.75/1.5?
4. 45-20+(10?5)%5*3=25 what is the operator in the place of “?” mark?
5. 3*6/22%2+7/2*(3.2-0.7)*2 in this problem which one is evaluated first? finally what is the answer?
6. Write a program to display Arithmetic operations for any two numbers?
7. Python Program to find the average of 3 numbers?
8. Write a python program to find simple and compound interest?
References:
Book: Python programming (Using Problem Solving Approach) – REEMA THARAJA