0% found this document useful (0 votes)
21 views51 pages

Module - 1-1

Uploaded by

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

Module - 1-1

Uploaded by

Sagarika.L
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Dept.

of CSE, NIEIT
Application Development
using Python
MODULE 1
• PYTHON BASICS
• FLOW CONTROL
• FUNCTIONS

Reference: Al Sweigart,“Automate the Boring Stuff with Python”,1st Edition.


INTRODUCTION

 It was created by Guido Van Rossum in 1991


and is currently one of the most popular
programming language.
 The name Python came from the British comedy
group - Monty Python.
 Python maintains two releases of Python namely
Python 2.x and Python 3.x. Python 2.x is
officially being discontinued from 01 Jan 2020.
 Python 3.8 is the latest version.
 File extension used is .py

Dept. of CSE, NIEIT


Why PYTHON?

Python is widely used even when it is somehow slower than other languages because:
 Easy to learn and code
 Free and high level language (easy to read)
 Portable
 Object Oriented
 Large collection of packages and modules
 Interpreted (each and every line can be executed directly without compiling the whole code)

Dept. of CSE, NIEIT


How to run a Python code?

 There are several ways to run the code, but the following 3 ways are the most popular:
1. Text Editor (eg: Sublime text, Atom etc)
1. They are not exclusively for Python.
2. Full IDE’s (eg: PyCharm , Spyder etc)
1. Best used for larger program with Python specific functionalities
3. Notebook Environments (eg: Jupyter Notebook)
1. Great for learning, seeing input and output next to each other, visualization and mark-down
notes (doesn’t use the same .py file extension though)

Dept. of CSE, NIEIT


Things to Install

 Sublime Text
 Anaconda Navigator

Dept. of CSE, NIEIT


