0% found this document useful (0 votes)
4 views30 pages

Python Module-1

Module-1 introduces Python as a high-level, general-purpose programming language designed for ease of use and integration. It covers the features of Python, the importance of programming, basic computer hardware architecture, and the foundational concepts of programming such as variables, expressions, and control structures. Additionally, it discusses Python IDEs, the process of writing and running programs, and common types of errors encountered in programming.

Uploaded by

jotise9094
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views30 pages

Python Module-1

Module-1 introduces Python as a high-level, general-purpose programming language designed for ease of use and integration. It covers the features of Python, the importance of programming, basic computer hardware architecture, and the foundational concepts of programming such as variables, expressions, and control structures. Additionally, it discusses Python IDEs, the process of writing and running programs, and common types of errors encountered in programming.

Uploaded by

jotise9094
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module-1 Introduction to Python

Module-1: Why should you learn to write programs, Variables expressions and
statements, Conditional execution, Functions.

Introduction to Python
 Python is a widely used general-purpose, high level programming language.
 It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation.
 Python is a object oriented programming language that lets you work quickly and integrate systems more
efficiently

Features of Python
 Simple

o Python is a simple and minimalistic language in nature


o Reading a good python program should be like reading English
o Its Pseudo-code nature allows one to concentrate on the problem rather than the language

 Easy to Learn

 Free & Open source

o Freely distributed and Open source

o Maintained by the Python community

 High Level Language –memory management

 Portable – runs on anything

 Interpreted

o You run the program straight from the source code.


o Python program Bytecode a platforms native language
o You can just copy your code to another system and it will automatically work with python
platform

 It supports Object-Oriented programming concepts

 Simple and additionally supports procedural programming and supports extensive libraries for
machine learning and Artificial intelligence concepts

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 1


Module-1 Introduction to Python
Python IDE’s
 Anaconda
 Pycharm
 Eclipse+Pydev
 Spyder

1: Why should you Learn write programs


 Programming is a very creative and rewarding activity. You can write programs for many reasons,
ranging from making your living to solving a difficult data analysis problem to having fun to helping
someone else solve a problem.
 We are surrounded in our daily lives with computers ranging from laptops to cell phones. We can
think of these computers as our “personal assistants” who can take care of many things on our behalf.
The hardware in our current-day computers is essentially built to continuously ask us the question,
“What would you like me to do next? Programmers add an operating system and a set of applications
to the hardware and we end up with a Personal Digital Assistant that is quite helpful and capable of
helping us do many different things.
 Human beings are able to read and understand the words in a few seconds, counting them are almost
painful because it is not the kind of problem that human minds are designed to solve. For a computer
the opposite is true, reading and understanding text from a piece of paper is hard for a computer to do
but ,counting the words and telling you how many times the most used word was used is very easy for
the computer. Hence, computer is acts as a personal assistance to perform task.

 The programmers must choose various programming languages to solve the complexity of the
program.

1.1 Creativity and motivation


Building useful, elegant, and clever programs for others to use is a very creative activity. Your computer
or Personal Digital Assistant (PDA) usually contains many different programs from many different groups of
programmers, each competing for your attention and interest. They try their best to meet your needs and give
you a great user experience in the process. In some situations, when you choose a piece of software, the
programmers are directly compensated because of your choice.
Our primary motivation is not to make money or please end users, but instead for us to be more productive
in handling the data and information that we will encounter in our lives. When you first start, you will be both

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 2


Module-1 Introduction to Python
the programmer and the end user of your programs. As you gain skill as a programmer and programming feels
more creative to you, your thoughts may turn toward developing programs for others.
1.2 Computer hardware architecture
To understand the art programming, it is better to know the basic architecture of computer [Link]
computer system involves some of the important parts as shown in Figure: [Link] parts are as explained
below:
 Central Processing Unit (CPU): It performs basic arithmetic, logical, control and I/O operations
specified by the program instructions. CPU will perform the given tasks with a tremendous speed.
Hence, the good programmer has to keep the CPU busy by providing enough tasks to it.
 Main Memory: It is the storage area to which the CPU has a direct access. Usually, the programs
stored in the secondary storage are brought into main memory before the execution. The processor
(CPU) will pick a job from the main memory and performs the tasks. Usually, information stored in
the main memory will be vanished when the computer is turned-off.
 The Secondary Memory: It is also used to store information, but it is much slower than the main
memory. The advantage of the secondary memory is that it can store information even when there is
no power to the computer. Examples of secondary memory are disk drives or flash memory (typically
found in USB sticks and portable music players).
 Input/ Output Devices: These are the medium of communication between the user and the computer.
