You are on page 1of 72

Python Basics

Computer Science 083


2

© Department of Computer Science, DPS R.K.Puram, New Delhi


Unit II: Computational Thinking and Programming – 1 2

● Familiarization with the basics of Python programming: Introduction to


Python, features of Python, executing a simple "hello world" program,

© Department of Computer Science, DPS R.K.Puram, New Delhi


execution modes: interactive mode and script mode, Python character set,
Python tokens (keyword, identifier, literal, operator, punctuator), variables,
concept of l-value and r-value, use of comments
● Knowledge of data types: number (integer, floating point, complex), boolean,
sequence (string, list, tuple), none, mapping (dictionary), mutable and
immutable data types
● Operators: arithmetic operators, relational operators, logical operators,
assignment operator, augmented assignment operators, identity operators(is,
is not), membership operators(in, not in)
● Expressions, statement, type conversion & input/output: precedence of
operators, expression, evaluation of expression, python statement, type
conversion (explicit & implicit conversion), accepting data as input from the
console and displaying output
Python - The Programming Language 3

Python was developed by Guido van Rossum and released in 1991.

© Department of Computer Science, DPS R.K.Puram, New Delhi


Python is an Interpreter based scripting language, which can be used:

● to create web based applications.


● to connect to database systems and to read and modify files.
● to handle big data and perform complex mathematics.
● for rapid software development.
Python installation 4

To try the programs, you need to download Python from python.org only.

© Department of Computer Science, DPS R.K.Puram, New Delhi


Presently, the latest version is 3.8.2.
However, you can download any version 3.6 onwards.

During installation, opt for Custom installation, and set the installation path for
python as C:\Python38 and let it install in default location.
Online Python 5

Every gmail account as well as your school official account allows you work on

© Department of Computer Science, DPS R.K.Puram, New Delhi


Python programs with in it through the URL - colab.research.google.com

In colab, you can type/edit the Python program online, run the Python program,
add notes along the code, share it with the teacher and peer to work in
collaboration. All this will happen as a part of your Google cloud/drive and you
don't have to bother about saving your program, but don't forget to name each
colab notebook with a meaningful name for your later comeback and work on it.
Each colab notebook will allow you to create multiple Python codes.
Python - The Programming Language 6

Python stands out as the present generation Programming Language because of the

© Department of Computer Science, DPS R.K.Puram, New Delhi


following reasons:
● It works on multiple platforms (Windows, Mac, Linux, Android, iOS, Raspberry
Pi, etc).
● It has a simple syntax that allows developers to write robust programs easily
and efficiently.
● It can be used to write procedural as well as object-oriented codes.
Python - The Programming Language 7

Python codes can be executed in:

© Department of Computer Science, DPS R.K.Puram, New Delhi