The Integer, Floating-Point, and String Data
Types

 Python programs can also have text values called strings, or strs (pronounced “stirs”).
 Always surround your string in single quote (') characters (as in 'Hello' or 'Goodbye cruel world!') so
Python knows where the string begins and ends.
 You can even have a string with no characters in it, '', called a blank string.

Dept. of CSE, NIEIT


Operator Precedence

Dept. of CSE, NIEIT


Storing values in variables

 Think of a variable as a labeled box that a value is placed in:

Dept. of CSE, NIEIT


Dept. of CSE, NIEIT
Variable names
You can name a variable anything as long as it obeys the following three rules(it is also case-
sensitive):
1. It can be only one word.
2. It can use only letters, numbers, and the underscore (_) character.
3. It can’t begin with a number.

Dept. of CSE, NIEIT


First Program

Dept. of CSE, NIEIT


The str(), int(), and float() Functions

 The str(), int(), and float() functions will evaluate to the string, integer, and
floating-point forms of the value you pass, respectively.
 Note that if you pass a value to int() that it cannot evaluate as an integer, Python will display
an error message.
 int() can also be used to round off floating values

Dept. of CSE, NIEIT


Dept. of CSE, NIEIT
FLOW CONTROL

 You almost never want your programs to start from the first line of code and
simply execute every line, straight to the end.
 Flow control statements can decide which Python instructions to execute
under which conditions.

Dept. of CSE, NIEIT


Dept. of CSE, NIEIT
Understanding…

 In a flowchart, there is usually more than one way to go from the start to the end. The same is
true for lines of code in a computer program.
 Flowcharts represent these branching points with diamonds, while the other steps are
represented with rectangles. The starting and ending steps are represented with rounded
rectangles.
 We first need to learn how to represent those yes and no options, and you need to understand
how to write those branching points as Python code

Dept. of CSE, NIEIT


Boolean values

Although integer, floating-point and string


data types can take infinite number of
values;
The Boolean data type has only two values:
True and False.
When typed as Python code, the Boolean
values True and False lack the quotes you
place around strings, and they always start
with a capital T or F, with the rest of the
word in lowercase.

Dept. of CSE, NIEIT


Comparison
Operators
Comparison operators compare two
values and evaluate down to a single
Boolean value.

== and != operators work with any data


types

Dept. of CSE, NIEIT


Boolean
Operators
The three Boolean operators (and, or,
and not) are used to compare Boolean
values.
Binary Boolean Operators: and , or
Unary Boolean Operators: not

Dept. of CSE, NIEIT


Mixing Boolean and Comparison Operators

 The and, or, and not operators are called Boolean operators because they always operate on the
Boolean values True and False.
 While expressions like 4 < 5 aren’t Boolean values, they are expressions that evaluate down to
Boolean values.

**Note: Boolean operators also have precedence: Python evaluates the


not operators first, then the and operators, and then the or operators.

Dept. of CSE, NIEIT


Elements of Flow Control

 Flow control statements often start with a part called the condition, and all are followed by
a block of code called the clause.
Condition
 Conditions are arithmetic or Boolean operations which always evaluate down to a Boolean
value, True or False.
 A flow control statement decides what to do based on whether its condition is True or False.

Dept. of CSE, NIEIT


Clause (Blocks of code)
 Lines of Python code can be grouped together in blocks.
 You can tell when a block begins and ends from the indentation of the lines of code.

There are three rules for blocks:


1. Blocks begin when the indentation increases.
2. Blocks can contain other blocks.
3. Blocks end when the indentation decreases to zero or to a containing block’s indentation.

Dept. of CSE, NIEIT


Flow Control Statements

if statements
 An if statement’s clause (that is, the block following the if statement) will execute
if the statement’s condition is True.
else statements
 The else clause is executed only when the if statement’s condition is False.
elif statements
 While only one of the if or else clauses will execute, you may have a case where
you want one of many possible clauses to execute.

Dept. of CSE, NIEIT


Dept. of CSE, NIEIT
while Loop Statements
 You can make a block of code execute over and over again with a while statement.
 The code in a while clause will be executed as long as the while statement’s condition is True
Let’s look at an if statement and a while loop that use the same condition and take the same actions based on that
condition:

Dept. of CSE, NIEIT


if vs while

Dept. of CSE, NIEIT


break, continue, pass

break
 If the execution reaches a break statement, it immediately
exits the while loop’s clause

continue
 When the program execution reaches a continue statement,
the program execution immediately jumps back to the start
of the loop and reevaluates the loop’s condition.
pass
 It is a null statement. The interpreter does not ignore
a pass statement, but nothing happens and the statement
results into no operation(eg: abstract functions)

Dept. of CSE, NIEIT


Dept. of CSE, NIEIT
for loops and range( ) function

 What if you want to execute a block of code only a certain number of times?

 The first time it is run, the variable i is set to 0. The print() call in the clause will print Jimmy
Five Times (0).

Note: This is similar to foreach type loop in Java, C# etc

Dept. of CSE, NIEIT


Dept. of CSE, NIEIT
The Starting, Stopping, and Stepping
Arguments to range()
range (start-point, end-point, steps)

Eg:

Dept. of CSE, NIEIT


Importing modules

 All Python programs can call a basic set of functions called built-in functions, including the print(),
input(), and len() functions you’ve seen before.
 Python also comes with a set of modules called the standard library.

from import Statements


 An alternative form of the import statement is composed of the from keyword, followed by the module
name, the import keyword, and a star;
for example: from random import *
Dept. of CSE, NIEIT
Ending a Program Early with sys.exit()

 The last flow control concept to cover is how to terminate the program.
 This always happens if the program execution reaches the bottom of the instructions.
 However, you can cause the program to terminate, or exit, by calling the sys.exit() function.

Dept. of CSE, NIEIT


FUNCTIONS

 A function is like a mini-program within a program.


 To be more simple, it is a subset of statements which you think will be repeatedly used in the
program.
 In general, you always want to avoid duplicating code, because if you ever decide to update
the code—if, for example, you find a bug you need to fix—you’ll have to remember to
change the code everywhere you copied it.
 Deduplication makes your programs shorter, easier to read, and easier to update.

Dept. of CSE, NIEIT


How to define a function?

 To create a Python function we use def keyword

Eg:

As you can see, it is similar to if/while statement declaration but with def keyword

Dept. of CSE, NIEIT


def Statements with Parameters

 When you call the print() or len() function, you pass in values, called arguments in this context, by
typing them between the parentheses.
 You can also create your own functions which takes these arguments.

 A parameter is a variable that an argument is stored in when a function is called.


Note: One special thing to note about parameters is that the value stored in a parameter is forgotten(scope is
just within the function) when the function returns.
Dept. of CSE, NIEIT
Return Values and return Statements

 When you call the len() function and pass it an argument such as 'Hello', the function call
evaluates to the integer value 5, which is the length of the string you passed it.
 In general, the value that a function call evaluates to is called the return value of the function.
 A return statement consists of the following:
 The return keyword
 The value or expression that the function should return

Dept. of CSE, NIEIT


Dept. of CSE, NIEIT
The None value

 In Python there is a value called None, which represents the absence of a value.
 None is the only value of the NoneType data type (similar to Null, Nil, Void or undefined).
 This value-without-a-value can be helpful when you need to store something that won’t be confused for a real
value in a variable.

 Behind the scenes, Python adds return None to the end of any function definition with no return statement.
 Also, if you use a return statement without a value (that is, just the return keyword by itself), then None is
returned.
Dept. of CSE, NIEIT
Keyword Arguments and print()

 Most arguments are identified by their position in the function call.


 Eg: random.randint(1, 10) is different from random.randint(10, 1)

 The first position indicates the starting point and the second one indicates the end point.
 However, keyword arguments are identified by the keyword put before them in the function
call.
 Keyword arguments are often used for optional parameters. (similar to default values of a
parameter that you learnt in Java).

Dept. of CSE, NIEIT


end and sep for print( )

 Consider the following code: It produces output as follows:

 The print statement automatically adds a newline at the end.


 However, you can set the end keyword argument to change this to a different string.

 You can also pass multiple strings and also, change the default separator using sep keyword argument

Dept. of CSE, NIEIT


Local and Global Scope

 Parameters and variables that are assigned in a called function are said to exist in that function’s
local scope.
 Variables that are assigned outside all functions are said to exist in the global scope.
 A variable that exists in a local scope is called a local variable, while a variable that exists in the
global scope is called a global variable.
 A variable must be one or the other; it cannot be both local and global.
 When a scope is destroyed, all the values stored in the scope’s variables are forgotten.
 There is only one global scope, and it is created when your program begins.
 When your program terminates, the global scope is destroyed, and all its variables are forgotten.

Dept. of CSE, NIEIT


Recollection of what a scope is..

Scopes matter for several reasons:


1. Code in the global scope cannot use any local variables.
2. However, a local scope can access global variables.
3. Code in a function’s local scope cannot use variables in any other local scope.
4. You can use the same name for different variables if they are in different scopes. That is, there can be a
local variable named spam and a global variable also named spam.

Dept. of CSE, NIEIT


The global statement

 If you need to modify a global variable from within a function, use the global statement.
 It tells Python, “In this function, eggs refers to the global variable, so don’t create a local variable
with this name.”
Output:

Dept. of CSE, NIEIT


4 rules!

There are four rules to tell whether a variable is in a local scope or global scope:

1. If a variable is being used in the global scope (that is, outside of all functions), then it is always a
global variable.
2. If there is a global statement for that variable in a function, it is a global variable.
3. Otherwise, if the variable is used in an assignment statement in the function, it is a local variable.
4. But if the variable is not used in an assignment statement, it is a global variable.

Dept. of CSE, NIEIT


Program showing the 4 rules

Output:

In a function, a variable will either always be global or always be local.


Dept. of CSE, NIEIT
Program is compiled in sequence?

 If you try to use a local variable in a function before you assign a value to it, as in the following
program, Python will give you an error
**Note: But in Python you can use the global variable in a function before it is assigned.

Dept. of CSE, NIEIT


Encapsulation

Dept. of CSE, NIEIT


Exception Handling

 Right now, getting an error, or exception, in your Python program means the entire program will
crash. You don’t want this to happen in real-world programs.

 print(spam(0)) throws an error and the program exits before executing print(spam(1))

Dept. of CSE, NIEIT


try…except?

 The code that could potentially have an error is put in a try clause. The program execution moves to
the start of a following except clause if an error happens.

 Java: try, catch & finally


Dept. of CSE, NIEIT
 Note that any errors that occur in function calls in a try block will also be caught.

Output:

 The reason print(spam(1)) is never executed is because once the execution jumps to the code in the
except clause, it does not return to the try clause.

Dept. of CSE, NIEIT

You might also like