0% found this document useful (0 votes)
212 views

Module 1

Uploaded by

mksaravanamk1
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
212 views

Module 1

Uploaded by

mksaravanamk1
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 74

RNS Institute of Technology

Department of Computer Science and


Engineering (Data Science)

Introduction to Python Programming


BPLCK205B
• Vision: Empowering students to solve complex
real time computing problems involving high
volume multidimensional data.
Course Outcomes
CO1 Demonstrate proficiency in handling of loops and creation of
functions.
CO2 Identify the methods to create and manipulate lists, tuples
and dictionaries.
CO3 Discover the commonly used operations involving regular
expressions and file system.
CO4 Interpret the concepts of Object-Oriented Programming as
used in Python.
CO5 Determine the need for scraping websites and working with
CSV, JSON and other file formats.
Module 1: Python Basics
• Whom Is This course for?
– Moving and renaming thousands of files and sorting
them into folders.
– Filling out online forms, no typing required
– Downloading files or copy text from a website
whenever it updates.
– Having your computer text you custom notifications.
– Updating or formatting Excel spreadsheets.
– Checking your email and sending out prewritten
responses.
Module 1: Python Basics
• Why Is Programming?
– “Do this; then do that.”
– “If this condition is true, perform this action;
otherwise, do that action.”
– “Do this action that number of times.”
– “Keep doing that until this condition is true.”
Module 1: Python Basics
➊ passwordFile = open('SecretPasswordFile.txt')
➋ secretPassword = passwordFile.read()
➌ print('Enter your password.')
typedPassword = input()
➍ if typedPassword == secretPassword:
➎ print('Access granted')
➏ if typedPassword == '12345':
➐ print('That password is one that an idiot puts on their luggage.')
else:
➑ print('Access denied')
Module 1: Python Basics
• What Is Python?
• Downloading and Installing Python:
• http://python.org/downloads/
Contd..
• In Ubuntu, you can install Python from the
Terminal by following these steps:
• 1. Open the Terminal window.
• 2. Enter sudo apt-get install python3.
• 3. Enter sudo apt-get install idle3.
• 4. Enter sudo apt-get install python3-pip.
Contd..
• Starting IDLE
• The Interactive Shell
• How to Find Help
– >>> '42' + 3
– ➊ Traceback (most recent call last):
– File "<pyshell#0>", line 1, in <module>
– '42' + 3
– ➋ TypeError: Can't convert 'int' object to str implicitly
– >>>
Contd..

• Asking Smart Programming Questions