Keyboard, mouse, monitor, printer etc. are the examples of I/O devices.
 Network Connection: Nowadays, most of the computers are connected to network and hence they
can communicate with other computers in a network. Retrieving the information from other computers
via network will be slower compared to accessing the secondary memory. Moreover, network is not
reliable always due to problem in connection.

Figure 1.1: Computer Hardware Architecture

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 3


Module-1 Introduction to Python
As a programmer, your job is to use and orchestrate each of these resources to solve the problem that you need
to solve and analyze the data you get from the solution. As a programmer you will mostly be “talking” to the
CPU and telling it what to do next.
Sometimes you will tell the CPU to use the main memory, secondary memory, network, or the input/output
devices.

1.3 Understanding programming


Programmers must have the skills to look at a data/information analysis problem and develop a program to
solve the problem.

In a sense, you need two skills to be a programmer:


• First, you need to know the programming language (Python) – Programmer should know the vocabulary
and the grammar. You need to be able to spell the words in this new language properly and know how to
construct well-formed “sentences” in this new language.
• Second, you need to “tell a story” -While writing a story, programmer should combine words and
sentences to convey an idea to the reader. There is a skill and art in constructing the story and skill in story
writing is improved by doing some writing and getting some feedback.

1.4 Words and sentences

Python vocabulary is actually pretty small. We call this “vocabulary” the “reserved words”. These are
words that have very special meaning to Python. When Python sees these words in a Python program, they
have one and only one meaning to [Link] reserved words in the language where humans talk to Python is
shown in table 1.1

Table 1.1: Keywords in python

And As assert break class continue Finally from

Def Del Elif else except false for global

If Import Is lambda none nonlocal not or

Yield With while try true return raise pass

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 4


Module-1 Introduction to Python
1.5 Python Editors and Installing Python/Conversing with Python
A step to install python is as follows:
 Python is freely downloadable from the internet. There are multiple IDEs (Integrated Development
Environment) available for working with Python. Some of them are PyCharm, LiClipse, IDLE etc.
When you install Python, the IDLE editor will be available automatically. The basic Python can be
downloaded from the link:
[Link]
 Apart from all these editors, Python program can be run on command prompt also. One has to install
suitable IDE depending on their need and the Operating System they are using. Because, there are
separate set of editors (IDE) available for different OS like Window, UNIX, Ubuntu, Soloaris, Mac,
etc.
 Once Python is installed, one can go ahead with working with Python. Use the IDE of your choice for
doing programs in Python.
 After installing Python, If you would like to use the default IDE of Python, that is, the IDLE, then you
can just run IDLE and you will get the editor as shown in Figure 1.2. The prompt >>> (usually called
as chevron) indicates the system is ready to take Python instructions.

Figure 1.2: Python IDLE editor


Once we are done with the program, we can close or terminate Python by giving quit() command as shown –
>>> quit()
Step 2: Using IDLE is very similar to using a text editor. Under File, select New file or press Ctrl + N. That will bring
up a new window titled, “Untitled”.

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 5


Module-1 Introduction to Python

Print the message and Save the file as [Link]

Run the file : goto RunRun module

Output:

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 6


Module-1 Introduction to Python

1.6 Terminology: Interpreter and Compiler


Python is a high-level language intended to be relatively straightforward for humans
to read and write and for computers to read and process. Other high-level languages include Java, C++, PHP,
Ruby, Basic, Perl, JavaScript, and many more.
The actual hardware inside the Central Processing Unit (CPU) does not understand any of these high-level
languages. The CPU understands a language we call machine language. Machine language is very simple and
frankly very tiresome to write because it is represented all in zeros and ones.
The programs written in high level languages are then translated to machine level instruction so as to be
executed by CPU. How this translation behaves depending on the type of translators viz. compilers and
interpreters.
 A compiler translates the source code of high-level programming language into machine level
language. For this purpose, the source code must be a complete program stored in a file (with
extension,.java, .c, .cpp etc). The compiler generates executable files (usually with extensions .exe, .dll
etc) that are in machine language. Later, these executable files are executed to give the output of the
program.
 Interpreter performs the instructions directly, without requiring them to be pre-compiled. Interpreter
parses (syntactic analysis) the source code ant interprets it immediately. Hence, every line of code can
generate the output immediately, and the source code as a complete set, need not be stored in a file.
Example to print the message:
>>> print("welcome to python")
welcome to python

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 7


Module-1 Introduction to Python
1.7 Writing a Program

