Chapter 5 Conditional and Iterative Statements (Part-II) To carry out repetitive task, python provides following iterative/looping statements:

Similar documents
Chapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action.

Control Structures 1 / 17

Chapter 5 : Informatics practices. Conditional & Looping Constructs. Class XI ( As per CBSE Board)

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley

Individual research task. You should all have completed the research task set last week. Please make sure you hand it in today.

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

LOOPS. Repetition using the while statement

1. What is the minimum number of bits needed to store a single piece of data representing: a. An integer between 0 and 100?

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

Visualize ComplexCities

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

REPETITION CONTROL STRUCTURE LOGO

Introduction. C provides two styles of flow control:

B Which of the following variable names are valid/invalid (i) _main_ (ii) sum of square

Loops / Repetition Statements

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

CSC 1351 The Twelve Hour Exam From Hell

LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE

Subject: PIC Chapter 2.

CHAPTER 5 FLOW OF CONTROL

Flow Control: Branches and loops

Problem Solving and 'C' Programming

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

MODULE 2: Branching and Looping

ITERATORS AND GENERATORS 10

CSSE 120 Introduction to Software Development Practice for Test 1 paper-and-pencil part Page 1 of 6

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Repetition Algorithms

CPSC 217 Midterm (Python 3 version)

Test #2 October 8, 2015

Conditional Control Structures. Dr.T.Logeswari

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

LECTURE 5 Control Structures Part 2

CS 112: Intro to Comp Prog

Introduction to Mathematical and Scientific Programming TUTORIAL WEEK 2 (MATH 1MP3) Winter 2019

Problem Set CVO 103, Spring 2018

Algorithms and Data Structures

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

UNIT 2B An Introduction to Programming ( for -loops) Principles of Computing, Carnegie Mellon University

Programming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester

switch-case Statements

Dept. of CSE, IIT KGP

DECISION CONTROL AND LOOPING STATEMENTS

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

CHAPTER : 9 FLOW OF CONTROL

