This document discusses different types of loops in Python including definite loops using for statements, indefinite loops using while statements, and different patterns for indefinite loops like interactive loops, sentinel loops, and end-of-file loops. It provides examples of using accumulators and loop variables to iterate over a sequence of user-entered numbers and calculate the average. Key loop concepts like pre-test loops, priming reads, and avoiding infinite loops are also covered.
Python interpreter and interactive mode, debugging; values and types: int, float, boolean, string, and list; variables, expressions, statements, tuple assignment, precedence of operators, comments; Illustrative programs: exchange the values of two variables, circulate the values of n variables, distance between two points.
This book is short and thorough introduction to Python math programming for programmers starting out. This book concise to the point and delivers its content well. For more information, visit programinator.weebly.com
This document discusses Python loops and string manipulation. It covers while loops, using a loop counter to repeat code a specified number of times. It also discusses slicing strings to access characters or substrings, checking if a string contains a character, and calling string methods like lower(), upper(), and replace() to manipulate strings.
The document provides information on various decision making and looping constructs in Python like if, else, elif, for, while loops. It explains the syntax and usage of these statements with examples. Key decision making constructs covered include if-else, if-elif-else statements. Looping constructs covered include for loops over sequences, range function to generate sequences, while loops, break and continue keywords in loops. Nested if statements and usage of else block with for and while loops are also discussed.
02 Control Structures - Loops & ConditionsEbad Qureshi
Complete Course Available at: https://github.com/Ebad8931/PythonWorkshop
Basic Concepts of Loops and Conditional Statements in Python are introduced in the presentation. Also covers How to get input from the Console and includes interactive Problems.
Looping statements allow executing code multiple times. There are different types of looping statements like for, while, and nested loops. The for loop iterates over a sequence like a list or string. It runs the block of code for each item in the sequence. The while loop repeats a block of code as long as a condition is true. Nested loops allow placing one loop within another loop to iterate multiple times.
This document contains examples of using for loops and while loops in MATLAB. It begins with examples of summing prime numbers, duplicating vector elements, and converting a for loop to a while loop. It then provides more examples of using loops to calculate interest, convert a matrix to a vector, print patterns of stars, and find twin prime numbers. It discusses the importance of efficiency in MATLAB and compares loop-based approaches to vectorized solutions.
The document discusses different types of loop structures in C programming, specifically focusing on the for loop. It provides the general form of a for loop statement, explains the initialize, test, and increment expressions, and gives examples of using multiple statements and initializing multiple variables within a for loop body. It also provides an example of a for loop to print the multiplication table of a user-input number a specified number of times.
CMIS 102 Hands-On Lab
// Week 4
Overview:
This hands-on lab allows you to follow and experiment with the critical steps of developing a program including the program description, analysis, test plan, design (using both flow chart and pseudocode visualization), and implementation with C code. The example provided uses sequential, selection and repetition statements.
Program Description:
This program will calculate the sum of 10 integers. The program will ask the user to 10 integers. If the sum of the numbers is greater than 1000, a message is printed stating the sum is over 1000. The design step will include both pseudocode and flow chart visualization.
Analysis:
I will use sequential, selection and repetition programming statements.
I will define three integer numbers: count, value, sum. Count will store how many times values are entered to make sure we don’t exceed 10 values. Value will store the input integer and sum will store the running sum.
The sum will be calculated by this formula:
sum = sum + value
For example, if the first value entered was 4 and second was 10:
sum = sum + value = 0 + 4
sum = 4 + 10 = 14
Values and sum can be input and calculated within a repetition loop:
while count <10
Input value
sum = sum + value
End while
The additional selection statement will be of this form:
If sum > 1000 then
print "Sum is over 1000"
End If
Test Plan:
To verify this program is working properly the input values could be used for testing:
Test Case
Input
Expected Output
1
value=1
value=1
value=1
value=0
value=1
value=2
value=0
value=1
value=3
value=2
Sum = 12
2
value=100
value=100
value=100
value=100
value=100
value=200
value=200
value=200
value=200
value=200
Sum = 1200
Sum is over 1000.
3
value=-100
value=-100
value=-200
value=0
value=200
value=100
value=0
value=200
value=-300
value=-200
Sum = -400
Pseudocode:
// This program will calculate the sum of 10 integers.
// Declare variables
Declare count, value, sum as Integer
//Initialize Counter, Sum to 0
Set count=0
Set sum = 0
// Loop through 10 integers
While count < 10
Print “Enter an Integer”
Input value
sum = sum + value
count=count+1
End While
// Print results and messages
Print “Sum is “ + sum
If (sum > 1000)
Printf “Sum is over 1000”
End if
Flow Chart:
C Code
The following is the C Code that will compile in execute in the online compilers.
// C code
// This program will calculate the sum of 10 integers.
// Developer: Faculty CMIS102
// Date: Jan 31, 2014
#include <stdio.h>
int main ()
{
/* variable definition: */
int count, value, sum;
/* Initialize count and sum */
count = 0;
sum = 0;
// Loop through to input values
while (count < 10)
{
printf("Enter an Integer\n");
scanf("%d", &value);
sum = sum + value;
count = count + 1;
}
printf("Sum is %d\n " , sum );
if (sum >1000)
printf("Sum is over 1000\n");
return 0;
}
Setting up the code and the input parameters in ideone.com:
Note the input integer.
Python is a general purpose programming language that can be used for both programming and scripting. It is an interpreted language, meaning code is executed line by line by the Python interpreter. Python code is written in plain text files with a .py extension. Key features of Python include being object-oriented, using indentation for code blocks rather than brackets, and having a large standard library. Python code can be used for tasks like system scripting, web development, data analysis, and more.
The document discusses different types of loops in Python including while loops, for loops, and infinite loops. It provides examples of using while loops to iterate until a condition is met, using for loops to iterate over a set of elements when the number of iterations is known, and how to terminate loops early using break or skip iterations using continue. It also discusses using the range() function to generate a sequence of numbers to iterate over in for loops.
This document discusses algorithms and flowcharts. It provides examples of algorithms to calculate the sum and average of grades, find the maximum value, count occurrences of zeroes, and find matches. It also explains the three types of control structures for algorithms - sequence, branching, and looping. Additionally, it describes the basic symbols used in flowcharts and provides examples of flowcharts for algorithms to calculate area of a circle and convert temperatures.
C++ Loops General Discussion of Loops A loop is a.docxhumphrieskalyn
C++ Loops
General Discussion of Loops
A loop is a programming construct that allows a group of statements, called the loop body, to be
executed zero or more times. For example, a loop might cause a group of statements to be executed
12 times.
A loop is controlled in part by the loop continuation condition. As long as the loop continuation
condition remains true, the loop will continue to execute. In order for a loop to stop, it must have a
terminating action, i.e. statement(s) in the loop body which when executed insure that the
continuation condition will eventually become false.
A loop control variable is a variable whose change may cause the continuation condition to
become false. A common error is to not initialize the control variable. To help ensure that the loop
does not become an infinite loop, always make sure to do the following three things with the LCV
(loop control variable):
1) Initialize the LCV, almost always done before the loop.
2) Test the LCV, this is done inside the continuation condition.
3) Update or change the LCV, inside the loop body.
There are three kinds of loops that are commonly available in programming languages.
1) The while loop executes an indefinite and possibly zero number of repetitions.
2) The do-while loop executes an indefinite number of times, but always at least once.
3) The for loop is convenient when the number of repetitions is known in advance.
C++ Loops
The above three loop types are available in C and C++, but the while loop is the most often used;
lets see some examples.
Example 1: A while loop that determines the number of digits in a positive integer, N. Assume that
N has previously been declared and given a value.
int Copy = N; // don’t want to destroy N!
DigitCount = 1; // all numbers have at least 1 digit
while ( Copy >= 10) // count the rest of the digits
{
++DigitCount; // found one more digit
Copy /= 10; // get rid of rightmost digit
}
When the loop finishes, DigitCount holds the number of digits in the integer N.
Example 2: A do-while loop that determines the number of digits in integer, N, same as above.
int Copy = N; // don’t destroy original N
DigitCount = 0; // do-while loop will increment this at least once
do
{
++DigitCount; // found one more digit
Copy /= 10; // get rid of rightmost digit
}
while ( Copy != 0); // count the rest of the digits. Note the ‘;’
A for loop could also be used to count digits, but let’s instead look at an example more suited to the
strong points of the for loop.
Example 3: A loop to print all of the upper case letters.
char Ch;
for ( Ch = ‘A’; Ch <= ‘Z’; ++Ch )
cout << Ch;
This loop is equivalent to the following while loop:
char Ch;
Ch = ‘A’;
while ( Ch <= ‘Z’ )
{
cout << Ch;
++Ch;
}
The following rules are used by C++ when executing ...
The document discusses different types of loops in Java including while, do-while, for, nested, and loops using break and continue statements. It provides examples of a guessing game program using a do-while loop that repeatedly prompts the user for a guess and checks if it matches a random number. It also gives short code examples demonstrating the basic syntax of for, nested, and loops with break and continue.
This document summarizes the contents of the second day of a hands-on workshop on the Python programming language. It discusses indentation, the range function, for and while loops, conditional statements like if/elif, and modules for math, time, and random variables. Example code is provided to demonstrate various Python concepts like loops, logical operators, and comparisons between Python and C/C++ programming.
The document discusses loops in Python, including while and for loops. It provides examples of using while loops to find the largest number input by a user and count even and odd numbers. It also demonstrates using for loops with the range() function, and using break and continue statements to change loop flow. The else block that can be used with while and for loops is also covered.
In this PPT you will learn how to use looping in python.
For more presentation in any subject please contact us on
[email protected].
You get a new presentation every Sunday at 10 AM.
Learn more about Python by clicking on given below link
Python Introduction- https://www.slideshare.net/RaginiJain21/final-presentation-on-python
Basic concept of Python -https://www.slideshare.net/RaginiJain21/python-second-ppt
Python Datatypes - https://www.slideshare.net/RaginiJain21/data-types-in-python-248466302
Python Library & Module - https://www.slideshare.net/RaginiJain21/python-libraries-and-modules
Basic Python Programs- https://www.slideshare.net/RaginiJain21/basic-python-programs
Python Media Libarary - https://www.slideshare.net/RaginiJain21/python-media-library
The document discusses while loops in programming. It defines a while loop as a structure that executes a sequence of instructions multiple times. It explains that while loops are used when the number of repetitions is unknown and cannot be calculated in advance. The document provides examples of using while loops with loop counters to run code a specific number of times and examples of infinite loops. It also discusses using the break statement to exit a loop early.
In this chapter we will examine the loop programming constructs through which we can execute a code snippet repeatedly. We will discuss how to implement conditional repetitions (while and do-while loops) and how to work with for-loops. We will give examples of different possibilities to define loops, how to construct them and some of their key usages. Finally, we will discuss the foreach-loop construct and how we can use multiple loops placed inside each other (nested loops).
Difference Between Normal & Smart/Automated HomeRuchika Sinha
Difference Between Normal Home & Smart/Automated Home.
In this we have discussed about the key differences, operational availability, problem statement, further enhancement
Greedy Algorithms WITH Activity Selection Problem.pptRuchika Sinha
An Activity Selection Problem
The activity selection problem is a mathematical optimization problem. Our first illustration is the problem of scheduling a resource among several challenge activities. We find a greedy algorithm provides a well designed and simple method for selecting a maximum- size set of manually compatible activities.
Ad
More Related Content
Similar to Python Programming Introduction - Loops & Boolean (20)
02 Control Structures - Loops & ConditionsEbad Qureshi
Complete Course Available at: https://github.com/Ebad8931/PythonWorkshop
Basic Concepts of Loops and Conditional Statements in Python are introduced in the presentation. Also covers How to get input from the Console and includes interactive Problems.
Looping statements allow executing code multiple times. There are different types of looping statements like for, while, and nested loops. The for loop iterates over a sequence like a list or string. It runs the block of code for each item in the sequence. The while loop repeats a block of code as long as a condition is true. Nested loops allow placing one loop within another loop to iterate multiple times.
This document contains examples of using for loops and while loops in MATLAB. It begins with examples of summing prime numbers, duplicating vector elements, and converting a for loop to a while loop. It then provides more examples of using loops to calculate interest, convert a matrix to a vector, print patterns of stars, and find twin prime numbers. It discusses the importance of efficiency in MATLAB and compares loop-based approaches to vectorized solutions.
The document discusses different types of loop structures in C programming, specifically focusing on the for loop. It provides the general form of a for loop statement, explains the initialize, test, and increment expressions, and gives examples of using multiple statements and initializing multiple variables within a for loop body. It also provides an example of a for loop to print the multiplication table of a user-input number a specified number of times.
CMIS 102 Hands-On Lab
// Week 4
Overview:
This hands-on lab allows you to follow and experiment with the critical steps of developing a program including the program description, analysis, test plan, design (using both flow chart and pseudocode visualization), and implementation with C code. The example provided uses sequential, selection and repetition statements.
Program Description:
This program will calculate the sum of 10 integers. The program will ask the user to 10 integers. If the sum of the numbers is greater than 1000, a message is printed stating the sum is over 1000. The design step will include both pseudocode and flow chart visualization.
Analysis:
I will use sequential, selection and repetition programming statements.
I will define three integer numbers: count, value, sum. Count will store how many times values are entered to make sure we don’t exceed 10 values. Value will store the input integer and sum will store the running sum.
The sum will be calculated by this formula:
sum = sum + value
For example, if the first value entered was 4 and second was 10:
sum = sum + value = 0 + 4
sum = 4 + 10 = 14
Values and sum can be input and calculated within a repetition loop:
while count <10
Input value
sum = sum + value
End while
The additional selection statement will be of this form:
If sum > 1000 then
print "Sum is over 1000"
End If
Test Plan:
To verify this program is working properly the input values could be used for testing:
Test Case
Input
Expected Output
1
value=1
value=1
value=1
value=0
value=1
value=2
value=0
value=1
value=3
value=2
Sum = 12
2
value=100
value=100
value=100
value=100
value=100
value=200
value=200
value=200
value=200
value=200
Sum = 1200
Sum is over 1000.
3
value=-100
value=-100
value=-200
value=0
value=200
value=100
value=0
value=200
value=-300
value=-200
Sum = -400
Pseudocode:
// This program will calculate the sum of 10 integers.
// Declare variables
Declare count, value, sum as Integer
//Initialize Counter, Sum to 0
Set count=0
Set sum = 0
// Loop through 10 integers
While count < 10
Print “Enter an Integer”
Input value
sum = sum + value
count=count+1
End While
// Print results and messages
Print “Sum is “ + sum
If (sum > 1000)
Printf “Sum is over 1000”
End if
Flow Chart:
C Code
The following is the C Code that will compile in execute in the online compilers.
// C code
// This program will calculate the sum of 10 integers.
// Developer: Faculty CMIS102
// Date: Jan 31, 2014
#include <stdio.h>
int main ()
{
/* variable definition: */
int count, value, sum;
/* Initialize count and sum */
count = 0;
sum = 0;
// Loop through to input values
while (count < 10)
{
printf("Enter an Integer\n");
scanf("%d", &value);
sum = sum + value;
count = count + 1;
}
printf("Sum is %d\n " , sum );
if (sum >1000)
printf("Sum is over 1000\n");
return 0;
}
Setting up the code and the input parameters in ideone.com:
Note the input integer.
Python is a general purpose programming language that can be used for both programming and scripting. It is an interpreted language, meaning code is executed line by line by the Python interpreter. Python code is written in plain text files with a .py extension. Key features of Python include being object-oriented, using indentation for code blocks rather than brackets, and having a large standard library. Python code can be used for tasks like system scripting, web development, data analysis, and more.
The document discusses different types of loops in Python including while loops, for loops, and infinite loops. It provides examples of using while loops to iterate until a condition is met, using for loops to iterate over a set of elements when the number of iterations is known, and how to terminate loops early using break or skip iterations using continue. It also discusses using the range() function to generate a sequence of numbers to iterate over in for loops.
This document discusses algorithms and flowcharts. It provides examples of algorithms to calculate the sum and average of grades, find the maximum value, count occurrences of zeroes, and find matches. It also explains the three types of control structures for algorithms - sequence, branching, and looping. Additionally, it describes the basic symbols used in flowcharts and provides examples of flowcharts for algorithms to calculate area of a circle and convert temperatures.
C++ Loops General Discussion of Loops A loop is a.docxhumphrieskalyn
C++ Loops
General Discussion of Loops
A loop is a programming construct that allows a group of statements, called the loop body, to be
executed zero or more times. For example, a loop might cause a group of statements to be executed
12 times.
A loop is controlled in part by the loop continuation condition. As long as the loop continuation
condition remains true, the loop will continue to execute. In order for a loop to stop, it must have a
terminating action, i.e. statement(s) in the loop body which when executed insure that the
continuation condition will eventually become false.
A loop control variable is a variable whose change may cause the continuation condition to
become false. A common error is to not initialize the control variable. To help ensure that the loop
does not become an infinite loop, always make sure to do the following three things with the LCV
(loop control variable):
1) Initialize the LCV, almost always done before the loop.
2) Test the LCV, this is done inside the continuation condition.
3) Update or change the LCV, inside the loop body.
There are three kinds of loops that are commonly available in programming languages.
1) The while loop executes an indefinite and possibly zero number of repetitions.
2) The do-while loop executes an indefinite number of times, but always at least once.
3) The for loop is convenient when the number of repetitions is known in advance.
C++ Loops
The above three loop types are available in C and C++, but the while loop is the most often used;
lets see some examples.
Example 1: A while loop that determines the number of digits in a positive integer, N. Assume that
N has previously been declared and given a value.
int Copy = N; // don’t want to destroy N!
DigitCount = 1; // all numbers have at least 1 digit
while ( Copy >= 10) // count the rest of the digits
{
++DigitCount; // found one more digit
Copy /= 10; // get rid of rightmost digit
}
When the loop finishes, DigitCount holds the number of digits in the integer N.
Example 2: A do-while loop that determines the number of digits in integer, N, same as above.
int Copy = N; // don’t destroy original N
DigitCount = 0; // do-while loop will increment this at least once
do
{
++DigitCount; // found one more digit
Copy /= 10; // get rid of rightmost digit
}
while ( Copy != 0); // count the rest of the digits. Note the ‘;’
A for loop could also be used to count digits, but let’s instead look at an example more suited to the
strong points of the for loop.
Example 3: A loop to print all of the upper case letters.
char Ch;
for ( Ch = ‘A’; Ch <= ‘Z’; ++Ch )
cout << Ch;
This loop is equivalent to the following while loop:
char Ch;
Ch = ‘A’;
while ( Ch <= ‘Z’ )
{
cout << Ch;
++Ch;
}
The following rules are used by C++ when executing ...
The document discusses different types of loops in Java including while, do-while, for, nested, and loops using break and continue statements. It provides examples of a guessing game program using a do-while loop that repeatedly prompts the user for a guess and checks if it matches a random number. It also gives short code examples demonstrating the basic syntax of for, nested, and loops with break and continue.
This document summarizes the contents of the second day of a hands-on workshop on the Python programming language. It discusses indentation, the range function, for and while loops, conditional statements like if/elif, and modules for math, time, and random variables. Example code is provided to demonstrate various Python concepts like loops, logical operators, and comparisons between Python and C/C++ programming.
The document discusses loops in Python, including while and for loops. It provides examples of using while loops to find the largest number input by a user and count even and odd numbers. It also demonstrates using for loops with the range() function, and using break and continue statements to change loop flow. The else block that can be used with while and for loops is also covered.
In this PPT you will learn how to use looping in python.
For more presentation in any subject please contact us on
[email protected].
You get a new presentation every Sunday at 10 AM.
Learn more about Python by clicking on given below link
Python Introduction- https://www.slideshare.net/RaginiJain21/final-presentation-on-python
Basic concept of Python -https://www.slideshare.net/RaginiJain21/python-second-ppt
Python Datatypes - https://www.slideshare.net/RaginiJain21/data-types-in-python-248466302
Python Library & Module - https://www.slideshare.net/RaginiJain21/python-libraries-and-modules
Basic Python Programs- https://www.slideshare.net/RaginiJain21/basic-python-programs
Python Media Libarary - https://www.slideshare.net/RaginiJain21/python-media-library
The document discusses while loops in programming. It defines a while loop as a structure that executes a sequence of instructions multiple times. It explains that while loops are used when the number of repetitions is unknown and cannot be calculated in advance. The document provides examples of using while loops with loop counters to run code a specific number of times and examples of infinite loops. It also discusses using the break statement to exit a loop early.
In this chapter we will examine the loop programming constructs through which we can execute a code snippet repeatedly. We will discuss how to implement conditional repetitions (while and do-while loops) and how to work with for-loops. We will give examples of different possibilities to define loops, how to construct them and some of their key usages. Finally, we will discuss the foreach-loop construct and how we can use multiple loops placed inside each other (nested loops).
Difference Between Normal & Smart/Automated HomeRuchika Sinha
Difference Between Normal Home & Smart/Automated Home.
In this we have discussed about the key differences, operational availability, problem statement, further enhancement
Greedy Algorithms WITH Activity Selection Problem.pptRuchika Sinha
An Activity Selection Problem
The activity selection problem is a mathematical optimization problem. Our first illustration is the problem of scheduling a resource among several challenge activities. We find a greedy algorithm provides a well designed and simple method for selecting a maximum- size set of manually compatible activities.
A greedy algorithm is any algorithm that follows the problem-solving heuristic of making the locally optimal choice at each stage.
A greedy algorithm is an approach for solving a problem by selecting the best option available at the moment.
The document discusses the 0-1 knapsack problem and provides an example of solving it using dynamic programming. The 0-1 knapsack problem aims to maximize the total value of items selected from a list that have a total weight less than or equal to the knapsack's capacity, where each item must either be fully included or excluded. The document outlines a dynamic programming algorithm that builds a table to store the maximum value for each item subset at each possible weight, recursively considering whether or not to include each additional item.
Dijkstra's algorithm finds the shortest paths between vertices in a graph with non-negative edge weights. It works by maintaining distances from the source vertex to all other vertices, initially setting all distances to infinity except the source which is 0. It then iteratively selects the unvisited vertex with the lowest distance, marks it as visited, and updates the distances to its neighbors if a shorter path is found through the selected vertex. This continues until all vertices are visited, at which point the distances will be the shortest paths from the source vertex.
Greedy with Task Scheduling Algorithm.pptRuchika Sinha
A greedy algorithm is any algorithm that follows the problem-solving heuristic of making the locally optimal choice at each stage. In many problems, a greedy strategy does not produce an optimal solution, but a greedy heuristic can yield locally optimal solutions that approximate a globally optimal solution in a reasonable amount of time
When we have to display a large portion of the picture, then not only scaling & translation is necessary, the visible part of picture is also identified. This process is not easy. Certain parts of the image are inside, while others are partially inside. The lines or elements which are partially visible will be omitted.
For deciding the visible and invisible portion, a particular process called clipping is used. Clipping determines each element into the visible and invisible portion. Visible portion is selected. An invisible portion is discarded.
Intel Corporation is an American multinational corporation and technology company headquartered in Santa Clara, California. It is the world's largest semiconductor chip manufacturer by revenue, and is the developer of the x86 series of microprocessors, the processors found in most personal computers
The main components of a PC and its purpose
Good price ranges for each component
Good options for each component
Cost breakdown for building a
PC Safety for assembly
How to wire a PC
Where each component goes
This document discusses computer casing and hardware. It defines computer casing as the box-like case that contains a computer's electronic components. It describes the main types of casings as desktop, mini tower, mid-size tower, and full-size tower. Each type is defined and their advantages/disadvantages listed. The parts of a computer case are identified as the front panel, back panel, and internal parts. Three factors that influence computer case design are identified as ergonomics, expansion capabilities, and cooling.
A motherboard is the main printed circuit board in general-purpose computers and other expandable systems. It holds and allows communication between many of the crucial electronic components of a system, such as the central processing unit and memory, and provides connectors for other peripherals.
In graph theory, the shortest path problem is the problem of finding a path between two vertices in a graph such that the sum of the weights of its constituent edges is minimized
The Bellman–Ford algorithm is an algorithm that computes shortest paths from a single source vertex to all of the other vertices in a weighted digraph. It is slower than Dijkstra's algorithm for the same problem, but more versatile, as it is capable of handling graphs in which some of the edge weights are negative numbers.
Python is an interpreted high-level general-purpose programming language. Its design philosophy emphasizes code readability with its use of significant indentation. Its language constructs as well as its object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects
Python allows importing and using classes and functions defined in other files through modules. There are three main ways to import modules: import somefile imports everything and requires prefixing names with the module name, from somefile import * imports everything without prefixes, and from somefile import className imports a specific class. Modules look for files in directories listed in sys.path.
Classes define custom data types by storing shared data and methods. Instances are created using class() and initialized with __init__. Self refers to the instance inside methods. Attributes store an instance's data while class attributes are shared. Inheritance allows subclasses to extend and redefine parent class features. Special built-in methods control class behaviors like string representation or iteration.
Optimization problems can be divided into two categories, depending on whether the variables are continuous or discrete:
An optimization problem with discrete variables is known as a discrete optimization, in which an object such as an integer, permutation or graph must be found from a countable set.
A problem with continuous variables is known as a continuous optimization, in which an optimal value from a continuous function must be found. They can include constrained problems and multimodal problems.
A grammar is said to be regular, if the production is in the form -
A → αB,
A -> a,
A → ε,
for A, B ∈ N, a ∈ Σ, and ε the empty string
A regular grammar is a 4 tuple -
G = (V, Σ, P, S)
V - It is non-empty, finite set of non-terminal symbols,
Σ - finite set of terminal symbols, (Σ ∈ V),
P - a finite set of productions or rules,
S - start symbol, S ∈ (V - Σ)
Software testing is a process that evaluates the functionality and quality of software. It involves examining software through various testing types and processes to verify it meets requirements and is error-free. The main types of software testing include static vs dynamic, black box vs white box, automated vs manual, and regression testing. The goal of testing is to identify bugs and ensure the software works as intended.
Backtracking is an algorithmic-technique for solving problems recursively by trying to build a solution incrementally, one piece at a time, removing those solutions that fail to satisfy the constraints of the problem at any point of time
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYijscai
With the increased use of Artificial Intelligence (AI) in malware analysis there is also an increased need to
understand the decisions models make when identifying malicious artifacts. Explainable AI (XAI) becomes
the answer to interpreting the decision-making process that AI malware analysis models use to determine
malicious benign samples to gain trust that in a production environment, the system is able to catch
malware. With any cyber innovation brings a new set of challenges and literature soon came out about XAI
as a new attack vector. Adversarial XAI (AdvXAI) is a relatively new concept but with AI applications in
many sectors, it is crucial to quickly respond to the attack surface that it creates. This paper seeks to
conceptualize a theoretical framework focused on addressing AdvXAI in malware analysis in an effort to
balance explainability with security. Following this framework, designing a machine with an AI malware
detection and analysis model will ensure that it can effectively analyze malware, explain how it came to its
decision, and be built securely to avoid adversarial attacks and manipulations. The framework focuses on
choosing malware datasets to train the model, choosing the AI model, choosing an XAI technique,
implementing AdvXAI defensive measures, and continually evaluating the model. This framework will
significantly contribute to automated malware detection and XAI efforts allowing for secure systems that
are resilient to adversarial attacks.
π0.5: a Vision-Language-Action Model with Open-World GeneralizationNABLAS株式会社
今回の資料「Transfusion / π0 / π0.5」は、画像・言語・アクションを統合するロボット基盤モデルについて紹介しています。
拡散×自己回帰を融合したTransformerをベースに、π0.5ではオープンワールドでの推論・計画も可能に。
This presentation introduces robot foundation models that integrate vision, language, and action.
Built on a Transformer combining diffusion and autoregression, π0.5 enables reasoning and planning in open-world settings.
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...Infopitaara
A feed water heater is a device used in power plants to preheat water before it enters the boiler. It plays a critical role in improving the overall efficiency of the power generation process, especially in thermal power plants.
🔧 Function of a Feed Water Heater:
It uses steam extracted from the turbine to preheat the feed water.
This reduces the fuel required to convert water into steam in the boiler.
It supports Regenerative Rankine Cycle, increasing plant efficiency.
🔍 Types of Feed Water Heaters:
Open Feed Water Heater (Direct Contact)
Steam and water come into direct contact.
Mixing occurs, and heat is transferred directly.
Common in low-pressure stages.
Closed Feed Water Heater (Surface Type)
Steam and water are separated by tubes.
Heat is transferred through tube walls.
Common in high-pressure systems.
⚙️ Advantages:
Improves thermal efficiency.
Reduces fuel consumption.
Lowers thermal stress on boiler components.
Minimizes corrosion by removing dissolved gases.
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...Infopitaara
A Boiler Feed Pump (BFP) is a critical component in thermal power plants. It supplies high-pressure water (feedwater) to the boiler, ensuring continuous steam generation.
⚙️ How a Boiler Feed Pump Works
Water Collection:
Feedwater is collected from the deaerator or feedwater tank.
Pressurization:
The pump increases water pressure using multiple impellers/stages in centrifugal types.
Discharge to Boiler:
Pressurized water is then supplied to the boiler drum or economizer section, depending on design.
🌀 Types of Boiler Feed Pumps
Centrifugal Pumps (most common):
Multistage for higher pressure.
Used in large thermal power stations.
Positive Displacement Pumps (less common):
For smaller or specific applications.
Precise flow control but less efficient for large volumes.
🛠️ Key Operations and Controls
Recirculation Line: Protects the pump from overheating at low flow.
Throttle Valve: Regulates flow based on boiler demand.
Control System: Often automated via DCS/PLC for variable load conditions.
Sealing & Cooling Systems: Prevent leakage and maintain pump health.
⚠️ Common BFP Issues
Cavitation due to low NPSH (Net Positive Suction Head).
Seal or bearing failure.
Overheating from improper flow or recirculation.
Value Stream Mapping Worskshops for Intelligent Continuous SecurityMarc Hornbeek
This presentation provides detailed guidance and tools for conducting Current State and Future State Value Stream Mapping workshops for Intelligent Continuous Security.
☁️ GDG Cloud Munich: Build With AI Workshop - Introduction to Vertex AI! ☁️
Join us for an exciting #BuildWithAi workshop on the 28th of April, 2025 at the Google Office in Munich!
Dive into the world of AI with our "Introduction to Vertex AI" session, presented by Google Cloud expert Randy Gupta.
Sorting Order and Stability in Sorting.
Concept of Internal and External Sorting.
Bubble Sort,
Insertion Sort,
Selection Sort,
Quick Sort and
Merge Sort,
Radix Sort, and
Shell Sort,
External Sorting, Time complexity analysis of Sorting Algorithms.
Fluid mechanics is the branch of physics concerned with the mechanics of fluids (liquids, gases, and plasmas) and the forces on them. Originally applied to water (hydromechanics), it found applications in a wide range of disciplines, including mechanical, aerospace, civil, chemical, and biomedical engineering, as well as geophysics, oceanography, meteorology, astrophysics, and biology.
It can be divided into fluid statics, the study of various fluids at rest, and fluid dynamics.
Fluid statics, also known as hydrostatics, is the study of fluids at rest, specifically when there's no relative motion between fluid particles. It focuses on the conditions under which fluids are in stable equilibrium and doesn't involve fluid motion.
Fluid kinematics is the branch of fluid mechanics that focuses on describing and analyzing the motion of fluids, such as liquids and gases, without considering the forces that cause the motion. It deals with the geometrical and temporal aspects of fluid flow, including velocity and acceleration. Fluid dynamics, on the other hand, considers the forces acting on the fluid.
Fluid dynamics is the study of the effect of forces on fluid motion. It is a branch of continuum mechanics, a subject which models matter without using the information that it is made out of atoms; that is, it models matter from a macroscopic viewpoint rather than from microscopic.
Fluid mechanics, especially fluid dynamics, is an active field of research, typically mathematically complex. Many problems are partly or wholly unsolved and are best addressed by numerical methods, typically using computers. A modern discipline, called computational fluid dynamics (CFD), is devoted to this approach. Particle image velocimetry, an experimental method for visualizing and analyzing fluid flow, also takes advantage of the highly visual nature of fluid flow.
Fundamentally, every fluid mechanical system is assumed to obey the basic laws :
Conservation of mass
Conservation of energy
Conservation of momentum
The continuum assumption
For example, the assumption that mass is conserved means that for any fixed control volume (for example, a spherical volume)—enclosed by a control surface—the rate of change of the mass contained in that volume is equal to the rate at which mass is passing through the surface from outside to inside, minus the rate at which mass is passing from inside to outside. This can be expressed as an equation in integral form over the control volume.
The continuum assumption is an idealization of continuum mechanics under which fluids can be treated as continuous, even though, on a microscopic scale, they are composed of molecules. Under the continuum assumption, macroscopic (observed/measurable) properties such as density, pressure, temperature, and bulk velocity are taken to be well-defined at "infinitesimal" volume elements—small in comparison to the characteristic length scale of the system, but large in comparison to molecular length scale
Raish Khanji GTU 8th sem Internship Report.pdfRaishKhanji
This report details the practical experiences gained during an internship at Indo German Tool
Room, Ahmedabad. The internship provided hands-on training in various manufacturing technologies, encompassing both conventional and advanced techniques. Significant emphasis was placed on machining processes, including operation and fundamental
understanding of lathe and milling machines. Furthermore, the internship incorporated
modern welding technology, notably through the application of an Augmented Reality (AR)
simulator, offering a safe and effective environment for skill development. Exposure to
industrial automation was achieved through practical exercises in Programmable Logic Controllers (PLCs) using Siemens TIA software and direct operation of industrial robots
utilizing teach pendants. The principles and practical aspects of Computer Numerical Control
(CNC) technology were also explored. Complementing these manufacturing processes, the
internship included extensive application of SolidWorks software for design and modeling tasks. This comprehensive practical training has provided a foundational understanding of
key aspects of modern manufacturing and design, enhancing the technical proficiency and readiness for future engineering endeavors.
Concept of Problem Solving, Introduction to Algorithms, Characteristics of Algorithms, Introduction to Data Structure, Data Structure Classification (Linear and Non-linear, Static and Dynamic, Persistent and Ephemeral data structures), Time complexity and Space complexity, Asymptotic Notation - The Big-O, Omega and Theta notation, Algorithmic upper bounds, lower bounds, Best, Worst and Average case analysis of an Algorithm, Abstract Data Types (ADT)
2. 2
Objectives
To understand the concepts of definite
and indefinite loops as they are realized
in the Python for and while
statements.
To understand the programming
patterns interactive loop and sentinel
loop and their implementations using a
Python while statement.
3. 3
Objectives
To understand the programming
pattern end-of-file loop and ways of
implementing such loops in Python.
To be able to design and implement
solutions to problems involving loop
patterns including nested loop
structures.
4. 4
Objectives
To understand the basic ideas of
Boolean algebra and be able to analyze
and write Boolean expressions involving
Boolean operators.
5. 5
For Loops: A Quick Review
The for statement allows us to iterate
through a sequence of values.
for <var> in <sequence>:
<body>
The loop index variable var takes on
each successive value in the sequence,
and the statements in the body of the
loop are executed once for each value.
6. 6
For Loops: A Quick Review
Suppose we want to write a program that can
compute the average of a series of numbers
entered by the user.
To make the program general, it should work
with any size set of numbers.
We don’t need to keep track of each number
entered, we only need know the running sum
and how many numbers have been added.
7. 7
For Loops: A Quick Review
We’ve run into some of these things
before!
A series of numbers could be handled by
some sort of loop. If there are n numbers,
the loop should execute n times.
We need a running sum. This will use an
accumulator.
8. 8
For Loops: A Quick Review
Input the count of the
numbers, n
Initialize sum to 0
Loop n times
Input a number, x
Add x to sum
Output average as sum/n
9. 9
For Loops: A Quick Review
# average1.py
# A program to average a set of numbers
# Illustrates counted loop with accumulator
def main():
n = eval(input("How many numbers do you have? "))
sum = 0.0
for i in range(n):
x = eval(input("Enter a number >> "))
sum = sum + x
print("nThe average of the numbers is", sum / n)
Note that sum is initialized to 0.0 so that sum/n returns a float!
10. 10
For Loops: A Quick Review
How many numbers do you have? 5
Enter a number >> 32
Enter a number >> 45
Enter a number >> 34
Enter a number >> 76
Enter a number >> 45
The average of the numbers is 46.4
11. 11
Indefinite Loops
That last program got the job done, but you
need to know ahead of time how many
numbers you’ll be dealing with.
What we need is a way for the computer to
take care of counting how many numbers
there are.
The for loop is a definite loop, meaning that
the number of iterations is determined when
the loop starts.
12. 12
Indefinite Loops
We can’t use a definite loop unless we
know the number of iterations ahead of
time. We can’t know how many
iterations we need until all the numbers
have been entered.
We need another tool!
The indefinite or conditional loop keeps
iterating until certain conditions are
met.
13. 13
Indefinite Loops
while <condition>:
<body>
condition is a Boolean expression, just like
in if statements. The body is a sequence of
one or more statements.
Semantically, the body of the loop executes
repeatedly as long as the condition remains
true. When the condition is false, the loop
terminates.
14. 14
Indefinite Loops
The condition is tested at the top of the loop.
This is known as a pre-test loop. If the
condition is initially false, the loop body will
not execute at all.
15. 15
Indefinite Loop
Here’s an example of a while loop
that counts from 0 to 10:
i = 0
while i <= 10:
print(i)
i = i + 1
The code has the same output as this
for loop:
for i in range(11):
print(i)
16. 16
Indefinite Loop
The while loop requires us to manage
the loop variable i by initializing it to 0
before the loop and incrementing it at
the bottom of the body.
In the for loop this is handled
automatically.
17. 17
Indefinite Loop
The while statement is simple, but yet
powerful and dangerous – they are a
common source of program errors.
i = 0
while i <= 10:
print(i)
What happens with this code?
18. 18
Indefinite Loop
When Python gets to this loop, i is
equal to 0, which is less than 10, so the
body of the loop is executed, printing 0.
Now control returns to the condition,
and since i is still 0, the loop repeats,
etc.
This is an example of an infinite loop.
19. 19
Indefinite Loop
What should you do if you’re caught in
an infinite loop?
First, try pressing control-c
If that doesn’t work, try control-alt-delete
If that doesn’t work, push the reset
button!
20. 20
Interactive Loops
One good use of the indefinite loop is to write
interactive loops. Interactive loops allow a
user to repeat certain portions of a program
on demand.
Remember how we said we needed a way for
the computer to keep track of how many
numbers had been entered? Let’s use
another accumulator, called count.
21. 21
Interactive Loops
At each iteration of the loop, ask the user if
there is more data to process. We need to
preset it to “yes” to go through the loop the
first time.
set moredata to “yes”
while moredata is “yes”
get the next data item
process the item
ask user if there is moredata
22. 22
Interactive Loops
Combining the interactive loop pattern with
accumulators for sum and count:
initialize sum to 0.0
initialize count to 0
set moredata to “yes”
while moredata is “yes”
input a number, x
add x to sum
add 1 to count
ask user if there is moredata
output sum/count
23. 23
Interactive Loops
# average2.py
# A program to average a set of numbers
# Illustrates interactive loop with two accumulators
def main():
moredata = "yes"
sum = 0.0
count = 0
while moredata[0] == 'y':
x = eval(input("Enter a number >> "))
sum = sum + x
count = count + 1
moredata = input("Do you have more numbers (yes or no)? ")
print("nThe average of the numbers is", sum / count)
Using string indexing (moredata[0]) allows us to
accept “y”, “yes”, “yeah” to continue the loop
24. 24
Interactive Loops
Enter a number >> 32
Do you have more numbers (yes or no)? y
Enter a number >> 45
Do you have more numbers (yes or no)? yes
Enter a number >> 34
Do you have more numbers (yes or no)? yup
Enter a number >> 76
Do you have more numbers (yes or no)? y
Enter a number >> 45
Do you have more numbers (yes or no)? nah
The average of the numbers is 46.4
25. 25
Sentinel Loops
A sentinel loop continues to process
data until reaching a special value that
signals the end.
This special value is called the sentinel.
The sentinel must be distinguishable
from the data since it is not processed
as part of the data.
26. 26
Sentinel Loops
get the first data item
while item is not the sentinel
process the item
get the next data item
The first item is retrieved before the loop
starts. This is sometimes called the priming
read, since it gets the process started.
If the first item is the sentinel, the loop
terminates and no data is processed.
Otherwise, the item is processed and the next
one is read.
27. 27
Sentinel Loops
In our averaging example, assume we
are averaging test scores.
We can assume that there will be no
score below 0, so a negative number
will be the sentinel.
28. 28
Sentinel Loops
# average3.py
# A program to average a set of numbers
# Illustrates sentinel loop using negative input as sentinel
def main():
sum = 0.0
count = 0
x = eval(input("Enter a number (negative to quit) >> "))
while x >= 0:
sum = sum + x
count = count + 1
x = eval(input("Enter a number (negative to quit) >> "))
print("nThe average of the numbers is", sum / count)
29. 29
Sentinel Loops
Enter a number (negative to quit) >> 32
Enter a number (negative to quit) >> 45
Enter a number (negative to quit) >> 34
Enter a number (negative to quit) >> 76
Enter a number (negative to quit) >> 45
Enter a number (negative to quit) >> -1
The average of the numbers is 46.4
30. 30
Sentinel Loops
This version provides the ease of use of
the interactive loop without the hassle
of typing ‘y’ all the time.
There’s still a shortcoming – using this
method we can’t average a set of
positive and negative numbers.
If we do this, our sentinel can no longer
be a number.
31. 31
Sentinel Loops
We could input all the information as
strings.
Valid input would be converted into
numeric form. Use a character-based
sentinel.
We could use the empty string (“”)!
32. 32
Sentinel Loops
initialize sum to 0.0
initialize count to 0
input data item as a string, xStr
while xStr is not empty
convert xStr to a number, x
add x to sum
add 1 to count
input next data item as a string, xStr
Output sum / count
33. 33
Sentinel Loops
# average4.py
# A program to average a set of numbers
# Illustrates sentinel loop using empty string as sentinel
def main():
sum = 0.0
count = 0
xStr = input("Enter a number (<Enter> to quit) >> ")
while xStr != "":
x = eval(xStr)
sum = sum + x
count = count + 1
xStr = input("Enter a number (<Enter> to quit) >> ")
print("nThe average of the numbers is", sum / count)
34. 34
Sentinel Loops
Enter a number (<Enter> to quit) >> 34
Enter a number (<Enter> to quit) >> 23
Enter a number (<Enter> to quit) >> 0
Enter a number (<Enter> to quit) >> -25
Enter a number (<Enter> to quit) >> -34.4
Enter a number (<Enter> to quit) >> 22.7
Enter a number (<Enter> to quit) >>
The average of the numbers is 3.38333333333
35. 35
File Loops
The biggest disadvantage of our
program at this point is that they are
interactive.
What happens if you make a typo on
number 43 out of 50?
A better solution for large data sets is
to read the data from a file.
36. 36
File Loops
# average5.py
# Computes the average of numbers listed in a file.
def main():
fileName = input("What file are the numbers in? ")
infile = open(fileName,'r')
sum = 0.0
count = 0
for line in infile.readlines():
sum = sum + eval(line)
count = count + 1
print("nThe average of the numbers is", sum / count)
37. 37
File Loops
Many languages don’t have a
mechanism for looping through a file
like this. Rather, they use a sentinel!
We could use readline in a loop to
get the next line of the file.
At the end of the file, readline
returns an empty string, “”
38. 38
File Loops
line = infile.readline()
while line != ""
#process line
line = infile.readline()
Does this code correctly handle the
case where there’s a blank line in the
file?
Yes. An empty line actually ends with
the newline character, and readline
includes the newline. “n” != “”
39. 39
File Loops
# average6.py
# Computes the average of numbers listed in a file.
def main():
fileName = input("What file are the numbers in? ")
infile = open(fileName,'r')
sum = 0.0
count = 0
line = infile.readline()
while line != "":
sum = sum + eval(line)
count = count + 1
line = infile.readline()
print("nThe average of the numbers is", sum / count)
40. 40
Nested Loops
In the last chapter we saw how we
could nest if statements. We can also
nest loops.
Suppose we change our specification to
allow any number of numbers on a line
in the file (separated by commas),
rather than one per line.
41. 41
Nested Loops
At the top level, we will use a file-
processing loop that computes a
running sum and count.
sum = 0.0
count = 0
line = infile.readline()
while line != "":
#update sum and count for values in line
line = infile.readline()
print("nThe average of the numbers is", sum/count)
42. 42
Nested Loops
In the next level in we need to update the
sum and count in the body of the loop.
Since each line of the file contains one or
more numbers separated by commas, we can
split the string into substrings, each of which
represents a number.
Then we need to loop through the substrings,
convert each to a number, and add it to sum.
We also need to update count.
43. 43
Nested Loops
for xStr in line.split(","):
sum = sum + eval(xStr)
count = count + 1
Notice that this for statement uses
line, which is also the loop control
variable for the outer loop.
44. 44
Nested Loops
# average7.py
# Computes the average of numbers listed in a file.
# Works with multiple numbers on a line.
import string
def main():
fileName = input("What file are the numbers in? ")
infile = open(fileName,'r')
sum = 0.0
count = 0
line = infile.readline()
while line != "":
for xStr in line.split(","):
sum = sum + eval(xStr)
count = count + 1
line = infile.readline()
print("nThe average of the numbers is", sum / count)
45. 45
Nested Loops
The loop that processes the numbers in each
line is indented inside of the file processing
loop.
The outer while loop iterates once for each
line of the file.
For each iteration of the outer loop, the inner
for loop iterates as many times as there are
numbers on the line.
When the inner loop finishes, the next line of
the file is read, and this process begins again.
46. 46
Nested Loops
Designing nested loops –
Design the outer loop without worrying
about what goes inside
Design what goes inside, ignoring the
outer loop.
Put the pieces together, preserving the
nesting.
47. 47
Computing with Booleans
if and while both use Boolean
expressions.
Boolean expressions evaluate to True
or False.
So far we’ve used Boolean expressions
to compare two values, e.g.
(while x >= 0)
48. 48
Boolean Operators
Sometimes our simple expressions do
not seem expressive enough.
Suppose you need to determine
whether two points are in the same
position – their x coordinates are equal
and their y coordinates are equal.
49. 49
Boolean Operators
if p1.getX() == p2.getX():
if p1.getY() == p2.getY():
# points are the same
else:
# points are different
else:
# points are different
Clearly, this is an awkward way to evaluate
multiple Boolean expressions!
Let’s check out the three Boolean operators
and, or, and not.
50. 50
Boolean Operators
The Boolean operators and and or are
used to combine two Boolean
expressions and produce a Boolean
result.
<expr> and <expr>
<expr> or <expr>
51. 51
Boolean Operators
The and of two expressions is true exactly
when both of the expressions are true.
We can represent this in a truth table.
P Q P and Q
T T T
T F F
F T F
F F F
52. 52
Boolean Expressions
In the truth table, P and Q represent
smaller Boolean expressions.
Since each expression has two possible
values, there are four possible
combinations of values.
The last column gives the value of P
and Q.
53. 53
Boolean Expressions
The or of two expressions is true when
either expression is true.
P Q P or Q
T T T
T F T
F T T
F F F
54. 54
Boolean Expressions
The only time or is false is when both
expressions are false.
Also, note that or is true when both
expressions are true. This isn’t how we
normally use “or” in language.
55. 55
Boolean Operators
The not operator computes the opposite of
a Boolean expression.
not is a unary operator, meaning it
operates on a single expression.
P not P
T F
F T
56. 56
Boolean Operators
We can put these operators together to
make arbitrarily complex Boolean
expressions.
The interpretation of the expressions
relies on the precedence rules for the
operators.
57. 57
Boolean Operators
Consider a or not b and c
How should this be evaluated?
The order of precedence, from high to low, is
not, and, or.
This statement is equivalent to
(a or ((not b) and c))
Since most people don’t memorize the the
Boolean precedence rules, use parentheses to
prevent confusion.
58. 58
Boolean Operators
To test for the co-location of two
points, we could use an and.
if p1.getX() == p2.getX() and p2.getY() == p1.getY():
# points are the same
else:
# points are different
The entire condition will be true only
when both of the simpler conditions are
true.
59. 59
Boolean Operators
Say you’re writing a racquetball simulation.
The game is over as soon as either player has
scored 15 points.
How can you represent that in a Boolean
expression?
scoreA == 15 or scoreB == 15
When either of the conditions becomes true,
the entire expression is true. If neither
condition is true, the expression is false.
60. 60
Boolean Operators
We want to construct a loop that
continues as long as the game is not
over.
You can do this by taking the negation
of the game-over condition as your loop
condition!
while not(scoreA == 15 or scoreB == 15):
#continue playing
61. 61
Boolean Operators
Some racquetball players also use a
shutout condition to end the game,
where if one player has scored 7 points
and the other person hasn’t scored yet,
the game is over.
while not(scoreA == 15 or scoreB == 15 or
(scoreA == 7 and scoreB == 0) or (scoreB == 7 and scoreA == 0):
#continue playing
62. 62
Boolean Operators
Let’s look at volleyball scoring. To win,
a volleyball team needs to win by at
least two points.
In volleyball, a team wins at 15 points
If the score is 15 – 14, play continues,
just as it does for 21 – 20.
(a >= 15 and a - b >= 2) or (b >= 15 and b - a >= 2)
(a >= 15 or b >= 15) and abs(a - b) >= 2
63. 63
Boolean Algebra
The ability to formulate, manipulate,
and reason with Boolean expressions is
an important skill.
Boolean expressions obey certain
algebraic laws called Boolean logic or
Boolean algebra.
64. 64
Boolean Algebra
and has properties similar to multiplication
or has properties similar to addition
0 and 1 correspond to false and true,
respectively.
Algebra Boolean algebra
a * 0 = 0 a and false == false
a * 1 = a a and true == a
a + 0 = a a or false == a
65. 65
Boolean Algebra
Anything ored with true is true:
a or true == true
Both and and or distribute:
a or (b and c) == (a or b) and (a or c)
a and (b or c) == (a and b) or (a and c)
Double negatives cancel out:
not(not a) == a
DeMorgan’s laws:
not(a or b) == (not a) and (not b)
not(a and b) == (not a) or (not b)
66. 66
Boolean Algebra
We can use these rules to simplify our
Boolean expressions.
while not(scoreA == 15 or scoreB == 15):
#continue playing
This is saying something like “While it is not
the case that player A has 15 or player B has
15, continue playing.”
Applying DeMorgan’s law:
while (not scoreA == 15) and (not scoreB == 15):
#continue playing
67. 67
Boolean Algebra
This becomes:
while scoreA != 15 and scoreB != 15
# continue playing
Isn’t this easier to understand? “While
player A has not reached 15 and player
B has not reached 15, continue
playing.”
68. 68
Boolean Algebra
Sometimes it’s easier to figure out when a
loop should stop, rather than when the loop
should continue.
In this case, write the loop termination
condition and put a not in front of it. After a
couple applications of DeMorgan’s law you
are ready to go with a simpler but equivalent
expression.
69. 69
Other Common Structures
The if and while can be used to
express every conceivable algorithm.
For certain problems, an alternative
structure can be convenient.
70. 70
Post-Test Loop
Say we want to write a program that is
supposed to get a nonnegative number
from the user.
If the user types an incorrect input, the
program asks for another value.
This process continues until a valid
value has been entered.
This process is input validation.
72. 72
Post-Test Loop
When the condition test comes after the
body of the loop it’s called a post-test
loop.
A post-test loop always executes the
body of the code at least once.
Python doesn’t have a built-in
statement to do this, but we can do it
with a slightly modified while loop.
73. 73
Post-Test Loop
We seed the loop condition so we’re
guaranteed to execute the loop once.
number = -1
while number < 0:
number = eval(input("Enter a positive number: "))
By setting number to –1, we force the
loop body to execute at least once.
74. 74
Post-Test Loop
Some programmers prefer to simulate a
post-test loop by using the Python
break statement.
Executing break causes Python to
immediately exit the enclosing loop.
break is sometimes used to exit what
looks like an infinite loop.
75. 75
Post-Test Loop
The same algorithm implemented with
a break:
while True:
number = eval(input("Enter a positive number: "))
if x >= 0: break # Exit loop if number is valid
A while loop continues as long as the
expression evaluates to true. Since
True always evaluates to true, it looks
like an infinite loop!
76. 76
Post-Test Loop
When the value of x is nonnegative, the
break statement executes, which
terminates the loop.
If the body of an if is only one line
long, you can place it right after the :!
Wouldn’t it be nice if the program gave
a warning when the input was invalid?
77. 77
Post-Test Loop
In the while loop version, this is
awkward:
number = -1
while number < 0:
number = eval(input("Enter a positive number: "))
if number < 0:
print("The number you entered was not positive")
We’re doing the validity check in two
places!
78. 78
Post-Test Loop
Adding the warning to the break
version only adds an else statement:
while True:
number = eval(input("Enter a positive number: "))
if x >= 0:
break # Exit loop if number is valid
else:
print("The number you entered was not positive.")
79. 79
Loop and a Half
Stylistically, some programmers prefer
the following approach:
while True:
number = eval(input("Enter a positive number: "))
if x >= 0: break # Loop exit
print("The number you entered was not positive")
Here the loop exit is in the middle of
the loop body. This is what we mean by
a loop and a half.
80. 80
Loop and a Half
The loop and a half is an elegant way to
avoid the priming read in a sentinel
loop.
while True:
get next data item
if the item is the sentinel: break
process the item
This method is faithful to the idea of
the sentinel loop, the sentinel value is
not processed!
82. 82
Loop and a Half
To use or not use break. That is the
question!
The use of break is mostly a matter of
style and taste.
Avoid using break often within loops,
because the logic of a loop is hard to
follow when there are multiple exits.
83. 83
Boolean Expressions
as Decisions
Boolean expressions can be used as
control structures themselves.
Suppose you’re writing a program that
keeps going as long as the user enters
a response that starts with ‘y’ (like our
interactive loop).
One way you could do it:
while response[0] == "y" or response[0] == "Y":
84. 84
Boolean Expressions
as Decisions
Be careful! You can’t take shortcuts:
while response[0] == "y" or "Y":
Why doesn’t this work?
Python has a bool type that internally uses 1
and 0 to represent True and False,
respectively.
The Python condition operators, like ==,
always evaluate to a value of type bool.
85. 85
Boolean Expressions
as Decisions
However, Python will let you evaluate
any built-in data type as a Boolean. For
numbers (int, float, and long ints), zero
is considered False, anything else is
considered True.
87. 87
Boolean Expressions
as Decisions
An empty sequence is interpreted as
False while any non-empty sequence
is taken to mean True.
The Boolean operators have operational
definitions that make them useful for
other purposes.
88. 88
Boolean Expressions
as Decisions
Operator Operational
definition
x and y If x is false, return x.
Otherwise, return y.
x or y If x is true, return x.
Otherwise, return y.
not x If x is false, return True.
Otherwise, return False.
89. 89
Boolean Expressions
as Decisions
Consider x and y. In order for this to be
true, both x and y must be true.
As soon as one of them is found to be
false, we know the expression as a
whole is false and we don’t need to
finish evaluating the expression.
So, if x is false, Python should return a
false result, namely x.
90. 90
Boolean Expressions
as Decisions
If x is true, then whether the
expression as a whole is true or false
depends on y.
By returning y, if y is true, then true is
returned. If y is false, then false is
returned.
91. 91
Boolean Expressions
as Decisions
These definitions show that Python’s
Booleans are short-circuit operators,
meaning that a true or false is returned
as soon as the result is known.
In an and where the first expression is
false and in an or, where the first
expression is true, Python will not
evaluate the second expression.
92. 92
Boolean Expressions as
Decisions
response[0] == "y" or "Y“
The Boolean operator is combining two
operations.
Here’s an equivalent expression:
(response[0] == "y") or ("Y")
By the operational description of or, this
expression returns either True, if
response[0] equals “y”, or “Y”, both of which
are interpreted by Python as true.
93. 93
Boolean Expressions
as Decisions
Sometimes we write programs that
prompt for information but offer a
default value obtained by simply
pressing <Enter>
Since the string used by ans can be
treated as a Boolean, the code can be
further simplified.
94. 94
Boolean Expressions
as Decisions
ans = input("What flavor fo you want [vanilla]: ")
if ans:
flavor = ans
else:
flavor = "vanilla"
If the user just hits <Enter>, ans will
be an empty string, which Python
interprets as false.
95. 95
Boolean Expressions
as Decisions
We can code this even more succinctly!
ans = input("What flavor fo you want [vanilla]: ")
flavor = ans or "vanilla“
Remember, any non-empty answer is
interpreted as True.
This exercise could be boiled down into
one line!
flavor = input("What flavor do you want
[vanilla]:” ) or "vanilla"
96. 96
Boolean Expressions
as Decisions
Again, if you understand this method,
feel free to utilize it. Just make sure
that if your code is tricky, that it’s well
documented!