● Interactive mode (Shell) using the Python IDLE (Integrated DeveLopment
Environment) to execute single line Python commands (Recommended version
3.6 and above and can be downloaded only from Python official website.
https://www.python.org)
● Scripting mode (Editor) to write program and execute its statements line by
line and get the result in the Python shell.
● Using Jupyter Notebook - for editing and executing ongoing series of codes in
a single file. colab.research.google.com as a part of your own gmail account
can also be used to create online Python notebooks, which will allow you to
have Basic Formatted Text, Codes and Output in a single place.
What makes a language? 8

Every language (machine or natural, it doesn't matter) consists of the following

© Department of Computer Science, DPS R.K.Puram, New Delhi


elements:
● An Alphabet : a set of symbols used to build words of a certain language (e.g.,
the Latin alphabet for English, the Cyrillic alphabet for Russian, Kanji for
Japanese, Devanāgarī (दे वनागरी) for Hindi, Marathi, Sanskrit, Nepali and so on)
● A Lexis : (i.e. a dictionary) a set of words the language offers its users (e.g.,
the word "computer" comes from the English language dictionary, while
"cmoptrue" doesn't; the word "chat" is present both in English and French
dictionaries, but their meanings are different)
What makes a language? (contd…) 9

● A Syntax : a set of rules (formal or informal, written or felt intuitively) used


to determine if a certain group of words forms a valid sentence (e.g., "I am a

© Department of Computer Science, DPS R.K.Puram, New Delhi


python" is a grammatically correct phrase, while "I a python am" isn't)
● Semantics : a set of rules determining if a certain phrase makes sense (e.g., "I
ate a doughnut" makes sense, but "A doughnut ate me" doesn't)
● Computer Languages which act as a bridge between natural human language
and computer understandable instructions are called high-level programming
languages.
● They are similar to natural languages since they use symbols, words and
conventions readable to humans.
● Set of instructions (a program) written in a high-level
programming is called a Source Code
What makes Python special? 10

● It's easy to learn - the time needed to learn Python is shorter than for many

© Department of Computer Science, DPS R.K.Puram, New Delhi


other languages; this means that it's possible to start solving problems using
programs faster;
● It's easy to use for writing new software - it's often possible to write code
faster when using Python;
● It's easy to understand - it's also often easier to understand someone else's
code faster if it is written in Python;
● It's easy to obtain, install and deploy - Python is free, open and
multiplatform; not all languages can boast that.
Quiz 11

Python in an example of :

© Department of Computer Science, DPS R.K.Puram, New Delhi


a. A high level programming language
b. A natural language
c. A machine Language

Ans:
a. A high level programming language
Quiz 12

What is a source code?

© Department of Computer Science, DPS R.K.Puram, New Delhi


a. The code, which is directly executed by computers
b. The code, which is produced by computer
c. A program written in a high level programming language

Ans:
c. A program written in a high level programming language
Quiz 13

What is IDLE?

© Department of Computer Science, DPS R.K.Puram, New Delhi


a. It is an acronym that stands for Integrated Development and Learning
Environment for Python
b. It is a Python version
c. It is an acronym for Integrated Development and Learning Extension

Ans:
a. It is an acronym that stands for Integrated development and
learning environment for Python
Literals - the data in itself 14

A literal is a data, whose value is determined by the literal itself.

© Department of Computer Science, DPS R.K.Puram, New Delhi


Let us take example of a some of the values as follows:
● 123
● 1252.75
● "Welcome to 11"
● True
Each of the above values represent a data. However, owing to their different data
types, they are categorised as following:
● int Integer
● float Floating point
● str String
● bool Boolean
Data types - Integer, Float, String or Boolean 15

The type of each of the different data as given in the previous slide can be
determined by the command type() in Python as follows:

© Department of Computer Science, DPS R.K.Puram, New Delhi


>>> type(123)
<class 'int'> Integer type data
>>> type(1252.75)
<class 'float'> Float type data
>>> type("Welcome to 11")
<class 'str'> String type data
>>> type(True)
<class 'bool'> Bool or Boolean type data
Integer vs. Float 16

The decimal point is essentially important in recognizing floating-point numbers in

© Department of Computer Science, DPS R.K.Puram, New Delhi


Python.

4 is an int

4.0 is a float

You may think that they are exactly the same, but Python sees them in a
completely different way.

It is also important to note that it is not only a decimal point which makes a
numerical value float. A float value can also be represented using the exponent
notation E. For example 4E8 is a float value representing 4 x 108
Strings 17

● Strings are used when you need to process text (like names of all kinds,
addresses, novels etc.), not numbers.

© Department of Computer Science, DPS R.K.Puram, New Delhi


● Strings need quotes the way float needs a point.
● You may enclose a string either within a set of single quotes or double quotes.

The following are some valid examples of strings in Python:

"This is a string"
'This is a string'
"It's Correct"
'I am "Monty Python"'
"I am 'Monty Python'"
Boolean values 18

Boolean values are determined by the truthfulness of a logical statement. For

© Department of Computer Science, DPS R.K.Puram, New Delhi


example, each time when you ask whether one number is greater than another, it
would result into an answer which is either True or False denoted as 1 and 0.

>>> type(True)
<class 'bool'>
Converts the boolean literal True into its
>>> int(True) equivalent integer 1
1
>>> type(False)
<class 'bool'>
Converts the boolean literal False into its
>>> int(False) equivalent integer 0
0
Quiz 19

What type of literal is the following example?

© Department of Computer Science, DPS R.K.Puram, New Delhi


"207"

a. int
b. float
c. str
d. bool

Ans:
c. str
Quiz 20

© Department of Computer Science, DPS R.K.Puram, New Delhi


What types of literals are the following four examples?

a. "Monty Python's circus"


b. 2.0
c. 528
d. False

a. str
b. float
c. int
d. bool
Arithmetic operators 21

Python uses the following arithmetic operators upon different type of data

© Department of Computer Science, DPS R.K.Puram, New Delhi


depending upon compatibility of the operator with the literal upon which it is
used:
Pno Name Symbol Example Result

1. Exponential ** 3**2 9
6.25 ** 0.5 2.5
2. Multiplication * 4 * 3 12
2.5 * 2 5.0
"Python" * 2 "PythonPython"
Arithmetic operators 22

Pno Name Symbol Example Result

© Department of Computer Science, DPS R.K.Puram, New Delhi


3. Division / 3/2 1.5
6.0/3 2.0
4. Floor Division // 7 // 2 3
5 // 2.0 2.0
5. Remainder/Modulo % 7 % 2 1
7.0 % 5 2.0
6. Addition + 7 + 3 10
7.0 + 2 9.0
"1" + "2" "12"
"Class" + " " + "11" "Class 11"
7. Subtraction - 7 - 2 5
5.25 - 2 3.25
Precedence of Operators 23

© Department of Computer Science, DPS R.K.Puram, New Delhi


Seq Operators Seq Operators

1 () 5 + - (Binary Operators)

2 ** 6 <= < > >=

3 + - (Unary Operators) 7 == !=

4 * / % // 8 = %= /= //= -= += *= **=
Evaluation of arithmetical expression 24

Result of an expression formed by combination of multiple arithmetic operators

© Department of Computer Science, DPS R.K.Puram, New Delhi


and data is always evaluated according to the order of precedence of the
operators in it. However the precedence may be altered by writing an operation
within parenthesis. For example:
Expression Result

2 + 3 * 5 17
2 1
(2 + 3) * 5 25
1 2
2 - 3 * 5 + 4 / 2 -11.0 Note: 4/2 = 2.0
3 1 4 2 9/3 = 3.0
2 + 3 * (5 - 4) / 2 3.5
4 2 1 3
Interesting Facts of Arithmetic Operations 25

While all arithmetic operators are left bound, the exponential operator ** is always

© Department of Computer Science, DPS R.K.Puram, New Delhi


right bound i.e. consecutive occurrences of ** operator in an expression is always
evaluated starting with the 2 operands in the right.

>>> 2 ** 3 ** 2
2 1 >>>2**(3**2)
512
512
>>>(2**3)**2
64

>>> 16 % 5 % 3
1 1 2 >>>(16 % 5) % 3
1
>>>16 % (5 % 3)
0
Interesting Facts of Arithmetic Operations 26

● A division operator / always gives the result of division in float i.e. with a

© Department of Computer Science, DPS R.K.Puram, New Delhi


decimal point irrespective of whether the operands are integer or float.
● A floor division // operator gives the nearest smaller integer of the division
result. (If Numerator or Denominator is float, the result is float equivalent to the int result)
● A modulo operator % evaluates the result of remainder of the division
operation upon the two operands for example Numerator % Denominator,
is always calculated using the convention:
Numerator = Quotient * Denominator + Remainder
or, Remainder = Numerator - Quotient * Denominator
where Quotient is the result of the Numerator // Denominator (Note
the floor division)
Thus, x % y is evaluated as x - (x // y) * y
Interesting Facts of Arithmetic Operations 27

>>> 7 / 2 >>> -7 // 2

© Department of Computer Science, DPS R.K.Puram, New Delhi


3.5 -4
>>> 4 / 2 >>> -7 % 2
2.0 1
>>> 7 // 2 **Calculation: x - (x // y) * y
-7-(-4)*2
3
-7+4*2
>>> 7.0 //2
-7+8 = 1
3.0
>>> -7 / 2 >>> 7 % -2
-3.5 -1
>>> 7 % 2 >>> 7.5 % -2
1 -0.5
>>> - 7.5 % 2
0.5
Interesting Facts of Arithmetic Operations 28

Strings can be operated with the arithmetic operators * and +

© Department of Computer Science, DPS R.K.Puram, New Delhi


With multiply operator *, if one of With the addition operator +, if one of
the operands is a string then the the operands is a string the the other
other operand must be an integer. operand must also be a string. In such
In such a case the string is a case the first string operand is
replicated the integer number of concatenated with the second string
times. Example:
operand. Example:
>>> "Hello" * 5
>>> "Hello" + "Class 11"
'HelloHelloHelloHelloHello'
>>> "*" * 20 'HelloClass 11'
'********************' >>> "Welcome "+"To "+"Python"
'Welcome To Python'
Variables - What are variables? 29

We have seen that arithmetic operations upon data gives a result. However, if we

© Department of Computer Science, DPS R.K.Puram, New Delhi


need to use these results of operations in other instructions, then we shall need to
store these results somewhere.

Python provides containers to store such values. These containers are called
variables and as the name suggests, the value stored in such a container can be
varied or altered at any point of execution.

Python variables have:

● A variable name. 230


VAL
E U "JA VALUE VAL
UE
00. CK 24
● An associated value. 50 T."

VARIABLE VARIABLE VARIABLE


AMOUNT NAME ROLLNO
Variables - Naming conventions 30

Variable names must follow some strict rules:

© Department of Computer Science, DPS R.K.Puram, New Delhi


● The name of the variable can be composed of uppercase or lowercase letters,
digits, and the character _ (underscore)
● The name of the variable must begin with a letter or an underscore _;
● Upper and lower case letters are treated as different (for example: Marks and
marks are two different variables);
● The name of the variable must not be any of Python's reserved words (the
keywords - we will learn about this soon).
Python keywords 31

Words with special meaning/purpose in a language are known as keywords

© Department of Computer Science, DPS R.K.Puram, New Delhi


False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Variables - Naming conventions 32

Following are some examples of correct Following are some examples of

© Department of Computer Science, DPS R.K.Puram, New Delhi


variable names: incorrect variable names:
My_name
My name Contains space
days_of_year
_Class_Section days#of#year Contains #
Chapter1 class Python Keyword
Name 1stChapter Starts with digit
FOR

(Can you guess why they are wrong?)


Creating Variables 33

A variable comes into existence as a result of assigning a value to it.

© Department of Computer Science, DPS R.K.Puram, New Delhi


If you assign any value to a nonexistent variable, the variable will be automatically
created.
The creation or its syntax is simple: just use the name of the desired variable,
then the equal sign (=) and the value you want to put into the variable.
Example:
My_name = "Monty Python"
The above instruction first creates a variable named My_name, and then assigns a
string literal "Monty Python" to the created variable My_name.
Using Variables 34

You're allowed to use as many variable declarations as you need to achieve your

© Department of Computer Science, DPS R.K.Puram, New Delhi


goal. Example:
>>> Value = 1
>>> Balance = 1000.0
>>> Name = 'John Doe'
The type of the value assigned to a created variable decides the type of the
variable:
>>> type(Value)
<class 'int'>
>>> type(Name)
<class 'str'>
>>> type(Balance)
<class 'float'>
Using Variables 35

However, you are not allowed to use a variable which has not been created i.e.

© Department of Computer Science, DPS R.K.Puram, New Delhi


which does not have a value assigned to it.

For example the following statement will throw an error:


>>> Age = 25
>>> type(age)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
type(age)
NameError: name 'age' is not defined

The reason of the error above is that we tried to find type of variable age, though
the variable which we had created was Age.
Using Variables 36

A variable in Python mutates itself according to the data assigned to it at any point

© Department of Computer Science, DPS R.K.Puram, New Delhi


of execution. For example:

>>> Value="Welcome"
>>> type(Value)
<class 'str'>
>>> Value = 25
>>> type(Value)
<class 'int'>
>>> Value = 4/2
>>> type(Value)
Can you guess why the type of
<class 'float'>
Value is float here ?
Using Variables 37

The value stored in a variable can be altered at any point of execution, using

© Department of Computer Science, DPS R.K.Puram, New Delhi


either a literal or by the value of another variable or an operation upon
variables/literals. For example:
>>> X = 25
>>> Y = X Variable Y is assigned value of X
>>> X
25
>>> Y
25
>>> X = Y + 15 Variable X is assigned Sum of
>>> X value of variable Y and 15
40
Using Variables 38

Variable Y is assigned twice its


>>> Y = Y * 2

© Department of Computer Science, DPS R.K.Puram, New Delhi


previous value
>>> Y
50
>>> X = X + Y
>>> X Variable X is assigned Sum of
90 its previous value and value of
>>> X = "Hello" variable Y
>>> Y = "Class"
>>> Z = X + " " + Y + " Eleven"
>>> Z
'Hello Class Eleven'
Quiz 39

Find the outputs of the following code for the red texted commands:

© Department of Computer Science, DPS R.K.Puram, New Delhi


>>>ver = "3.8"
>>>"Python version" + ver 'Python version3.8'
>>>X=3
>>>Y=2
>>>X**Y**X 6561
>>>Z=X+Y
>>>ver*Z
'3.83.83.83.83.8'
>>>type(ver*Z)
<class 'str'>
>>>Z = X // Y
>>>Z
1
>>>type(Z)
<class 'int'>
Comments: Single line 40

Comments in Python are used to describe what a particular segment of the code is

© Department of Computer Science, DPS R.K.Puram, New Delhi


doing. Comments are for increasing readability of a program. Python Interpreter
ignores comment.
In Python, we use the hash (#) symbol to start writing a comment. It extends up to
the newline character (till the enter key is pressed).

#The following statement is used to

#display the output My First Python

print('My First Python') #this statement is to display a value


Comments: Multi line 41

If a comment extends over multiple lines we can use triple quotes, either '''

© Department of Computer Science, DPS R.K.Puram, New Delhi


or """ to mark the beginning of a multi-line comment and similarly a pairing
set of ''' or """ to mark the end of the comment.

'''The following statement is used to


display the output My First Python'''
print('My First Python')
Knowledge of data types 42

NUMBER BOOLEAN SEQUENCE MAPPING

© Department of Computer Science, DPS R.K.Puram, New Delhi


int float complex bool str list tuple dict

345 34.5 3+5j True ("R",20,8.5) {1:20,2:40,3:60}

0 0.0 5.1+2.2j False [1,"Om",23] {"Rno":2,"Nm":"Om"}

-43 -4.3 -4+3j "AMAR" {"N1":2.5,"N2":3.2}

'Ram Nagar'
NONE

None Mutable Immutable

Content allowed to be
changed
Numbers and Arithmetic Expressions 43

A=20 A=20

© Department of Computer Science, DPS R.K.Puram, New Delhi


B=45 65 <class 'int'> B=40 2.0 <class 'float'>
C=A+B C=B/A
print(C,type(C)) print(C,type(C))

A=20 A=20
B=45 -25 <class 'int'> B=40 2 <class 'int'>
C=A-B C=B//A
print(C,type(C)) print(C,type(C))

A=20 A=2
B=45 900 <class 'int'> B=3 8 <class 'int'>
C=A*B C=A**B
print(C,type(C)) print(C,type(C))
Data Types in expressions and results 44

© Department of Computer Science, DPS R.K.Puram, New Delhi


-

<int> * <int> = <int>

**

<int> / <int> = <float>

<int> // <int> = <int>


Data Types in expressions and results 45

© Department of Computer Science, DPS R.K.Puram, New Delhi


-

<float> * <int> = <float>

**

<float> / <int> = <float>

<float> // <int> = <float>


Operators - Relational 46

Python Relational Operators are used to compare two values and return a result
as either True or False:

© Department of Computer Science, DPS R.K.Puram, New Delhi


Operator Meaning Example
== Equal to x == y
!= Not equal to x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Operators - Logical 47

Python Logical Operators are used to operate upon Boolean Values and return a

© Department of Computer Science, DPS R.K.Puram, New Delhi


single result as either True or False:

Operator Meaning Example


and Returns True only if both x < 5 and x < 10
statements are true
or Returns True if at least one of x < 6 or x < 4
the statements is true
not Reverse the result, returns False not(x < 5 and x < 10)
if the result is true
Operators - Assignment and Augmented 48

Assignment and Augmented (Arithmetic Assignment) operators are used to assign values to variables:

© Department of Computer Science, DPS R.K.Puram, New Delhi


Sno Operator Example Equivalent Meaning
1 = x = 5 x is assigned value 5
2 += x += 5 x=x+5 x is incremented by 5
3 -= x -= 5 x=x-5 x is decremented by 5
4 *= x *= 5 x=x*5 x is assigned product of last value of
x and 5
Operators - Assignment and Augmented 49

Assignment and Augmented (Arithmetic Assignment) operators are used to assign values to variables:

© Department of Computer Science, DPS R.K.Puram, New Delhi


Sno Operator Example Equivalent Meaning
5 /= x /= 5 x=x/5 x is assigned quotient of last value of
x divided by 5
6 %= x %= 5 x=x%5 x is assigned remainder of last value of
x divided by 5
7 //= x //= 5 x=x//5 x is assigned floor division of last value of
x divided by 5
8 **= x **= 5 x=x**5 x is assigned last value of x to the
power 5
Python Statements 50

Instructions that a Python interpreter can execute are called statements. For example:

© Department of Computer Science, DPS R.K.Puram, New Delhi


x = 1
y = 2 + 4 + 6 + 8 + 10 + 12 These independent statements assign
values to variables named x and y.
Multi-line statements
In Python, end of a statement is marked by a newline character (by pressing the enter key).
However, a statement can be extended over multiple lines with the line continuation character
(\). For example:
y = 2 + 4+ \
6 + 8 + \
10 + 12 These 3 lines are equivalent to the
print(y) single line statement
y = 2 + 4 + 6 + 8 + 10 + 12
Python Statements 51

Different statements are generally written in different lines, example:

© Department of Computer Science, DPS R.K.Puram, New Delhi


x = 1
y = 2
z = x + y

However, we can put multiple statements in a single line using semicolons, as


follows:
x = 1; y = 2; z = x + y
Assigning Multiple Variables 52

Assigning multiple values to multiple variables

© Department of Computer Science, DPS R.K.Puram, New Delhi


Multiple variables can be assigned values using a single Python assignment
statement as follows:

x, y, z = 15, 95.5, "Welcome" The code assigns 15 to x, 95.5 to y


and "Welcome" to z

Assigning same value to multiple variables


Multiple variables can be assigned the same value using a single Python assignment
statement as follows:
The code assigns the value 15 to the
x = y = z = 15
three variables x, y and z.
print() with escape sequence 53

Escape Sequence Description

© Department of Computer Science, DPS R.K.Puram, New Delhi


\n Newline character
\\ To print backslash
\t To use a horizontal tab
\' OR \" To print a single quote or double quote

Python
print("Hello\nFriends") Hello
code
print('We aren\'t afraid') Friends
print("Just \t tabbed") We aren't afraid
print("My Car __/===\\__") Just tabbed
Output My Car __/===\__
print(" 'O O'")
'O O'
print() - Displaying outputs 54

The print() function prints the specified message to the screen. The message can

© Department of Computer Science, DPS R.K.Puram, New Delhi


be a declared and initialized variable, any literal, or the result of any operation.
Example:

print('Hello World') Python Hello World


code
print("Double quotes") Double quotes
print('concatena'+'tion') concatenation
print('hello','there') hello there
print('I\'m 5') I'm 5
print("I'm 5") Output I'm 5
print('He said "hi"') He said "hi"
print() - Displaying outputs 55

© Department of Computer Science, DPS R.K.Puram, New Delhi


print(23==23,45==34) True False
print("Hello"=="Bye","Bye"=="Bye") False True
print(43>23,43<23) True False
print("AB">"AC","AB"<"AC") Python False True
print(51<=51,51<=54) code True True
print("51"<"533")
print(50>34 and 52<90) True
print(50>34 and 52>90) True
print(65>34 or 52<90,50<34 or False
52>90) True False
print(not("Morning"=="Evening")) Output True
print(not(25>35)) True
Syntax of Python print() 56

print(object(s), sep = <separator>, end = <end>)

© Department of Computer Science, DPS R.K.Puram, New Delhi


PARAMETERS

Parameter Description
object(s) Any object (variable/literal/calculation). If there are
multiple objects, they may be separated by comma.

sep=<separator> Optional. Used to specify what character to be used


to separate multiple objects to be printed with a
single print(). Default is space ' '
end=<end> Optional. Used to specify what character should be
printed at the end. Default is '\n' (line feed)
print() - Examples 57

© Department of Computer Science, DPS R.K.Puram, New Delhi


print ('Hello', 'World') Hello World

print ('Hello', 'World', sep = '#') Hello#World

print ('Hello') Hello

print ('World') World

print ('Hello',end = '')


print ('World') HelloWorld
Taking user input 58

Programmers often need to interact with users to get data for processing. Python

© Department of Computer Science, DPS R.K.Puram, New Delhi


provides us with the inbuilt function input() to take a user input for any data. The
value entered by the user is returned back by the input() as a string.

Syntax:
<Var>=input( <prompt> )

Parameter Description
prompt A String, representing a default message before the input.
Taking user input 59

The input() in Python works as follows:

© Department of Computer Science, DPS R.K.Puram, New Delhi


● When input() function executes the program flow stops until the user has
given an input.
● The prompt is displayed on the output screen to ask a user to enter input
value (However, the prompt, to be printed on the screen is optional with
input()).
● The user input value is accepted as a string and returned back by the input().
Even a number entered with input() is treated as a string. Thus to input a
number as an integer or a float value, an explicit conversion is needed from
string to an int or float respectively.
Taking user input 60

FirstName= input('First Name:')

© Department of Computer Science, DPS R.K.Puram, New Delhi


LastName = input('Last Name:') Python
FullName = FirstName+" "+LastName code
print('Good Day',FullName,sep="!")

for user Inputs as First Name:Priya


Priya and Sahay Last Name:Sahay
Output → Good Day!Priya Sahay
Taking user input 61

N = int(input('Number:')) By default, input takes string,

© Department of Computer Science, DPS R.K.Puram, New Delhi


C = input("Pattern Character:") so, we need convert it into
integer to treat it as a number
print(N,C*N)
print("7 Times",N,"=",7*N) Python
code

for user Inputs as Number:9


9 and * Pattern Character:*
Output → 9 *********
7 Times 9 = 63
Taking user input 62

E = float(input('English:')) By default, input takes string,

© Department of Computer Science, DPS R.K.Puram, New Delhi


M = float(input('Maths:')) so, we need convert it into
float to treat it as a number
AVG = (E+M)/2
print("Average Marks:",AVG) Python
code

English:65
for user Inputs as Maths:85
65 and 85
Average Marks: 75.0
Output →
Taking user input 63

P = float(input('Principal:')) By default, input takes string,

© Department of Computer Science, DPS R.K.Puram, New Delhi


R = float(input('Rate:')) so, we need convert it into
T = float(input('Time:')) float to treat it as a number
SI = P*R*T/100
print("Simple Interest:",SI)
Python
code

Principal:7000
for user Inputs as Rate:10
7000,10 and 5
Time:5
Output →
Simple Interest: 3500.0
While conversion, keep the following in mind 64

While converting the input data to

© Department of Computer Science, DPS R.K.Puram, New Delhi


P = float(input('Principal:'))
R = float(input('Rate:')) int or float, remember - if we enter
T = float(input('Time:')) string, it will raise an exception.
SI = P*R*T/100 The program will not execute
print("Simple Interest:",SI) further.

Principal:7000
Rate:10
Time:Good Time
----------------------------------------------
ValueError: could not convert string to float: 'Good Time'
Simplicity of Instructions 65

You do not write programs for executing it once by the computer, you need to

© Department of Computer Science, DPS R.K.Puram, New Delhi


write clear instructions so that any whosoever reads the program later (even
you yourself!!) should be able to understand.

It is very common for programmers not to understand the logic of their own
programs after some time. Maintenance and Modification of such programs
would be very difficult.

A=float(input("A:")) P=float(input("P:"))
B=float(input("B:")) R=float(input("R:"))
C=float(input("C:")) T=float(input("T:"))
D=A*B*C/100 SI=P*R*T/100
print(D) print(SI)
Simplicity of Instructions 66

Writing simple instructions helps in avoiding this problem. Some Tips are as

© Department of Computer Science, DPS R.K.Puram, New Delhi


follows:
● Avoid clever instructions.
● One instruction per task
● Use standards − Every language has its standards, follow them
● Use appropriate comments

S=float(input("Sal:"))
IH=S+S*(30/100)+S*(10/100)
print(IH) Sal=float(input("Sal:"))
DA=Sal*(30/100)
Tax=Sal*(10/100)
InHand=Sal+DA-Tax
print(InHand)
Clarity & Simplification of expression 67

Expression in a program is a sequence of operators and operands to do an


arithmetic or logical computation.

© Department of Computer Science, DPS R.K.Puram, New Delhi


Some examples of valid expressions:
● Assigning a value to a variable
● Arithmetic calculations using one or more variables
● Comparing two values

Writing non-ambiguous expressions is a skill that must be developed by every


programmer.
Here are some points to be kept in mind while writing such expressions
● Avoid expressions which may give ambiguous results
● Avoid complex expressions

Keep the names of the variables simple, short and yet meaningful
Errors in a program 68

● Error/Bug: Any malfunction, which either “stops the normal

© Department of Computer Science, DPS R.K.Puram, New Delhi


compilation/execution of the program” OR “program execution with wrong
results” is known as an error/bug in the program. Removal of Bug from a
program is known as debugging.

● Syntax Error: Syntax error, also known as parsing error, is the most common
kind of error in the program, which occurs due to wrong use of syntax of the
language. The process of translation of the script to be understood by the
system is known as parsing. The parser stops translation at the offending line
(line with wrong syntax) and displays a little ‘arrow’ pointing at the earliest
point in the line where the error was detected.
Syntax Errors - Examples 69

Code with Error Message Corrected Code

© Department of Computer Science, DPS R.K.Puram, New Delhi


23=A SyntaxError:can't assign to A=23
literal
A=90,B=100 SyntaxError: can't assign to A=90;B=100
literal
print("Hello")) SyntaxError: unmatched ')' print("Hello")
City="Mumbai' SyntaxError: EOL while City="Mumbai"
scanning string literal
A=10 SyntaxError: unexpected A=10
B=20 indent B=20
print(A+B) print(A+B)
Logical Errors 70

These errors occur due to wrong use of formula or expression by the programmer.

© Department of Computer Science, DPS R.K.Puram, New Delhi


Due to this, the program produces wrong results while execution.
Example of Logical Error:

If following statement is written by the If following statement is written by


programmer to calculate Average marks of the programmer to calculate Area of
three subjects, it is a Logical error. rectangle, it is a Logical error.
Avg=English + Maths + Science / 3 Area = Length + Breadth

Correct Code after removal of Logical Error Correct Code after removal of Logical
Avg=(English + Maths + Science)/3 Error
Area = Length * Breadth
Run-time Errors/Exceptions 71

Run-Time/Execution-Time Error: These errors are encountered during execution of

© Department of Computer Science, DPS R.K.Puram, New Delhi


the program due to unexpected input or output or calculation.
Example of Run-Time/Execution-Time Error/Exceptions

A=int(input("Numerator"))
B=int(input("Denominator"))
C=A/B;
print(C)
The program shown above will The program shown above will throw an
throw an Exception Exception (ValueError), if user enters a
(ZeroDivisionError), if user non numeric value for example Hello for
enters 0 for the variable B. any of the variables A or B.
72

© Department of Computer Science, DPS R.K.Puram, New Delhi


Thank you!
Department of Computer Science
Delhi Public School R.K.Puram New Delhi

You might also like