As Python is interpreted language, one can keep typing every line of code one after the other (and
immediately getting the output of each line) as shown in previous section. But, in real-time scenario, typing a
big program is not a good idea. It is not easy to logically debug such lines. Hence, Python programs can be
stored in a file with extension .py and then can be run. Programs written within a file are obviously reusable
and can be run whenever we want. Also, they are transferrable from one machine to other machine via pen-
drive, CD etc.

1.8 What is a program?

The definition of a program at its most basic is a sequence of Python statements that have been crafted to do
something. Even our simple [Link] script is a program.
It might be easiest to understand what a program is by thinking about a problem that a program might be built
to solve, and then looking at a program that would solve that problem.
For example, look at the following text about a clown and a car.
Look at the text and figure out the most common word and how many times it occurs.

the clown ran after the car and the car ran into the tent
and the tent fell down on the clown and the car

Then imagine that if the programmer is doing this task looking at millions of lines of text it would become a
difficult task. So it is quicker to learn Python and write a Python program to count the words than it would
and the tent fell down on the clown and the car
become to easy to perform task. Python is a way for us to exchange useful instruction sequences (i.e.,
programs) in a common language that can be used by anyone who installs Python on their computer. So
neither of us are talking to Python, instead we are communicating with each other through Python.
Demonstrating simple python program for addition of two numbers,

#addition of two numbers


[Link]
x=10
y=20
z=x+y
print(z)
Output
>>>30

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 8


Module-1 Introduction to Python
1.9 The building blocks of programs
The building blocks of python programming language is as follows. These building blocks are not only
applicable for python it is also applicable for all programming languages.
 Input: Get data from the “outside world”. This might be reading data from a file, or even some kind of
sensor like a microphone or GPS. In our initial programs, our input will come from the user typing
data on the keyboard.
 Output: Display the results of the program on a screen or store them in a file or perhaps write them to
a device like a speaker to play music or speak text.
 Sequential execution: Perform statements one after another in the order they are encountered in the
script.
 Conditional execution: Check for certain conditions and then execute or skip a sequence of
statements.
 Repeated execution: Perform some set of statements repeatedly, usually with some variation.

 Reuse: Write a set of instructions once and give them a name and then reuse those instructions as
needed throughout your program.

1.10 What could possibly go wrong?

As your programs become increasingly sophisticated, you will encounter three general types of errors:
 Syntax errors: A syntax error means that programmer had violated the “grammar” rules of Python.
Python is case–sensitive [Link],there may be chance of grammatical error while typing the
program. Example: >>> primt 'Hello'
SyntaxError: invalid
syntax
 It is responsibility of programmer to take of such errors in coding. So the line and character that
SyntaxError:
Python indicates invalid
in a syntax errorsyntax
may just be a starting point for your
investigation.
 Logic errors: A logic error is when your program has good syntax but there is a mistake in the order
of the statements or perhaps a mistake in how the statements relate to one another. Logical errors cause
the program to behave incorrectly, but they do not usually crash the program. Unlike a program with
syntax errors, a program with logic errors can be run, but it does not operate as intended.
 Semantic errors: A semantic error is when your description of the steps to take is syntactically perfect
and in the right order, but there is simply a mistake in the program. The program is perfectly correct
but it does not do what you intended for it to do.

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 9


Module-1 Introduction to Python

//Program to display logical error


x = 9.0
y = 3.0
z = x+y/2
print ('The average of the two numbers you have entered is:', z)
Output
The average of the two numbers you have entered is: 10.5

2. Variables
A variable is a name that refers to a value. An assignment statement creates new variables and gives them
values. In python, a variable need not be declared with a specific type before its usage. Whenever you want a
variable, just use it. The type of it will be decided by the value assigned to it.
2.1 Values and Types
A value is one of the basic things a program works with, like a letter or a number.
Consider an example, It consists of integer and strings,
>>> print(4)
4
>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.1415926535897931

The above example makes three assignments.


 The first assigns a string to a new variable named message.
 The second assigns the integer 17 to n
 The third assigns the (approximate) value of _ to pi.
To display the value of a variable, you can use a print statement:
>>> print(n)
17
>>> print(pi)
3.141592653589793
The type of a variable is the type of the value it refers to above example
>>> type(message)
<class 'str'> #type refers to string
>>> type(n)
Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 10
Module-1 Introduction to Python
<class 'int'> #type refers to integer
>>> type(pi)
<class 'float'> #type refers to float

2.3 Variable names and keywords


 Variable names can be arbitrarily long. They can contain both letters and numbers, but they cannot
start with a number. It is legal to use uppercase letters, but it is a good idea to begin variable names
with a lowercase letter. The underscore character (_) can appear in a name.
 It is often used in names with multiple words, such as my_name or airspeed_of_unladen_swallow.
 Variable names can start with an underscore character, but we generally avoid doing this unless we are