***********PYTHON PROGRAMS FOR CLASS XI ******************** """ Program to Calculate Simple Interest """ p = eval(input("enter Principle?

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

Introduction to Python (All the Basic Stuff)

Chapter 4. Flow of Control

SBT 645 Introduction to Scientific Computing in Sports Science #3

CMSC201 Computer Science I for Majors

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

CPSC 217 Midterm (Python 3 version)

CS 1110: Introduction to Computing Using Python Loop Invariants

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Comp 150 Exam 2 Overview.

Chapter 5: Control Structures

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

Name SECTION: 12:45 2:20. True or False (12 Points)

Example: Monte Carlo Simulation 1

Programming Training

3 The L oop Control Structure

fifth Solutions to Exercises 85

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Chapter 4 Repetition Structures. Dr. Zhang COSC 1436 Spring 2017 June 15, 2017

A Look Back at Arithmetic Operators: the Increment and Decrement

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control

Introduction to the Java Basics: Control Flow Statements

Advanced Computer Programming

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Repetition Structures II

Principles of Computer Science I

MEIN 50010: Python Flow Control

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Unit 5. Decision Making and Looping. School of Science and Technology INTRODUCTION

CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi

Introduction to: Computers & Programming:

Lecture 6. Statements

n Group of statements that are executed repeatedly while some condition remains true

Lecture 04 More Iteration, Nested Loops. Meet UTA Jarrett s dog Greta, lying in her nest

Building Java Programs

Notes on Chapter 1 Variables and String

Programming for Experimental Research. Flow Control

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators

Branching is deciding what actions to take and Looping is deciding how many times to take a certain action.

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Statements 2. a operator= b a = a operator b

Python Programming Language

Stacks. Revised based on textbook author s notes.

Lessons on Python Functions

Transcription:

Chapter 5 Conditional and Iterative Statements (Part-II) Iterative Statements To carry out repetitive task, python provides following iterative/looping statements: 1. Conditional loop while (condition based loop) 2. Counting loop for (loop for a given number of times) range() function range() function generates a list which is a special sequence type. The common use of range( ) is in the following form: range(lower limit, upper limit) The function in the form range(l, u) will produce a list having values starting from l, l+2, l+2 (u-1). Lower limit (l) is included in list but upper limit is not included in the list. e.g. range (0, 5) will produce list as [0, 1, 2, 3, 4] range(12, 18) will produce list as [12, 13, 14, 15, 16, 17] To produce a list with numbers having gap other than 1, the following form of range( ) function is used: range( lower limit, upper limit, step value) e.g. range(0, 10, 2) will produce list as [0, 2, 4, 6, 8 ] range(5, 0) will produce list as [5, 4, 3, 2, 1] Another form of range( ) is : range(number) that creates a list from 0 to number-1. e.g. range(5) will produce list [0, 1, 2, 3, 4] Statement range(10) range(5,10) range(3,7) range(5,15,3) range(9,3,-1) range(10,1,-2) Values generated P a g e 1 13

Operators in and not in To check whether a value is contained inside a list you can use in operator, e.g. 3 in [1, 2, 3, 4] will return true as value 3 is contained in sequence [1, 2, 3, 4] 5 in [1, 2, 3, 4] will return false as value 5 is not contained in sequence [1, 2, 3, 4] 5 not in [1, 2, 3, 4] will return true as value 5 is not contained in sequence [1, 2, 3, 4] a in trade will return True as a is contained in sequence trade ash in trash will return True for loop ends when the loop is repeated for the last value of the sequence. P a g e 2 13

e.g.1. Consider another for loop for ch in calm : print(ch) The above loop will produce output as: c a l m e.g.2. for loop that prints the square of each value in the list: for v in [1,2,3] : print(v*v*v) The above loop will produce output as: 1 8 27 When repetition/iteration is to be done over a large list, then range( ) function is to be used. e.g.1. for val in range(3, 18) : print(val) In the above loop, range(3,18) will first generate a list [3,4,5, 16,17] P a g e 3 13

e.g.2 program to print the numbers from 1 to 100. for a in range(1, 101) : print(a) e.g.3. for loop to print the series : 2, 4, 6, 8,10 for num in range(2, 12, 2) : print(num) e.g.4. for loop to print the sum of natural numbers between 1 to 7. 1+2+3+4+5+6+7 sum = 0 for n in range(1,8) sum = sum+n print( Sum of natural number between 1 and 7 is:, sum) e.g.5. for loop to print the sum of series : 1 + 3 + 5 +7 + 8 + 9 s=0 for num in range(1,11,2) s = s + num print( Sum of series is,s) e.g.6. program to print table of a number, say 5. num = 5 for a in range(1, 11) print(num, x,a, =,num*a ) The while loop A while loop is a conditional loop that will repeat the instructions within itself as long as a condition remains true. The general form of while loop is : while <logical expression> : loop body where the loop body may contain a single statement or multiple statements or an empty statement. The loop iterates(repeat) while the logical expression evaluates to true. When the expression becomes false, the program control passes to the line after the loop body. P a g e 4 13

P a g e 5 13

e.g.2. n = 1 while n < 5 : print( Square of, n, is, n*n) n += 1 print( Thank You ) The above code will print output as : Square of 1 is 1. Square of 2 is 4. Square of 3 is 9. Square of 4 is 16. Thank You P a g e 6 13

Elements of While loop 1. Initialization Expression (Starting) - Before entering in a while loop, its loop variable must be initialized. The initialization expression give the loop variable their first value. 2. Test Expression (Repeating or Stopping) - It is an expression whose truth value decides whether the loop body will be executed or not. If the test expression evaluates to true, the loop body gets executed, otherwise the loop is terminated. - In a while loop, the test expression is evaluated before entering into a loop. 3. The Body of the Loop (Doing) - The statements that are executed repeatedly form the body of the loop. - In a while loop, before every iteration the test expression is evaluated and if it is true, the body of the loop is executed; if the test expression evaluates to false, the loop is terminated. 4. Update Expression(s) (Changing) - The update expressions change the value of loop variable. - The update expression is given as a statement inside the body of while loop. Important points about while loop 1. In a while loop, a loop control variable should be initialized before the loop begins. An uninitialized variable cannot be used in an expression. P a g e 7 13

2. ** while loop is called Entry controlled loop as it controls the execution of the loop body by testing a condition. e.g.1. Code to print series from 1 to 10 using while loop. i = 1 while i <= 10 : print( i, end= ) i = i + 1 e.g.2. Code to print even numbers between 1 to 10 using while loop. 2 4 6 8 10 i = 2 while i <= 10 : print( i, end= ) i = i + 2 e.g.3. Code to print odd numbers between 10 to 1 using while loop. 9 7 5 3 1 i = 9 while i >= 1 : print( i, end= ) i = i + 2 P a g e 8 13

e.g.3. Code to print odd numbers between 1 to 10 using while loop. 1 3 5 7 9 i = 1 while i <= 9 : print( i, end= ) i = i + 2 e.g. 4. Write code using while loop to print the sum of series 1+2+3+4+.+10. 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 k = 1 sum =0 while k <= 10 : sum = sum + k k = k + 1 print( Sum of series is:, sum) e.g. 5. while loop to print factorial of a number n. 1! = 1 2! = 2 * 1 = 2 3! = 3 * 2 * 1 = 6 4!= 4 * 3 * 2 * 1 = 24 5! = 5 * 4 * 3 * 2 * 1 = 120 num = int(input( Enter a number: )) fact = 1 a =1 while a <= num : fact = fact * a a = a + 1 print( The factorial of, num, is, fact) Jump Statements break and continue Python offers two jump statements to be used within loops to jump out of loop-iterations(repetitions). These are break and continue statements. The break statement It enables a program to skip over a part of the code. A break statement terminates the very loop it lies within. Execution resumes at the statement immediately following the body of the terminated statement. P a g e 9 13

e.g. for i in range(1,5) : if i == 2 : break print(i) ** when the value of i will become 2, then i == 2 becomes true and break statement gets executed, and it stop the execution of the loop. Therefore the above code will produce the output as : 1 The continue statement Instead of forcing termination (like break statement), the continue statement forces the next iteration of the loop to take place, skipping any code in between. e.g. for i in range(1,5) : if i == 2 : continue print(i, end= ) The output of above code is : 1 3 4 P a g e 10 13

Loop else statement else clause of a Python loop executes when the loop terminates normally, i.e., when test-condition results into false for a while loop or for loop has executed for the last value in the sequence; not when the break statement terminates the loop. e.g. for a in range (1, 4) : print( Element is, end= ) print(a) print( Ending loop after printing all elements of sequence ) The above code will give the following output: Element is 1 Element is 2 Element is 3 Ending loop after printing all elements of sequence Now consider the same loop as above but with a break statement: Now the output is: for a in range (1, 4) : if a % 2 == 0 : break print( Element is, end= ) print(a) print( Ending loop after printing all elements of sequence ) Element is 1 Question: Program to input a number and test if it is a prime number. num = int(input( Enter number: )) lim = int(num/2)+1 for i in range (2, lim) rem = num % i if rem == 0: print(num, is not a prime number ) break else: print(num, is a prime number ) P a g e 11 13

Practice Questions Q1. What is the output of the following code fragment? for a in abcde : print(a, +, end= ) Q2. What is the output of the following code fragment? for i in range (0,10) : pass print(i) Q3. Why does Hello not print even once? for i in range(10, 1) : print( Hello ) Q4. Predict the output of the following code fragments: (a) count = 0 while count < 10 : print( Hello ) count+=1 (b) x = 10 y = 0 while x > y : print(x, y) x = x 1 y = y + 1 (c) x = 45 while x < 50 : print(x) (d) for x in [1,2,3] : for y in [4,5,6] : print(x, y) (e) keepgoing = True x = 100 while keepgoing : print(x) x = x 10 if x < 50 : keepgoing = False Q5. Rewrite the following code fragments using for loop : (a) i = 100 while (i > 0) : print(i) i -= 3 (b) while num > 0 : print(num % 10) num = num/10 P a g e 12 13

Q6. What is following code doing? What would it print for input as 3? n = int (input( Enter an integer: )) if n < 1 : print( invalid value ) for i in range(1, n+1) : print(i*i) Q7. Consider the following python program: N = int(input( Enter N: )) i = 1 sum = 0 while i < N : if i % 2 == 0 : sum = sum + i i = i + 1 print(sum) (a) What is the output when the input value is 5? (b) What is the output when the input value is 0? Q8. Consider below given two code fragments. What will be their outputs if the inputs are entered in the given order are (i) Jacob (ii) 12345 (iii) END (iv) end? (a) name = while True : name = input( Enter name( end to exit): ) if name == end : break print( Hello, name) print( Wasn t it fun? ) (b) name = while name! = end : name = input( Enter name( end to exit): ) if name == end : pass print( Hello, name) print( Wasn t it fun? ) ****************** P a g e 13 13