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

19674254 Python Module 1

This document provides an introduction to Python programming, covering its features, syntax, and development process. It discusses the Python interactive shell, IDLE, and the Jupyter Notebook, as well as basic coding skills such as data types, variables, and error handling. Additionally, it outlines the software development process and includes practical programming exercises.

Uploaded by

jocktmpx4oxc
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 views55 pages

19674254 Python Module 1

This document provides an introduction to Python programming, covering its features, syntax, and development process. It discusses the Python interactive shell, IDLE, and the Jupyter Notebook, as well as basic coding skills such as data types, variables, and error handling. Additionally, it outlines the software development process and includes practical programming exercises.

Uploaded by

jocktmpx4oxc
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
You are on page 1/ 55

Date: 10/02/2023 Module I

Getting started with Python programming

* Python is a high-level, general-purpose programming language for


solving problems on modern computer systems.

*Its original creator is Guido van Rossum.

* Python is a product of the Python Software Foundation, a non-profit


organization that holds the copyright.

*It is a powerful object-oriented programming language, comparable to


Perl, Ruby, Scheme, or Java.

* Python is simpler to use, available on Windows, macOS, and Unix


operating systems

* Since its data types are more general, Python is applicable to a much
larger problem domain

* Python is an interpreted language, which can save you considerable


time during program development because no compilation and linking is
necessary.

* Python enables programs to be written compactly and readably.


Programs written in Python are typically much shorter than equivalent C,
C++, or Java programs.

Reasons are:

1. The high-level data types allow you to express complex operations


in a single statement;
2. Statement grouping is done by indentation instead of beginning
and ending brackets;
3. No variable or argument declarations are necessary.
Use of indentation Example:

In Python, we need to indent all code blocks to the same level.

def bigger_than_five(x):
if x > 5:
print("X is bigger than five")
else:
print("x is 5 or smaller")

Because indentation is required, the Python language does not need curly
braces to group code blocks like Java, C, and C#

No manual compilation of your program

* Many languages either require a manual compilation step before you can
run your program or can be run directly by the interpreter. Python is
actually somewhere in between these two worlds.

=> You can write your code in a text editor and execute it directly. No
additional steps like compilation and linking are necessary.

Internally Python compiles your code into lower-level code, called


bytecode(*.pyc ).

This code is not specific to a system architecture (like Intel vs ARM), but
it is faster to read and parse than plain text files. Therefore Python is
platform-independent.
Date : 17/02/2023, Friday

Python Interactive Shell

* Python is an interpreted language

* The interpreter operates like the Unix shell

=> when called with standard input connected to a TTY(Teletypewriter)


device, it reads and executes commands interactively;

=> when called with a file name argument or with a file as standard
input, it reads and executes a script from that file.

* Shell: A Shell in operating systems lies between the kernel of the


operating system and the user. It's a "protection" in both directions.

=>The user doesn't have to use the complicated basic functions of the OS
but is capable of using the interactive shell which is relatively simple and
easy to understand.

=>The kernel is protected from unintentional and incorrect usages of


system functions.

* With the Python installer, two interactive shells are provided:

1. IDLE (Python GUI)


2. Python (command line).

1. Python Interactive Shell:When commands are read from a tty, the


interpreter is said to be in interactive mode. In this mode it prompts for the
next command with the primary prompt, usually three greater-than signs
(>>>).

The interpreter prints a welcome message stating its version number and a
copyright notice before printing the first prompt.
Once the Python interpreter is started, you can issue any command at the
command prompt

* To end the interactive session, You can either use exit() or Ctrl-D (i.e.
EOF) to exit.
2.Python IDLE - Integrated DeveLopment Environment

* Python interactive shell with GUI is known as Integrated Development


Environment (IDLE). It is an integrated program development
environment that comes with the Python installation.The easiest way to
open a Python shell is to launch the IDLE.

* The IDLE programming environment uses color-coding to help the


reader pick out different elements in the code

* To quit the Python IDLE, you can either select the window’s close box or
press the Control + D key combination.
Editing, Saving, and Running a Script

1. Select the option New Window from the File menu of the shell
window(IDLE)
OR
$ gedit/vim/vi filename.py

2. Write Python expressions or statements on separate lines, in the order in