writing library code for others to use.
 Consider an example for variable declaration,
If you give a variable an illegal name, you get a syntax error:
>>> 76trombones = 'big parade'
SyntaxError: invalid syntax
>>> more@ = 1000000
SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical Zymurgy'
SyntaxError: invalid syntax
 76trombones is illegal because it begins with a number.
 more@ is illegal because it contains an illegal character, @.
 But what‟s wrong with class? It turns out that class is one of Python‟s keywords. The interpreter uses
keywords to recognize the structure of the program, and they cannot be used as variable names.
 As Python is case-sensitive, variable name karthik is different from KARTHIK etc.
Python reserves 33 keywords:
and a and del from None True def lambda
as elif global nonlocal Try raise return
assert else if not While finally
break except import or with is
class False in pass yield continue

2.4 Statements
A statement is a unit of code that the Python interpreter can execute. We have seen two kinds of statements:
print being an expression statement and assignment statement
Following are the examples of statements –
Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 11
Module-1 Introduction to Python
>>> print("Hello") #printing statement
Hello
>>> x=5 #assignment statement
>>> print(x) #printing statement
2.5 Operators and operands
 Operators are special symbols that represent computations like addition and multiplication. The values the
operator is applied to are called operands.
 The operators +, -, *, /, and ** perform addition, subtraction, multiplication, division, and exponentiation,
as in the following Table 1.2:
 Now, += is compound assignment operator
>>> x=3
>>> y=6
>>> x+=y #x=x+y
>>> print(x)
9
Table 1.2 Arithmetic Operators
Operator Meaning Example
+ Addition Sum= a+b
- Subtraction Diff= a-b
/ Division a=4 ,b=3
A=a/b
A = 4/3
(A will get a value 1.3333333)
// Floor Division – returns F = a//b
only integral part after A= 4//3 (X will get a value 1
division
% Modulus – remainder after A= a %b
Division (Remainder after dividing a by b)

** Exponent E = x** y
(means x to the powder of y)
2.6 Expressions
An expression is a combination of values, variables, and operators. A value all by itself is considered
an expression, and so is a variable, so the following are all legal expressions. If you type an expression in
interactive mode, the interpreter evaluates it and displays the result:
>>> x=5
>>> x+1
6
Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 12
Module-1 Introduction to Python
2.7 Order of operations
When more than one operator appears in an expression, the order of evaluation depends on the rules of
precedence. For mathematical operators, Python follows mathematical convention.
The acronym PEMDAS is a useful way to remember the rules:
 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. You can also use parentheses to make an expression easier to read, as in (minute * 100) /60, even if
it doesn‟t change the result.
 Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is 3, 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 is 5, not 4, and 6+4/2 is 8.0, not 5.
 Operators with the same precedence are evaluated from left to right. So the expression 5-3-1 is 1, not
3, because the 5-3 happens first and then 1 is subtracted from 2.
2.8 Modulus operator
The modulus operator works on integers and yields the remainder when the first operand is divided by the
second.
In Python, the modulus operator is a percent sign (%).
The syntax is the same as for other operators:
>>> quotient = 7 // 3
>>> print(quotient)
2
>>> remainder = 7 % 3
>>> print(remainder)
1
So 7 divided by 3 is 2 with 1 left over.
2.9 String operations
The + operator works with strings, but it is not addition in the mathematical sense. Instead it performs
concatenation, which means joining the strings by linking them end to end.
For example:
Example1 Example2
>>> first = 10 >>> first = '100'
>>> second = 15 >>> second = '150'
>>> print(first+second) >>> print(first + second)
25 100150
The output of this program is 100150
Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 13
Module-1 Introduction to Python
2.10 Asking the user for input
Python provides a built-in function called input that gets input from the keyboard. When this function is
called, the program stops and waits for the user to type something. When the user presses Return or Enter, the
program resumes and input returns what the user typed as a string.
For example,
>>> inp = input()
Welcome to world of python
>>> print(inp)
Welcome to world of python
 It is a good idea to print a prompt telling the user what to input. You can pass a string to input to be
displayed to the user before pausing for input:
>>> name = input('What is your name?\n')
What is your name?
Fred
>>> print(name)
Fred
 The sequence \n at the end of the prompt represents a newline, which is a special character that causes a
line break. That‟s why the user‟s input appears below the prompt.
 If you expect the user to type an integer, you can try to convert the return value to int using the int()
function:
Example1:
>>> prompt = 'How many days in a week?\n'
>>> days = input(prompt)
'How many days in a week?
7
>>> type(prompt)
<class 'str'> #type is string