• Stack Overlow (http://stackoverflow.com/)
• The “learn programming” subreddit at
http://reddit.com/r/learnprogramming/.
Chapter 1. Python Basics
• The Python programming language
• Syntactical constructions
• standard library functions
• Interactive development environment
features.
Contd..
• Entering Expressions into the Interactive Shell
• A window with the >>> prompt should appear;
Contd..
• >>> 2 + 2
• 4
• The IDLE window should now show some text like this:
• Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013,
00:06:53) [MSC v.1600 64 bit
• (AMD64)] on win32
• Type "copyright", "credits" or "license()" for more
information.
• >>> 2 + 2
• 4 >>>
Contd..
Contd..
The Integer, Floating-Point, and String Data
Types
• A data type is a category for values, and every
value belongs to exactly one data type.
String Concatenation and Replication
• when + is used on two string values, it joins
the strings .-string concatenation operator.
• Use the + operator on a string and an integer
value or with two integer values or or floating-
point values.
• Python Can't convert 'int' object to str
implicitly.
String Concatenation and Replication
• The * operator is used for multiplication when it
operates on two integer or floating-point values.
• But when the * operator is used on one string
value and one integer value, it becomes the string
replication operator.
• The * operator can be used with only two
numeric values (for multiplication) or one string
value and one integer value (for replication)
Storing Values in Variables
• Assignment Statements
• with an assignment statement.
Storing Values in Variables
• When a variable is assigned a new value , the
old value is forgotten. -overwriting the
variable
Contd..
• Variable Names
• variable name must obey the following three
rules:
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.
Contd..
First Program
Dissecting Your Program
• Comments
• The following line is called a comment.
• ➊ # This program says hello and asks for my
name.
• The print() Function
– displays the string value inside the parentheses on
the screen
– print('Hello world!')
– print('What is your name?')
Contd..
• The input() Function
– The input() function waits for the user to type
some text on the keyboard and press ENTER.
– myName = input()
– This function call evaluates to a string equal to the
user’s text.
• The len() Function
• The str(), int(), and float() Functions
Contd..
Chapter 2. Flow Control
• Flow control statements can decide which
Python instructions to execute under which
conditions.
Contd..
• Boolean Values
• 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.
• They always start with a capital T or F
Contd..
• Comparison Operators
Contd..
• Boolean Operators
• Three Boolean operators (and, or, and not) are
used to compare Boolean values.
Contd..
• Mixing Boolean and Comparison Operators
• >>> (4 < 5) and (5 < 6)
• True
• >>> (4 < 5) and (9 < 6)
• False
• >>> (1 == 2) or (2 == 2)
• True
Contd..
• 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.
• Conditions
• Blocks of Code
Contd..
• Conditions
• Condition is just a more specific name in the
context of flow control statements.
• Conditions always evaluate down to a Boolean
value, True or False.
Contd..
• Blocks of Code
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.
Example:
• if name == 'Mary':
• ➊ print('Hello Mary')
• if password == 'swordfish':
• ➋ print('Access granted.')
• else:
• ➌ print('Wrong password.')
Flow Control Statements
• if Statements
• In Python, an if statement consists of the following:
– The if keyword
– A condition (that is, an expression that evaluates to True
or False)
– A colon
– Starting on the next line, an indented block of code
(called the if clause)
• if name == 'Alice':
print('Hi, Alice.')
Flow Control Statements
Flow Control Statements
• else Statements
• An else statement always consists of the following:
– The else keyword
– A colon
– Starting on the next line, an indented block of code
(called the else clause)
• if name == 'Alice':
print('Hi, Alice.')
else:
print('Hello, stranger.')
Flow Control Statements
Flow Control Statements
• elif Statements
• An elif statement always consists of the
following:
– The elif keyword
– A condition (that is, an expression that evaluates
to True or False)
– A colon
– Starting on the next line, an indented block of
code (called the elif clause)
Flow Control Statements
Contd..
Flow Control Statements
• while Loop Statements
• A while statement always consists of the
following:
– The while keyword
– A condition (that is, an expression that evaluates
to True or False)
– A colon
– Starting on the next line, an indented block of
code (called the while clause)
Flow Control Statements
• Code with an if statement:
• spam = 0
• if spam < 5:
Running these
print('Hello, two code snippets,
world.')
something
spam = spamvery
+ 1 different happens for
each
• code one.
with a while statement:
• spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
Flow Control Statements
Flow Control Statements
Flow Control Statements
Flow Control Statements
• break Statements
Contd..
• Continue Statements
Contd..
• for Loops and the range() Function
• A for statement looks something like for i in range(5):
and always includes the following:
– The for keyword
– A variable name
– The in keyword
– A call to the range() method with up to three integers
passed to it
– A colon
– Starting on the next line, an indented block of code (called
the for clause)
Contd..
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')

Output:
Contd..
• The Starting, Stopping, and Stepping
Arguments to range()
Contd..
Importing Modules
• Python also comes with a set of modules called
the standard library.
• Each module is a Python program that contains a
related group of functions that can be
embedded in your programs.
• Example, the math module, the random module.
• Before you can use the functions in a module,
you must import the module with an import
statement.
Contd..
examples
• Python program to find the sum of natural
numbers up to n where n is provided by user.
• Python Program to find the factors of a
number.
• Python program to check if the input number
is prime or not.
• Python program to find the factorial of a
number provided by the user.
examples
• Python program to find a given year is leap
year.
• Python Program to find the roots of quadratic
equation.
• Python program to swap to numbers.
• Python program to print stars shown:
*
***
*****
*******
*********
***********
Functions
• A function is like a mini-program within a
program.
• ➊ def hello():
• ➋ print('Howdy!')
• print('Howdy!!!')
• print('Hello there.')
➌ hello()
• hello()
• hello()
def Statements with Parameters
• ➊ def hello(name):
• ➋ print('Hello ' + name)
• ➌ hello('Alice')
• hello('Bob')
Return Values and return Statements
• When creating a function using the def
statement, you can specify what the return
value should be with a return statement.
• A return statement consists of the following:
• The return keyword
• The value or expression that the function
should return
example

print(getAnswer(random.randint(1,9)))
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.
Keyword Arguments and print()
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.
Local and Global Scope
• Scopes matter for several reasons:
• Code in the global scope cannot use any local
variables.
• However, a local scope can access global
variables.
• Code in a function’s local scope cannot use
variables in any other local scope.
• You can use the same name for different
variables if they are in different scopes.
Local and Global Scope

• Local Variables Cannot Be Used in the Global


Scope.
• Local Scopes Cannot Use Variables in Other
Local Scopes.
• Global Variables Can Be Read from a Local
Scope.
• Local and Global Variables with the Same
Name.
The global Statement

• If you need to modify a global variable from within a


function, use the global statement.
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.
Exception Handling
• We want the program to detect errors, handle
them, and then continue to run.
Exception Handling
• Errors can be handled with try and except
statements. The code that could potentially
have an error is put in a try clause.
Examples
• Python program to find LCM of two numbers.
• Python program to find GCD of two numbers.
• Python program to find GCD of two numbers
using recursive function.
• Python program to find factorial of a number
using recursive function.
• Python program to print Fibonacci numbers
using recursive function.
Examples
• Python program to find sum of natural
numbers using recursive function.
• Python program to print Floyds Triangle.
• 1
• 23
• 456
• 7 8 9 10
• Newtons method to approx the sqrt
• Y=x+a/x/2

You might also like