which you want Python to execute them.

3. Save the file using a . py extension.

4. To run this file of code as a Python script, select Run Module from the
Run menu or press the F5 key. (IDLE)

OR
$ python filename.py
IPython Notebook

ref: https://ipython.org/ipython-doc/dev/notebook/notebook.html

* The IPython Notebook is now known as the Jupyter Notebook.


It is an interactive computational environment, in which you
can combine code execution, rich text, mathematics, plots and rich media.

* The notebook extends the console-based approach to interactive


computing in a qualitatively new direction, providing a web-based
application suitable for capturing the whole computation process:
developing, documenting, and executing code, as well as communicating
the results.

* The IPython notebook combines two components:

1. A web application: a browser-based tool for interactive authoring of


documents which combine explanatory text, mathematics, computations
and their rich media output.
* In-browser editing for code, with automatic syntax highlighting,
indentation, and tab completion/introspection.
* The ability to execute code from the browser, with the results of
computations attached to the code which generated them.
* Displaying the result of computation using rich media representations,
such as HTML, LaTeX, PNG, SVG, etc. For example, publication-quality
figures rendered by the matplotlib library, can be included inline.
2. Notebook documents:
* Notebook documents contains the inputs and outputs of a interactive
session as well as additional text that accompanies the code but is not
meant for execution.
* Notebook files can serve as a complete computational record of a
session, interleaving executable code with explanatory text, mathematics,
and rich representations of resulting objects.
Input, Processing, and Output in Python

*In terminal-based interactive programs, the input source is the keyboard,


and the output destination is the terminal display.

* The programmer can also force the output of a value


by using the print function.

1. Syntax: print(<expression>)
Semantics: Python first evaluates the expression and then displays its
value.

In Python code, a string is always enclosed in quotation marks

2. The syntax for a print statement with two or more expressions looks like
the following:

Syntax:
print(<expression>,..., <expression>)
Semantics:
Evaluates the expressions and displays them, separated by one
space, in the console window.
* The programmer can also ask the user for input

1. Syntax: input(<a string prompt>)


Semantics:
Displays the string prompt and waits for keyboard input.
Returns the string of characters entered by the user.

This function causes the program to stop and wait for the user to enter a
value from the keyboard. When the user presses the return or enter key, the
function accepts the input value and makes it available to the program.

The form of an assignment statement with the input function is the


following:
Syntax: <variable identifier> = input(<a string prompt>)

* The input function always builds a string from the user’s keystrokes and
returns it to the program.
After inputting strings that represent numbers, the programmer must
convert them from strings to the appropriate numeric types.
Detecting and Correcting Syntax Errors

* The term syntax refers to the rules for forming sentences in a language.

* Programmers usually make typographical errors when editing programs,


and the Python interpreter will nearly always detect them. Such errors are
called syntax errors.

* When Python encounters a syntax error in a program, it halts execution


with an error message

Here, Python responds that this name is not defined.

Here, in this error message, Python explains that this line of code is
unexpectedly indented. There is an extra space before the word print.

* Indentation is significant in Python code.

- Each line of code entered at a shell prompt or in a script must begin in


the leftmost column, with no leading spaces.
- The only exception to this rule occurs in control statements and
definitions, where nested statements must be indented one or more spaces.
How Python Works?

1. The interpreter reads a Python expression or statement, also called the


source code, and verifies that it is well formed.

- It rejects any sentence that does not adhere to the grammar rules, or
syntax, of the language.

- As soon as the interpreter encounters such an error, it halts translation


with an error message.

2. If a Python expression is well formed, the interpreter then translates it to


an equivalent form in a low-level language called byte code.

3. This byte code is next sent to another software component, called the
Python virtual machine (PVM), where it is executed. If another error
occurs during this step, execution also halts with an error message.
Problems

1. Write a Python program that prints (displays) your name, address, and
telephone number.

2. Write and test a program that accepts the user’s name (as text) and age
(as a number) as input. The program should output a sentence containing
the user’s name and age.

3. Write and test a program that computes the area of a circle.


This program should request a number representing a radius as input from
the user. It should use the formula 3.14 * radius ** 2 to compute the area
and then output this result suitably labeled.