Example 2:
>>> x=int(input('enter number\n'))
enter number
12
>>> type(x)
<class 'int'> #type is string

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 14


Module-1 Introduction to Python
2.11 Comments
Comments are most useful when they document non-obvious features of the code. It is reasonable to
assume that the reader can figure out what the code does; it is much more useful to explain why.
Ex1. #This is a single-line comment
Ex2. ''' This is a
multiline
comment '''

2.12 Choosing mnemonic variable names


Consider the following example,
Program1: Program2:
a = 35.0 hours = 35.0
b = 12.50 rate = 12.50
c=a*b pay = hours * rate
print(c) print(pay)

 The Python interpreter sees above of these programs as exactly the same but humans see and understand
these programs quite differently. Humans will most quickly understand the intent of the second program
because the programme has chosen variable names that reflect their intent regarding what data will be
stored in each variable.
 We call these wisely chosen variable names “mnemonic variable names”. The word mnemonic means
“memory aid”. We choose mnemonic variable names to help us remember why we created the variable in
the first place.

2.13 Debugging
Some of the errors are common in python programming language. Even though it is correct but difficult
understand the syntax. Few of the examples are
Ex1 : >>> bad name = 5
SyntaxError: invalid syntax
#variable name should not define with space

Ex2: >>> month=09


SyntaxError: invalid token
#Python does not allow preceding zeros for numeric values.

Ex3: >>> principal=327.68

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 15


Module-1 Introduction to Python
>>> interest=principle*rate
NameError: name 'principle' is not defined
Pyhton is case- sensitive, so variable principle is different from prinicipal.

[Link] Execution
3.1 Boolean expressions
 A boolean expression is an expression that is either true or false. The following examples use the operator
= =, which compares two operands and produces True if they are equal and False otherwise:
>>> 5 == 5
True
>>> 5 == 6
False
 True and False are special values that belong to the class bool; they are not strings:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
 The = = operator is one of the comparison operators; the others are
Table 1.3: Comparison operator
Statement Comments Example
X!=Y # X is not equal to Y If x=5 , y=6
>>> x!=y
False
X>Y # X is greater than Y >>> x > y
False
X<Y # X is less than Y >>> x < y
False
X>=Y # X is greater than or equal to Y >>> x > =y
False
X<=Y # X is less than or equal to Y >>> x < =y
False
X is Y # X is the same as Y >>> x is y
False
X is not Y # X is not the same as Y >>> x is not y
True

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 16


Module-1 Introduction to Python
3.2 Logical operators
There are three logical operators: and, or, and not. The semantics (meaning) of these operators is similar to their
meaning in English.
Table 1.4 : Logical operators
Operators Statement Comments Example
And x> 0 and x<10 Is true only if x is greater Ex1 :>>> x=5
than 0 and less than10 >>> x>0 and x<10
True
Ex2: >>> x= -5
>>> x>0 and x<10
False
Or n%2 ==0 or n%3==0 Is true only if either >>> n=2
condition is true >>>n%2==0 or n%3==0
True
Not not(x>y) negates Boolean >>> x=5
expression >>> x> 0 and x<10
True
>>> not x
False
 Logical operators treat the operands as Boolean (True or False).
 Python treats any non-zero number as True and zero as False.
>>> Ex: 17 and True
True
# Example1 (Boolean Operands)
>>> a= True
>>> b= False
>>> print('a and b is :', a and b)
a and b is : False
>>> print('a or b is :', a or b)
a or b is : True
>>> print('Complement of a is : ', not a)
Complement of a is False

3.3 Conditional execution


A conditional statement gives the developer to ability to check conditions and change the behavior of the
program accordingly. The simplest form is the if statement:
1) if statement:
Syntax,
if condition:
statements

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 17


Module-1 Introduction to Python
 The boolean expression after the if statement is called the condition. We end the if statement with a colon
character (:) and the line(s) after the if statement are indented is as shown in figure 1.2.
 The statement consists of a header line that ends with the colon character (:) followed by an indented
block. Statements like this are called compound statements because they stretch across more than one line.
 If the logical condition is true, then the statement gets executed. If the logical condition is false, the
indented statement is skipped.
Example:
x=1
if x>0:
print("positive number") #one tab indentation

Output: Fig 1.2 : If Logic


positive number
3.4 Alternative execution
A second form of the if statement is alternative execution, in which there are two possibilities and the
condition determines which one gets executed is as shown in Figure 1.3
The syntax looks like this:
Syntax,
if condition :
statements
else :
statements

Figure 1.3: if-Then-Else Logic

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 18


