0% found this document useful (0 votes)
6 views63 pages

Module 1 BPLCK205B

The document is an introduction to Python programming, covering basic concepts such as data types, variables, and flow control statements. It explains how to use the interactive shell, perform string operations, and implement control structures like if, else, and loops. Additionally, it discusses functions, scope, and exception handling in Python.

Uploaded by

Rumana
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)
6 views63 pages

Module 1 BPLCK205B

The document is an introduction to Python programming, covering basic concepts such as data types, variables, and flow control statements. It explains how to use the interactive shell, perform string operations, and implement control structures like if, else, and loops. Additionally, it discusses functions, scope, and exception handling in Python.

Uploaded by

Rumana
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/ 63

Introduction to Python

Programming
(BPLCK205B)

Rumana Anjum
Assistant Professor
Dept of CSE, VVIET
Chapter 1: Python Basics
Agenda
• Entering expressions into the interactive shell

• The integer, floating-point and String Data Types

• String concatenation and replication

• Storing values in variables

• Your first program

• Dissecting your program


Entering expressions into the interactive shell
Run the interactive shell by launching IDLE, which is installed with Python. On
Windows, open the Start menu, select All Programs ▸ Python 3.3, and then select
IDLE (Python GUI).
A window with the >>> prompt should appear; that‘s the interactive shell.
• In Python, 2 + 2 is called an expression. Expressions consist of values (such as 2) and
operators (such as +), and they can always evaluate (that is, reduce) down to a single value.

• The other operators which can be used are:


The integer, floating-point and String Data Types

• The integer (or int) data type indicates values that are whole numbers.
• Numbers with a decimal point, such as 3.14, are called floating-point numbers (or floats).
• Note that even though the value 42 is an integer, the value 42.0 would be a
floating_x0002_point number.
• Python programs can also have text values called strings, or strs and surrounded in single
quote.
• The string with no characters, '', called a blank string.
String concatenation and replication

⮚ The meaning of an operator may change based on the data types of the values
next to it
⮚ For example, + is the addition operator when it operates on two integers or
floating- point values.
⮚ However, when + is used on two string values, it joins the strings
as the string concatenation operator.
⮚ If we try to use the + operator on a string and an integer value, Python will not know how to handle this,
and it will display an error message.

• 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.
• 1.4 Storing Values in Variables

• A variable is like a box in the computer‘s memory where you can store a single value.
• If we need to use variables later, then the result must be stored in variable.

• Assignment Statements
• You‘ll store values in variables with an assignment statement.
• An assignment statement consists of a variable name, an equal sign (called the
assignment operator), and the value to be stored.
• Ex: spam = 42
• Overwriting the variable

• When a variable is assigned a new value , the old value is forgotten, which is why spam
evaluated to 42 instead of 40 at the end of the example.
• One more example
• Variable names
• We can name a variable anything as long as it obeys the following three rules:
• It can be only one word.
• It can use only letters, numbers, and the underscore (_) character.
• It can‘t begin with a number.
Your First Program
Example program:
• Dissecting Your Program
• The following line is called a comment.

• The print() Function


•The print() function displays the string value inside the parentheses on the screen.

•When Python executes this line, you say that Python is calling the print() function and the
string value is being passed to the function.

•The quotes are not printed to the screen. They just mark where the string begins and ends;
they are not part of the string value
• The Input Function

• We can think of the input() function call as an expression that evaluates to whatever
• string the user typed in. If the user entered 'Al', then the expression would evaluate to
• myName = 'Al'.

Printing the User’s Name


• The following call to print() actually contains the expression 'It is good to meet you, '
+myName between the parentheses.

• If 'Al' is the value stored in myName on the previous line, then this expression evaluates
to 'It is good to meet you, Al'.
• The len() Function
• We can pass the len() function a string value (or a variable containing a string), and the
function evaluates to the integer value of the number of characters in that string.
Example 1:

Example 2:
• Here print() function isn‘t causing that error, but rather it‘s the expression you tried to
pass to print().

• Python gives an error because we can use the + operator only to add
two integers together or concatenate two strings.
NOTE
We can‘t add an integer to a string because this is ungrammatical in
Python.
The str(), int() and float() Functions:’
The str() function can be passed an integer value and will
evaluate to a string value version of it, as follows:

The following evaluation happens:


• 'I am ' + str(29) + ' years old.'
• 'I am ' + '29' + ' years old.',
• 'I am 29 years old.'.

finally 'I am 29 years old.' passed to the print() function.


• The str(), int(), and float() functions will evaluate to the string, integer,
and floating- point forms of the value you pass, respectively.
• example:

Note:
• The str() function is handy when you have an integer or float that you
want to concatenate to a string.
• The int() function is also helpful if we have a number as a string value
that you want to use in some mathematics.
• Example: The input() function always returns a string, even if the user
enters a number.
• The int() function is also useful if we need to round a floating-point
number down. If we want to round a floating-point number up, just add
1 to it afterward.
• Example:
• Explain what following code does:
Explaination goes like this:
Text and Number Equivalence
Although the string value of a number is considered a completely
different value from the integer or floating-point version, an integer can
be equal to a floating point.
CHAPTER 2
FLOW CONTROL
1. Boolean Values
2. Comparison Operators
3. Boolean Operators
4. Mixing Boolean and Comparison Operators
5. Elements of Flow Control
6. Program Execution
7. Flow Control Statements
8. Importing Modules
9. Ending a Program Early with sys.exit()
INTRODUCTION
• Flow control statements can decide which Python instructions to
execute under which conditions.
Boolean Values
The Boolean data type has only two values: True and False.
Comparison Operators
List of comparision operator