4. Write a program to compute area and perimeter of a square. Read the


value for length of a side from keyboard.

5. Given divident and divisor, WAP to display quotient and remainder.


Date: 21/02/23 Tuesday

The Software Development Process

* Programming is not just writing code. It consists of organization and


planning, and various conventions for diagramming those plans.

* The process of planning and organizing a program is referred to as


software development. There are several approaches to software
development

One version is known as the Waterfall model.

1. Customer request => Collecting user requirements

2. Analysis => Programmer writes Requirement specification

3. Design => Programmers determine how the program will do its task

4. Implementation =>The programmers write the program.

5. Integration = > Different parts of a large program are brought together


into a smoothly functioning whole

6. Maintenance => During the life time of a program, requirements


change, errors are detected, and minor or major modifications are made.
*Modern software development is usually incremental and iterative.

=> This means that analysis and design may produce a rough draft,
skeletal version, or prototype of a system for coding, and then back up to
earlier phases to fill in more details after some testing.

* Extensive and careful testing is required to ensure correct working of a


program. It is not limited to implementation and integration phases. Output
of each phase must be scrutinized carefully.
Case Study: Income Tax Calculator

1. Customer Request

The customer requests for a program that computes a person’s income tax

2. Requirement Analysis

* Programmer attempts to learn about the problem domain and specify


what a program is going to do.

The relevant tax law:

* Another part of analysis determines what information the user will


have to provide.

In this case, the user inputs are gross income and number of dependents.

* Here the programmer and customer may decide on the user interface of
the developing application to get a better understanding.
3. Design
Design describes how the program is going to do the task. This usually
involves writing an algorithm in ordinary English / pseudocode.

4. Implementation (Coding)

Implementation is easy for the programmer, once pseudo code is ready


5. Testing

* A single run without syntax errors and with correct outputs provides just
a slight indication of a program’s correctness. Only thorough testing can
build confidence that a program is working correctly.

* Testing = > The programmer just loads the program repeatedly into the
shell and enters different sets of inputs. Some sets of inputs can reveal an
error. An error at this point, also called a logic error or a design error , is an
unexpected output.

A correct program produces the expected output for any legitimate


input.

* Test suite : Test suite is a smaller set of inputs, from which we can
conclude that the program will likely be correct for all inputs.
Basic Coding Skills

Strings, Assignment, and Comments

Data Types

* In programming, a data type consists of a set of values and a set of


operations that can be performed on those values.

* A literal is a value that a data type can take

The first two data types listed, int and float are called numeric data types,
because they represent numbers.

String Literals

* A string literal is a sequence of characters enclosed in single or double


quotation marks.

*Empty string: Although it contains no characters, it is also a string.

* Double-quoted strings can contain single quotation marks


or apostrophes
* To output the string as a single line

* To output a paragraph of text that contains several lines, you could use a
separate print function call for each line.

OR

However, it is more convenient to enclose the entire string literal, line


breaks and all, within three consecutive quotation marks (either single
or double) for printing

Escape Sequences

* Escape sequences are the way Python expresses special characters,


such as the tab, the newline, and the backspace (delete key), as literals.
String Concatenation

* We can join two or more strings to form a new string using the
concatenation operator + .

* The * operator allows you to build a string by repeating another string


a given number of times. The left operand is a string, and the right operand
is an integer

Variables and the Assignment Statement

* A variable associates a name with a value, making it easy to remember


and use the value later in a program.
* Rules to be followed, while choosing names for your variables:

1. Keywords are reserved for other purposes and thus cannot be used for
variable names.

2. In general, a variable name must begin with either a letter or an


underscore ( _ ), and can contain any number of letters, digits, or other
underscores.

3. Python variable names are case sensitive

4. Python programmers typically use lowercase letters for variable names,


but in the case of variable names that consist of more than one word, it’s
common to begin each word in the variable name (except for the first
one) with an uppercase letter.

Eg: interestRate

5. Programmers use all uppercase letters for the names of variables that
contain values that the program never changes.
Eg: STANDARD_DEDUCTION

* The wise programmer selects names that inform the human reader about
the purpose of the data.

* Variables receive their initial values and can be reset to new values with
an assignment statement .

Synatx: <variable name> = <expression>