Module-1 Introduction to Python
Example,
x=6
if x%2 == 0:
print('x is even')
else :
print('x is odd')

3.5 Chained conditionals


If there are more than two possibilities and we need more than two branches. One way to express a
computation like that is a chained conditional. elif is an abbreviation of “else if.” Again, exactly one branch
will be executed is as shown in figure 1.4

Figure 1.4: If-Then-ElseIf Logic

Example

Syntax, Example
if condition1: x=1
Statement y=6
elif condition2: if x < y:
Statement print('x is less than y')
........| elif x > y:
elif condition_n: print('x is greater than y')
Statement else:
else: print('x and y are equal')
Statement
Output:
X is less than y

3.6 Nested Conditions


The conditional statements can be nested. That is, one set of conditional statements can be nested
inside the other. We could have written the three-branch example like this. The outer conditional contains two
branches.

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 19


Module-1 Introduction to Python
The first branch contains a simple statement. The second branch contains another if statement, which
has two branches of its own. Those two branches are both simple statements, although they could have been
conditional statements as well is as shown in figure [Link] conditionals make the code difficult to read,
even though there are proper
indentations. Hence, it is advised to use logical operators like and to simplify the nested conditionals.

Figure 1.5: Nested If Statements

Example
x=3
y=4
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')
//Output:
x is less than y

3.7 Catching exceptions using try and except


There is a chance of runtime error while executing some program. One of the possible reasons is wrong input.
For example, consider the following code segment –
Example1
a=int(input("Enter a:"))
b=int(input("Enter b:"))

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 20


Module-1 Introduction to Python
c=a/b
print(c)
Output
When we run the above code with zero, we may get possible error
Enter a: 5
Enter b: 0
Traceback (most recent call last):
File "F:/Python-EC2018/Pythonprograms/[Link]", line 3, in <module>
c=a/b
ZeroDivisionError: division by zero

 There is a conditional execution structure built into Python to handle these types of expected and
unexpected errors called “try / except”.

 The idea of try and except is that you know that some sequence of instruction(s) may have a problem
and you want to add some statements to be executed if an error occurs. These extra statements (the
except block) are ignored if there is no error.

 We can re -write the above code using try-except


Example
a=int(input("Enter a:"))
b=int(input("Enter b:"))
try:
c=a/b
print(c)
except:
print("Divisible by 0 is not possible")

Output
Enter a: 5
Enter b: 0
Divisible by 0 is not possible
3.8 Short-circuit evaluation of logical expression
Consider an example of x=1,When Python is processing a logical expression such as x >= 2 and (x/y)
> 2, it evaluates the expression from left to right. Because of the definition of and, if x is less than 2, the

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 21


Module-1 Introduction to Python
expression x >= 2 is False and so the whole expression is False regardless of whether (x/y) > 2 evaluates to
True or False.
 When Python detects that there is nothing to be gained by evaluating the rest of a logical expression, it
stops its evaluation and does not do the computations in the rest of the logical expression. When the
evaluation of a logical expression stops because the overall value is already known, it is called short-
circuiting the evaluation.
 When the first part of logical expression results in True, then the second part has to be evaluated to
know the overall result.
 The short-circuiting not only saves the computational time, but it also leads to a technique known as
guardian pattern.
Consider an example,
 The first example is true because both conditions are true.
 But the second example did not fail because the first part of the expression x >= 2 evaluated to False
so the (x/y) was not ever executed due to the short-circuit rule and there was no error .
 The third calculation failed because Python was evaluating (x/y) and y was zero,which causes a
runtime error.
Example1, Example 2 Example 3
>>> x = 1 >>> x = 6
>>> x = 6
>>> y = 0 >>> y = 0
>>> y = 2
>>> x >= 2 and (x/y) > 2 >>> x >= 2 and (x/y) > 2
>>> x >= 2 and (x/y) > 2
False Traceback (most recent call
True
last):
File "<stdin>", line 1, in
<module>
ZeroDivisionError: division by
zero
We can construct the logical expression to strategically place a guard evaluation just before the evaluation
that might cause an error as follows:
Consider an example,
Example 1: Example 2 Example 3
>>> x = 1 >>> x = 6 >>> x >= 2 and (x/y) > 2 and
>>> y = 0 >>> y = 0 y != 0
>>> x >= 2 and y != 0 and >>> x >= 2 and y != 0 and Traceback (most recent call
(x/y) > 2 (x/y) > 2 last):
False False File "<stdin>", line 1, in
<module>
ZeroDivisionError: division by
zero

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 22