Example:
== and != can actually work with any data types

The <, >, <=, and >= operators, on the other hand, work properly only
with integer and floating-point values.
Note the Difference Between the == and = Operators
• The == operator (equal to) asks whether two values are the same as each other.

• The = operator (assignment) puts the value on the right into the variable on the left.

Boolean Operators
Three boolean operators are and , or and not.
Truth table for and operator is :
• Truth table for or operator is :

Truth table for not operator is :


Mixing Boolean and Comparison Operators

Evaluation goes like this:

Explain this expression:


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:
⮚ The Boolean expressions are conditions, which are the same thing as expressions.

⮚ Conditions 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, and
almost every flow control statement uses a condition.

Blocks of Code:
There are three rule:
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:

Program Execution:
➢ The program execution (or simply, execution) is a term for the current
instruction being executed.
Flow Control Statements:
1. 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)
Example:
2. else Statements:
An else statement doesn‘t have a condition, and in code, an else
statement always consists of the following:
1. The else keyword
2. A colon
3. Starting on the next line, an indented block of code (called the else
clause)
Example and Flowchart :
3. elif Statements:
In code, an elif statement always consists of the following:
1. The elif keyword
2. A condition (that is, an expression that evaluates to True or False)
3. A colon
4. Starting on the next line, an indented block of code (called the elif
clause)
Example and Flowchart :
Example and Flowchart :

Whats the output for following code?


4. while loop Statements:
In code, a while statement always consists of the following:
1. The while keyword
2. A condition (that is, an expression that evaluates to True or False.
3. A colon
4. Starting on the next line, an indented block of code (called the while
clause)
Example:
Flowchart :
Annoying while loop example:
name = ''
while name != 'your name':
print('Please type your name')
name = input()
print('Thank you')

Output:
Please type your name
Ashwini
Please type your name
Alice
Please type your name
234788
Please type your name
your name
Thank you
5. break Statements:
If the execution reaches a break statement, it immediately exits the while
loop‘s clause

6. Continue statement
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.
• Example:

Output:
for loops and the range() function:
In code, a for statement looks something like for i in range(5): and always
includes the following:
1. The for keyword
2. A variable name
3. The in keyword
4. A call to the range() method with up to three integers passed to it
5. A colon
6. Starting on the next line, an indented block of code (called the for
clause)
Flow chart:

what does this code do??


The Starting, Stopping, and Stepping Arguments to range()
• Range can be called with multiple arguments separated by a comma.

• The first argument will be where the for loop‘s variable starts, and the
second argument will be up to, but not including, the number to stop at.
Output:
12
13
14
15
• Range with step argument

Example:

Output:

What does this code do??


Importing Modules
• Python also comes with a set of modules called the standard library.
• Before we can use the functions in a module, we must import the
module with an import statement. In code, an import statement
consists of the following:
1. The import keyword
2. The name of the module
3. Optionally, more module names, as long as they are separated by
commas

Example Output
• Since randint() is in the random module, we must first type random. in
front of the function name to tell Python to look for this function inside
the random module

• Import statement imports four different modules:

• from random import * :With this form of import statement, calls to


functions in random will not need the random prefix.
Ending a Program Early with sys.exit()
Example:

• Since this function is in the sys module, we have to import sys before
your program can use it.
• Since the response variable is set by the input() function, the user must
enter exit in order to stop the program.
Chapter 3
FUNCTIONS

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

Example: Output

• The first line is a def statement ❶, which defines a function named


hello().
• This code is executed when the function is called, not when the function
is first defined.
def Statements with Parameters
• We can also define our own functions that accept arguments like len()
and print() functions.
Example: Output :

Return Values and Return Statements:


The value that a function call evaluates to is called the return value of the
function.
A return statement consists of the following:
1. The return keyword
2. The value or expression that the function should return.
• Example:
The None Value
• In Python there is a value called None, which represents the absence of
a value.

Keyword Arguments and print()


• Most arguments are identified by their position in the function call.
• random.randint(1, 10) is different from random.randint(10, 1).
print() function:
Example 1:

• Example 2:

• Example 3:
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.

• When your program terminates, the global scope is destroyed, and all its
variables are forgotten.

• local scope is created whenever a function is called.When the function


returns, the local scope is destroyed, and these variables are forgotten.
Scopes matter for several reasons:
• Code in the global scope cannot use any local variables
• a local scope can access global variables
• Code in a function‘s local scope cannot use variables in any other local
scope.
• We can use the same name for different variables if they are in different
scopes.
Local Variables Cannot Be Used in the Global Scope
Example Output
Local Scopes Cannot Use Variables in Other Local Scopes:
A new local scope is created whenever a function is called,
including when a function is called from another function.
Example:
Global Variables Can Be Read from a Local Scope:
Example:

Local and Global Variables with the Same Name: Example:


The Global Statement
• If we need to modify a global variable from within a function, use the
global.

Output:
spam
NOTE:
• If we ever want to modify the value stored in a global variable from in a
function, we must use a global statement on that variable.
• If we try to use a local variable in a function before we assign a value to
it, as in the following program, Python will give you an error.
Example:
Exception Handling:
Example:

We can put the previous divide-by-zero code in a try clause and have an
except clause contain code to handle what happens when this error occurs.
Guess the number:
Output:
THANK YOU

You might also like