Semantics : The Python interpreter first evaluates the expression on the


right side of the assignment symbol and then binds the variable name on
the left side to this value.

- When this happens to the variable name for the first time, it is called
defining or initializing the variable

-After you initialize a variable, subsequent uses of the variable name in


expressions are known as variable references
- When the interpreter encounters a variable reference in any expression, it
looks up the associated value. If a name is not yet bound to a value when it
is referenced, Python signals an error.

* Variables serve two important purposes in a program.

- They help the programmer keeptrack of data that change over time
- They also allow the programmer to refer to a complex piece of
information with a simple name

Program Comments and Docstrings

* A comment is a piece of program text that the computer ignores but that
provides useful documentation to programmers.

* Docstring: The author of a program can include his or her name and a
brief statement about the program’s purpose at the beginning of the
program file.
This type of comment, called a docstring and is a multi-line string.

* End-of-line comments: These comments begin with the # symbol and


extend to the end of a line.
An end-of-line comment might explain the purpose of a variable or the
strategy used by a piece of code, if it is not already obvious.
Good Programming Practices

1. Begin a program with a statement of its purpose and other information


that would help orient a programmer called on to modify the program at
some future date.

2. Accompany a variable definition with a comment that explains the


variable’s purpose.

3. Precede major segments of code with brief comments that explain their
purpose. The case study program presented earlier in this chapter does this.

4. Include comments to explain the workings of complex or tricky sections


of code.

Numeric Data Types


Integers

* Integers include 0, the positive whole numbers, and the negative whole
numbers

* Integer literals in a Python program are written without commas, and a


leading negative sign indicates a negative value.

* The magnitude of a Python integer is vey large and is limited only by the
memory of your computer.

Floating-Point Numbers

* Python uses floating-point numbers to represent real numbers.

* Values of the most common implementation of Python’s float type range


from approximately -10308 to 10308 and have 16 digits of precision

* A floating-point number can be written using either ordinary decimal


notation or scientific notation.

Character Sets

* In Python, character literals look just like string literals and are of the
string type.

* To mark the difference, we may use single quotes to enclose single-


character strings, and double quotes to enclose multi-character strings.

=> Thus, we refer to 'H' as a character and "Hi!"

* All data and instructions in a program are translated to binary numbers


before being run on a real computer.
To support this translation, the characters in a string each map to an
integer value. This mapping is defined in character sets, like the ASCII set
and the Unicode set.
- Original ASCII set encoded each keyboard character and several control
characters using the integers from 0 through 127. The ASCII set dou-
bled in size to 256 distinct values in the mid-1980s.

- Unicode set was created to support 65,536 values. Unicode supports


more than 128,000 values at the present time

* Following Table shows the mapping of character values to the first 128
ASCII codes:

* Python’s ord and chr functions convert characters to their numeric


ASCII codes and back again, respectively.
-These two functions provide a handy way to shift letters by a fixed
amount.

Problems
1. Let the variable x be "dog" and the variable y be "cat" . Write the values
returned by the following operations:
a. x + y
b. "the " + x + " chases the " + y
c. x * 4

2. Find the numeric value of following characters: a,e,i,o,u

3. Code a python program to get the upper case of input lower case letter.

4. Code a python program to get the lower case of input upper case letter.
Date: 22/2/23
Wednesday

Expressions

* Expressions provide an easy way to perform operations on data values to


produce other data values.

Eg: 5 + 3 * 2

* When entered at the Python shell prompt, an expression’s operands are


evaluated, and its operator is then applied to these values to compute the
value of the expression.

Arithmetic Expressions

* Arithmetic expression consists of operands and operators combined

eg: –3 ** 2, 2 ** 3 ** 2

* Common arithmetic operators in python are:


Operator precedence rules:

1. Exponentiation has the highest precedence and is evaluated first.

2. Unary negation is evaluated next, before multiplication, division, and


remainder.

3. Multiplication, both types of division, and remainder are evaluated


before addition and subtraction.

4. Addition and subtraction are evaluated before assignment.

5. With two exceptions, operations of equal precedence are left associative,


so they are evaluated from left to right.
- Exponentiation and assignment operations are right associative, so
consecutive instances of these are evaluated from right to left.