Module-1 Introduction to Python
 In the first logical expression, x >= 2 is False so the evaluation stops at the and.
 In the second logical expression, x >= 2 is True but y != 0 is False so we never reach (x/y).
 In the third logical expression, the y!= 0 is after the (x/y) calculation so the expression fails with an
error.
 In the second expression, we say that y != 0 acts as a guard to insure that we only execute (x/y) if y is
non-zero.
4. Functions
 A function is a block or piece of code that performs a specific task in a program, which only runs
when it is called.
 You can pass data, known as parameters into a function. A function can return data as a result.
 In Python, all functions are treated as objects, so it is more flexible compared to other high-level
languages.

4.1 Functions calls


A sequence of instructions intended to perform a specific independent task is known as a function .When
we define a function we will give a valid name to it, and then specify the instructions for performing
required task. Then, whenever we want to do that task, a function is called by its name.
Consider an example,
>>> type(33)
<class 'int'>
 The name of the function is type. The expression in parenthesis is called the argument of the function.
The argument is a value or variable that we are passing into the function as input to the function. The
result, for the type function, is the type of the argument.
 It is common to say that a function “takes” an argument and “returns” a result. The result is called the
return value.
Function types
 Built in functions
 User defined functions

4.2 Built in functions


Python provides a number of important built in functions that we can use without needing to provide
the function definition
Syntax,
The general form of built-in functions:
«function_name» («arguments»)

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 23


Module-1 Introduction to Python
An argument is an expression that appears between the parentheses of a function call and each
argument is separated by comma
Table 1.5: Built in functions
Built –in- functions Syntax/Examples Comments
max( ) >>>max(„hello world‟) #display character
„w‟ having maximum
ASCII code
min( ) min(„hello world‟) #display least character
„„ having minimum ASCII
code
len( ) >>>len(„hello world‟) # display length of
11 string
round( ) >>>round(3.8) #round the value with
4 single parameter.
>>>round(3.3)
3
>>>round(3.5)
4
>>>round( 3.141592653, 2 ) #round the value with 2
3.14 parameters

pow() >>>pow(2,4) # 2^4


abs() >>>abs(-3.2) # returns the absolute
value of object

4.3 Type conversions functions


Python also provides built-in functions that convert values from one type to another.
Consider an example,
Table 1.6 : Type conversion functions
DataType Example comments
int() Ex1 >>> int('32') #integer value enclosed with
32 quotes can be easily converted
Ex2 >>> int('Hello')
into string.
ValueError: invalid literal for int() with
base 10: 'Hello' #string value enclosed within
Ex3 : >>>int(3.9999) single quotes cannot be
3
converted to integer
Ex4 : int(-2.3)
float() Ex1 : >>>float(32)
32
Ex2 : float(„3.124‟)
3.124

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 24


Module-1 Introduction to Python
str() Ex1 : >>> str(32)
32
Ex2 : >>> str(„3.124‟)
3.124
4.4 Random numbers
 Given the same inputs, most computer programs generate the same outputs every time, so they are said
to be deterministic. Determinism is usually a good thing, since we expect the same calculation to yield
the same result. For some applications, though, we want the computer to be unpredictable. Games are
an obvious example, but there are more.
 Making a program truly nondeterministic turns out to be not so easy, but there are ways to make it at
least seem nondeterministic. One of them is to use algorithms that generate pseudorandom numbers.
The function random returns a random float between 0.0 and 1.0 and for integer between (1 and 100
etc) .
o Consider an example; Python has a module random for the generation of random numbers.

Example , Output: This program produces the following list of


5 random numbers between 0.0 and up to but not
import random
including 1.0.
for i in range(10): 0.11132867921152356
x = [Link]() 0.5950949227890241
print(x) 0.04820265884996877
0.841003109276478
0.997914947094958

 The random function is only one of many functions that handle random numbers. The function
randint() takes the parameters low and high, and returns an integer between low and high (including
both).
Ex1 : >>> import random
>>> [Link](5,10)
10
Ex2 : >>> [Link](5,10)
10
>>> [Link](5,10)
7
 To choose an element from a sequence at random, you can use choice:
Ex1 : >>> t = [1, 2, 3]
>>> [Link](t)
2
>>> [Link](t)
3

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 25


Module-1 Introduction to Python
4.5 Math functions
 Python has a math module that provides most of the familiar mathematical functions. Before we can
use the module, we have to import it:
>>> import math
 This statement creates a module object named math. If you print the module object, you get some