6. You can use parentheses to change the order of evaluation.


* A computer generates a syntax error when an expression or sentence is
not well formed.

* A semantic error is detected when the action that an expression describes


cannot be carried out, even though that expression is syntactically correct.
Eg: 45 / 0 and 45 % 0

* When both operands of an arithmetic expression are of the same numeric


type, the resulting value is also of that type (except for division operation)

* When each operand is of a different type, the resulting value is of the


more general type.

* Programmers usually insert a single space before and after each operator
to make the code easier for people to read.

* Normally, an expression must be completed on a single line of


Python code.
When an expression becomes long or complex, you can move to a
new line by placing a backslash character \ at the end of the current line.

Mixed-Mode Arithmetic and Type Conversions

* Performing calculations involving both integers and floating-point


numbers is called mixed-mode arithmetic .

Eg: Calculate the area of a circle with radius =3

Here, the less general type (int) is temporarily and automatically con-
verted to the more general type (float) before the operation is performed.
Thus, in the example expression, the value 9 is converted to 9.0 before
the multiplication.

* Yo have type conversion functions to explicitly convert values from one


type to another.
A typeconversion function is a function with the same name as
the data type to which it converts.

* Input() function reads all inputs as strings and they must be converted to
appropriate numeric type, before using in arithmetic expressions.

* Note that the int function converts a float to an int by truncation, not by
rounding to the nearest whole number.
* Type conversion can be used to construct strings from numbers and
other strings.

Eg: Given profit = 1000.55, print it as $ 1000.55

Here, profit is a floating-point number that represents an amount of money


in dollars and cents

If we try to concatenate them the result is:

To solve this,we use the str function to convert the value of profit to a
string and then concatenate this string to the $ symbol:

* Python is a strongly typed programming language .

=> The interpreter checks data types of all operands before operators are
applied to those operands. If the type of an operand is not appropriate, the
interpreter halts execution with an error message.

Problems
1. An object’s momentum is its mass multiplied by its velocity. Write a
program that accepts an object’s mass (in kilograms) and velocity (in
meters per second) as inputs and then outputs its momentum.

2. The kinetic energy of a moving object is given by the formula KE =( 1 /


2 ) mv2 where m is the object’s mass and v is its velocity. Modify the
program1 so that it prints the object’s kinetic energy as well as its
momentum.
24/02/23
Friday

Using Functions and Modules

Python includes many useful functions, which are organized in libraries of


code called modules.

Calling Functions: Arguments and Return Values

* A function is a chunk of code that can be called by name to perform a


task.

Eg: round(6.7)

function name : round


parameter/ argument : 6.7
value returned : 7

*Functions often require arguments , that is, specific data values, to


perform their tasks. Names that refer to arguments are also known as
parameters .

- When an argument is an expression, it is first evaluated, and then its


value is passed to the function for further processing.

- Some functions have only optional arguments , some have required


arguments, and some have both required and optional arguments.

Eg: round()
- When called with just one argument, the round function exhibits its
default behavior , which is to return the nearest whole number with a
fractional part of 0.

- However, when a second, optional argument is supplied, this argument, a


number, indicates the number of places of precision to which the first
argument should be rounded.
Eg: round(7.563, 2) returns 7.56 .
* Each argument passed to a function has a specific data type.

=> A program that attempts to pass an argument of the wrong data type to
a function will usually generate an error.

For example, one cannot take the square root of a string, but only of a
number.

* When a function completes its task, the function may send a result back
to the part of the program that called that function in the first place.

The process of sending a result back to another part of a program is


known as returning a value.

Python modules

* Simply, module is a file containing a set of functions you want to include


in your application.

* To create a module just save the code you want in a file with the file
extension .py

def greeting(name):
print("Hello, " + name)

* A module allows you to logically organize your Python code. Grouping


related code into a module makes the code easier to understand and use.

* You can use any Python source file as a module by executing an import
statement in some other Python source file.

When the interpreter encounters an import statement, it imports the


module

import mymodule

mymodule.greeting("Jonathan")
When using a function from a module, use the syntax:
module_name.function_name

* There are several built-in modules in Python, which you can import
whenever you like.

1.The math Module

* The math module includes several functions that perform basic


mathematical operations.

To import math module:


>>>import math

To list its resources:


>>> dir(math)

Using functions from the module

>>> math.pi
3.1415926535897931

>>> math.sqrt(2)
1.4142135623730951

To get help on a function:

>>> help(math.cos)

* If you are going to use only a couple of a module’s resources frequently,


then you may import it as:

>>> from math import pi, sqrt


>>> print(pi, sqrt(2))
3.14159265359 1.41421356237

Generally, the first technique of importing resources (that is, importing just
the module’s name) is preferred.
Problems

1. Write a program that calculates and prints the number of minutes in a


year.
2. Light travels at 3 *108 meters per second. A light-year is the distance a
light beam travels in one year. Write a program that calculates and displays
the value of a light-year.

3. An employee’s total weekly pay equals the hourly wage multiplied by


the total number of regular hours plus any overtime pay. Overtime pay
equals the total overtime hours multiplied by 1.5 times the hourly wage.
Write a program that takes as inputs the hourly wage, total regular hours,
and total overtime hours and displays an employee’s total weekly pay.
Control statements
Control statements are statements that allow the computer to select or
repeat an action:

The for Loop

*Loops repeat an action.

Each repetition of the action is known as a pass or an iteration

*There are two types of loops

- those that repeat an action a predefined number of times ( definite


iteration )

- those that perform the action until the program determines that it needs to
stop ( indefinite iteration )

Syntax:

for <variable> in range(<an integer expression>):


<statement-1>
.
.
<statement-n>

Semantics:

*The first line of code in a loop is called the loop header. The colon (:)
ends the loop header.
The integer expression, in it denotes the number of iterations that the
loop performs. It counts from 0 to the value of the header’s integer
expression minus 1. On each pass through the loop, the header’s variable
is bound to the current value of this count.

*The loop body comprises the statements in the remaining lines of code,
below the header. These statements are executed in sequence on each pass
through the loop.
*The statements in the loop body must be indented and aligned in the
same column

Illustraion
1. WAP to implement python exponentiation operator .

Count-controlled loops

* Loops that count through a range of numbers are also called count-
controlled loops. The value of the count on each pass is often used in
computations.

Illustartion
Q. WAP to find the factorial of a number.
* To count from an explicit lower bound, the programmer can supply a
second integer expression in the loop header. When two arguments are
supplied to range, the count ranges from the first argument to the second
argument minus 1.

Now the synax becomes:

Q. WAP to sum all the numbers between a lower and upper limit.

Augmented Assignment

* The assignment symbol can be combined with the arithmetic and


concatenation operators to provide augmented assignment operations .
Synatx:
<variable> <operator> = <expression>

Semantics:
<variable> = <variable> <operator> <expression>

Off-by-One Error

* The error is that, the loop fails to perform the expected number of
iterations.

* Off-by-one errors mostly result when the programmer incorrectly


specifies the upper bound of the loop.

The programmer might intend the above loop to count from 1 through 4,
but it counts from 1 through 3.

* Note that this is not a syntax error, but rather a logic error. Logic
errors are not detected by the Python interpreter.

Loops That Count Down

* you can use a third argument in the range() function, namely step
argument to specify the step value.

* When the step argument is a negative number, the range function


generates a sequence of numbers from the first argument down to the
second argument plus 1

Problems

1. Write a loop that prints your name 100 times. Each output should begin
on a new line.

2. WAP to find multiples of 7 between the range 100 to 300.

Formatting Text for Output

* The total number of data characters and additional spaces for a given
datum in a formatted string is called its field width.

* Python includes a general formatting mechanism that allows the


programmer to specify field widths for different types of data.
* Synatx:

<format string> % <datum>

% i s the format operator

* To format a string data value, we use the notation

%<field width>s

in the format string.

- When the field width is positive, the datum is right-justified; when the
field width is negative, you get left-justification.
- If the field width is less than or equal to the datum’s print length in
characters, no justification is added.

* To format integers, you use the letter d.

* To format a sequence of data values, you construct a format string that


includes a format code for each datum and place the data values
in a tuple following the % operator.

Syntax:

<format string> % (<datum–1>, ..., <datum–n>)

* The format information for a data value of type float has the form