information about it:
>>> print(math)
<module 'math' (built-in)>
Table 1.7: Math Functions
Examples Comments
>>> import math # Finds the square root of number
>>> [Link](3)
1.7320508075688772
>>> [Link](30) # Finds the sin of 30
-0.9880316240928618
>>> [Link](30) # Finds the cos of 30
0.15425144988758405
>>> print([Link]) # print the value of pi
3.141592653589793
>>> math.log10(2) # finds the logarithm base 10
0.3010299956639812
>>> [Link](2) #finds the log base e
0.6931471805599453

4.6 Adding new functions(definitions and uses)


We have only been using the functions that come with Python, but it is also possible to add new functions. A
function definition specifies the name of a new function and the sequence of statements that execute when the
function is called.
The syntax of user-defined function would be
def fname(Par_list) :
Statement1
Statement2
……………
Statement_n
return value
where,

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 26


Module-1 Introduction to Python
def  Keyword
fname  Name of the function
par_list  number of arguments passing to functions
Statement number of statements
return value  return the output value
o The rules for function names are the same as for variable names: letters, numbers and some
punctuation marks are legal, but the first character can‟t be a number. You can‟t use a keyword
as the name of a function, and you should avoid having a variable and a function with the same
name.
o The empty parentheses after the name indicate that this function doesn‟t take any arguments.
o The first line of the function definition is called the header; the rest is called the body. The
header has to end with a colon and the body has to be indented.
o By convention, the indentation is always four spaces. The body can contain any number of
statements.
Consider an example,
Example1
def simple():
print("hi")
print("welcome to world of python")
print("welcome to function")
simple() #function call

#Output
Welcome to function
hi
Welcome to world of python

 In the below program it consists of two functions definitions simple() and repeat_lyrics() Function
definitions get executed just like other statements, but the effect is to create function objects. The
statements inside the function do not get executed until the function is called, and the function definition
generates no output.
Example2
def simple():
print("hi")
print("welcome to world of python")
print("welcome to function")
def repeat_lyrics():
simple()

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 27


Module-1 Introduction to Python
simple()
repeat_lyrics()

Output
welcome to function
hi
welcome to world of python
hi
welcome to world of python

4.7 Flow of execution


 In order to ensure that a function is defined before its first use, you have to know the order in which
statements are executed, which is called the flow of execution.
 Execution always begins at the first statement of the program. Statements are executed one at a time, in
order from top to bottom.
 Function definitions do not alter the flow of execution of the program, but remember that statements inside
the function are not executed until the function is called.
 A function call is like a detour in the flow of execution. Instead of going to the next statement, the flow
jumps to the body of the function, executes all the statements there, and then comes back to pick up where
it left off.
 Python is good at keeping track of where it is, so each time a function completes, the program picks up
where it left off in the function that called [Link] it gets to the end of the program, it terminates .
4.8 Parameters and arguments
 A parameter is a variable defined by a method/function that receives a value when the method is called
 An argument is a value that is passed to a method when it is invoked.
Consider an example,
def example(a,b):
print("welcome to inside function")
print("arguments are ",a,b)
print(" printing elements are as follows")
x="Hello"
y=3
example(x,y)
print("done")

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 28


Module-1 Introduction to Python
In the above program a and b are parameter, x and y are called as arguments. The argument is being passed
when a function example() is invoked. The parameter receives the argument as an input and statements
inside the function are executed.
As Python variables are not belongs to particular data types in general, one can pass any type of value to the
function as an argument.
4.9 Fruitful functions and void functions
Some of the functions we are using, such as the math functions, yield results for lack of a better name, I call
them fruitful functions.
 The function which returns some result to the calling function after performing a task is known as
fruitful function. In the below example we are using return statement in our function. When this script
executes, the print statement will print out “6” because the addition function was called with 3 and 3 as
arguments.
Consider an example,
def addition(a,b): #function definition
sum=a + b
return sum
x=addition(3, 3) #function call
print("addition of 2 numbers")
print(x)
 When we are using built –in functions, yield results for them we named as fruitful functions.
>>>[Link](2)
1.7320508075688772
 The void function might display something on the screen or has some other effect. they perform an
action but they don‟t have return value
Consider an example
>>> result=print(Hello)
Hello
>>> print(result)
None
>>> print(type(None))
<class 'NoneType'>

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 29


Module-1 Introduction to Python
4.10 Why functions?
It may not be clear why it is worth the trouble to divide a program into functions. There are several reasons:
• Creating a new function gives you an opportunity to name a group of statements, which makes your program
easier to read, understand, and debug.
• Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only
have to make it in one place.
• Dividing a long program into functions allows you to debug the parts one at a time and then assemble them
into a working whole.
• Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse
it.

***********************************

Chethana H R, Mamatha Jajur, Asst Prof, Dept of CSE Page 30

You might also like