%<field width>.<precision>f
27/02/2023
Monday

Selection: if and if-else Statements

* Selection statements, allow a computer to make choices among


instruction execution, based on the testing of some conditions.

The Boolean Type, Comparisons, and Boolean Expressions

* In Python, Boolean literals are written as: True and False

* Simple Boolean expressions consist of the Boolean values True or False ,


variables bound to those values, function calls that return Boolean values,
or comparisons.

* The result of the comparison is a Boolean value. We need comaparison


in selction statements to make decisions.
if-else Statements

* The if-else statement is the most common type of selection statement.

* It is also called a two-way selection statement , because it directs the


computer to make a choice between two alternative courses of action.

Synatx:

* The condition in the if-else statement must be a Boolean expression—


that is, an expression that evaluates to either true or false.

* The two possible actions each consist of a sequence of statements.


- Note that each sequence must be indented at least one space beyond the
symbols if and else .
* There is a colon (:) following the condition and the word else

Semantics:

Problems:

1. WAP to print the maximum and minimum of two input numbers.

2. Write a Python code to check whether a given year is a leap year or not
[An year is a leap year if it’s divisible by 4 but not divisible by 100 except
for those divisible by 400].
One-Way Selection Statements

* The simplest form of selection is the if statement .

* Syntax:

- it consists of a condition and just a single sequence of statements


- If the condition is True , the sequence of statements is run. Otherwise,
control proceeds to the next statement following the entire selection
statement.

* Semantics:

* Simple if statements are often used to prevent an action from being


performed if a condition is not right.

Multi-Way if Statements

* The process of testing several conditions and responding accordingly can


be described in code by a multi-way selection statement .

* Syntax:
- The multi-way if statement considers each condition until one evaluates
to True or they all evaluate to False .

- When a condition evaluates to True , the corresponding action is


performed and control skips to the end of the entire selection statement.

- If no condition evaluates to True , then the action after the trailing else is
performed.

* Semantics:

Problems

1. WAP to find the biggest among three numbers.


2. WAP to implement following simple grading scheme that is based on
two assumptions: that numeric grades can range from 0 to 100 and that the
letter grades are A, B, C, and F.

Logical Operators and Compound Boolean Expressions

* Boolean operators can be combined using following logical operators.


* Illustration
Conditional Iteration: The while Loop

* Some times the number of iterations in a loop is unpredictable. Then we


do conditional iteration, meaning that the process continues to repeat as
long as a condition remains true.

* Conditional iteration requires that a condition be tested within the loop to


determine whether the loop should continue. Such a condition is called the
loop’s continuation condition.

* If the continuation condition is false, the loop ends. If the continuation


condition is true, the statements within the loop are executed again.

* Syntax:

while <condition>:
<sequence of statements>

- At least one statement in the body of the loop must update a variable that
affects the value of the condition. Otherwise, the loop will continue
forever, an error known as an infinite loop.

* Semantics:
* Illustartion

* There are two input statements, one just before the loop header and one
at the bottom of the loop body.

-The first input statement initializes a variable to a value that the loop
condition can test. This variable is also called the loop control variable

- The second input statement obtains the other input values, including one
that will terminate the loop.

Count Control with a while Loop

* You can also use a while


loop for a count-controlled
loop
Problems

Q1. WAP to count to count down from 10 to 1

The while True Loop and the break Statement

* It is possible to simplify while loop’s structure and thus improve its


readability using break statement.

- This loop’s structure can be simplified if we receive the first input inside
the loop and break out of the loop if a test shows that the continuation
condition is false.

- This implies postponing the actual test until the middle of the loop.

- Python includes a break statement that will allow us to make this change
in the program.

Illustarion:

* In cases where the body of the loop must execute at least once, this
technique simplifies the code and actually makes the program’s logic
clearer.
Random Numbers

* Many situations, such as games, include some randomness in the choices


that are made.

* To simulate randomness in computer applications, programming


languages include resources for generating random numbers .

* Python’s random module supports several ways to do this.

- The easiest is to call the function random.randint with two integer


arguments.

- The function random.randint returns a random number from among the


numbers between the two arguments and including those numbers.

Illustration: Simulating the randomness of die tossing experiment

You might also like