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

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

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Flow Control: Branches and loops

5. Selection: If and Switch Controls

INDEX. Sl. No. Programs Page No. Procedure 2. 1 To check whether person is eligible for vote or not. 2 To find the given number is even or odd 6-8

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Fourth Edition

Repetition Structures

Selection Statement ( if )

CHAPTER 5 FLOW OF CONTROL

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Introduction. C provides two styles of flow control:

Algorithm Discovery and Design. Why are Algorithms Important? Representing Algorithms. Chapter 2 Topics: What language to use?

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

C++ Programming: From Problem Analysis to Program Design, Third Edition

Chapter 4 - Notes Control Structures I (Selection)

Theory of control structures

MODULE 2: Branching and Looping

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

Introduction to Programming

CS 115 Lecture 8. Selection: the if statement. Neil Moore

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

Chapter 4. Flow of Control

Programming Training. Main Points: - Python Statements - Problems with selections.

Lab1. Introduction to Python. Lab 4: Selection Statement. Eng. Mai Z. Alyazji

Chapter 4: Control Structures I (Selection)

A Quick Review of Chapter 1

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

Loops / Repetition Statements

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

CS1100 Introduction to Programming

Score score < score < score < 65 Score < 50

Test #2 October 8, 2015

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

Course Outline. Introduction to java

Chapter 3 Problem Solving and the Computer

SNS COLLEGE OF ENGINEERING,

Decision Making -Branching. Class Incharge: S. Sasirekha

CS 111X - Fall Test 1

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures

Flow Control. So Far: Writing simple statements that get executed one after another.

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

if Statement Numeric Rela5onal Operators The if Statement Flow of Control: Branching (Savitch, Chapter 3)

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Conditional Execution

if Statement Numeric Rela7onal Operators The if Statement Flow of Control: Branching (Savitch, Chapter 3)

Control Structures 1 / 17

REPETITION CONTROL STRUCTURE LOGO

CS 111X - Fall Test 1 - KEY KEY KEY KEY KEY KEY KEY

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

CHAPTER 7 COMPOSITION AND DECOMPOSITION

Repetition Algorithms

Chapter 8. Statement-Level Control Structures

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 8 Statement-Level Control Structures

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Homework #2. If (your ID number s last two digits % 6) = 0: 6, 12, 18

Conditional Control Structures. Dr.T.Logeswari

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

AP Computer Science Principles Programming Question Tips. 1: Which algorithm/code segment achieves some result?

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Problem Solving and 'C' Programming

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

3 The L oop Control Structure

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

Topics. Chapter 5. Equality Operators

CS 1301 Exam 1 Fall 2014

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

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Control Structures. A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping

8. Control statements

Chapter 8. Statement-Level Control Structures

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Lecture 3. Input, Output and Data Types

Chapter 4: Control Structures I

Eng. Mohammed S. Abdualal

All written answers are limited to their question boxes. Make sure all answers are easily legible.

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 4: Control Structures I (Selection)

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

Programming Logic and Design Sixth Edition

Programming Fundamentals - A Modular Structured Approach using C++ By: Kenneth Leroy Busbee

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points)

An Introduction to Python

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Making Decisions In Python

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Maltepe University Computer Engineering Department. Algorithms and Programming. Chapter 4: Conditionals - If statement - Switch statement

Introduction to Computer Science Midterm 3 Fall, Points

CHAPTER 2 PROBLEM SOLVING TECHNIQUES. Mr Mohd Hatta Bin Hj Mohamed Ali Computer Programming BFC2042

Lecture 02 Making Decisions: Conditional Execution

BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17)

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1

Computer System and programming in C


Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

CPSC 3740 Programming Languages University of Lethbridge. Control Structures

C++ PROGRAMMING SKILLS Part 2 Programming Structures

Nested Selections. Chapter 8

Transcription:

Chapter 5 Conditional and Iterative Statements Statement Statement are the instructions given to the computer to perform any kind of action. Types of Statement 1. Empty Statement The which does nothing. In python an empty is pass. It takes the following form : pass wherever Python encounters a pass, Python does nothing and moves to next. 2. Simple Statement Any single executable is a simple in Python. E.g. 3. Compound Statement print( Programming ) A compound represents a group of s executed as a unit. It takes following form : <compound header> : <indented body containing multiple simple/compound s> STATEMENT FLOW CONTROL In a program, s may be executed sequentially, selectively or iteratively. Every programming language provides constructs to support sequence, selection or iteration. SEQUENCE The sequence construct means the s are being executed sequentially. Java execution starts with first, and then each is executed in turn. STATEMENT 1 STATEMENT 2 STATEMENT 3 P a g e 1 11

SELECTION The selection construct means the execution of (s) depending upon a condition-test. If a condition evaluates to true, a course of action (a set of s) is followed otherwise another course of action (a different set of s) is followed. Condition? TRUE One Course-of-action STATEMENT 1 STATEMENT 2 FALSE Another Courseofaction STATEMENT 3 STATEMENT 4 ITERATION The iteration construct means repetition of a set of s depending upon a condition-test. Till the time a condition is true, a set of s are repeated again and again. As soon as the condition becomes false, the repetition stops. The iteration construct is also called looping construct. Condition? FALSE EXIT TRUE Condition is evaluated again, And if true, given set of s are repeated. STATEMENT 1 STATEMENT 2 P a g e 2 11

The set of s that are repeated again and again is called the body of loop. PROGRAM LOGIC DEVELOPMENT TOOLS - Helps in reading and analysing the problem which needs to be solved by programming. ALGORITHM - It is a step by step procedure (well defined instructions) to solve a given problem. For instance, the algorithm for addition of two numbers is : 1. Input first number. 2. Input second number. 3. Add first number with second number and store the result in third variable. 4. Display the result. FLOWCHARTS - It is a graphical representation of an algorithm. Following symbols are used in flowcharts: - Use Data symbol for Input/Output Operation (taking input and showing output) - Use Process symbol for any type of computation and internal operations like initialization, calculation etc. - e.g. flowchart for addition of two numbers will be : P a g e 3 11

PSEUDOCODE - It is an informal language that helps programmers describe steps of a program s solution without using any programming language syntax. e.g. Pseudo code for addition of two number is : Input first number in variable a Input second number in variable b Sum = firstnumber to be added with second number Display the result DECISION TREES - These are a way of presenting rules in a hierarchical and sequential structure, where based on the hierarchy of rules, certain outcomes are predicted. THE if STATEMENTS OF PYTHON The if s are the conditional s in Python and these implement selection constructs. P a g e 4 11

The if if tests a condition and if the condition evaluates to true, it carries out some instructions and does nothing in case condition evaluates to false. if is a compound and its syntax (general form) is : if <conditional/realtional expression> : [] where a may consist of a single, a compound or just the pass. e.g.1. if ch == : print( character is space ) The above code will check whether the character variable ch stores a space or not ; if it does, then condition ch == evaluates to true and print given in second line will be executed. If however, variable ch does not store a space i.e., the condition ch == evaluates to false, then nothing will happen, no will be executed. e.g.2. ch = input( Enter a single character: ) if ch >= 0 and ch < 9 : print( You entered a digit ) The above code after getting input in ch, compares its value; if the value falls between characters 0 to 9 i.e. the condition evaluates to true, and thus execute the in the if body that is, it will print a message saying You entered a digit e.g.3. if grade == A : print( You did well ) e.g.4. Program to find the eligibility of a person for voting. Display message Eligible or Not Eligible for voting based on age entered by the user. (using if ) age = float(input( Enter your age: )) if age >= 18 : print( Eligible for voting ) if age <= 18 : print( Not Eligible for voting ) P a g e 5 11

e.g.5. Program that takes a number and checks whether the given number is odd or even. Num = int(input( Enter an integer: )) if num % 2 == 0 : print(num, is EVEN number ) if num % 2!= 0 : print(num, is ODD number ) The if-else - This form of if tests a condition and if the condition evaluates to true, it carries out s indented below if and in case condition evaluates to false, it carries out s indented below else. - The Syntax(general form) of the if-else is as shown below : if <conditional expression> : [s] [s] e.g.1. if a > 0 : print(a, is a positive number ) print(b, is a negative number ) e.g.2. Program to accept two numbers and print the largest of two numbers. x = float(input( Enter first number: )) y = float(input( Enter second number: )) if x > y : P a g e 6 11

print( largest number is,x) print( largest number is,y) e.g.3. Program to find the eligibility of a person for voting. Display message Eligible or Not Eligible for voting based on age entered by the user. age = float(input( Enter your age: )) if age >= 18 : print( Eligible for voting ) print( Not Eligible for voting ) e.g.4. Program that takes a number and checks whether the given number is odd or even. num = int(input( Enter an integer: )) if num % 2 == 0 : print(num, is EVEN number ) print(num, is ODD number ) e.g.5. Program to test the divisibility of a number with another number. num1 = int(input( Enter first number: )) num2 = int(input( Enter second number: )) rem = num1 % num2 if rem == 0 : print(num1, is divisible by, number2) print(num1, is not divisible by, number2) e.g.6. Program to display a menu for calculating area of circle or perimeter of a circle. radius = float(input( Enter radius of the circle: )) print( 1. Calculate Area ) print( 2. Calculate Perimeter ) choice = int(input( Enter your choice(1 or 2): )) if choice == 1: area = 3.14 * radius * radius print( Area of circle with radius, radius, is, area) else perm = 2 * 3.14159 * radius print( Perimeter of circle with radius, radius, is, perm) P a g e 7 11

The if elif Statement The general form of this is : if <conditional expression> : [s] elif <conditional expression> : [s] [s] e.g. 1. if runs >= 100 : print( Batsman scored a century ) elif runs >= 50 : print( Batsman scored a fifty ) print( Batsman has neither scored a century nor a fifty ) Python will test this condition in case previous condition (runs >=100) is false This block will be executed when both the if condition (i.e. runs >=100 and runs >=50 ) are false. e.g. 2. Program to accept a number from user and check whether the number is positive,negative or zero. num = float(input( Enter a number: )) if num < 0 : print(num, is a negative number ) elif num > 0 : print(num, is a positive number ) print(num, is equal to zero ) e.g. 3. Program that reads two numbers and an arithmetic operator and displays the computed result: num1 = float(input( Enter first number: )) num2 = float(input( Enter second number: )) op = input( Enter operator[+, -, *, /, %]: ) result = 0 if op == + : result = num1 + num2 elif op == - : result = num1 num2 elif op == * : P a g e 8 11

result = num1 * num2 elif op == / : result = num1 / num2 elif op == % : result = num1 % num2 print( Invalid operator!! ) print(num1,op,num2, =, result) Nested if Statement - A Nested if is an if that has another if in its if s body or in elif s body or in its else s body. P a g e 9 11

STORING CONDITIONS To make program readable, conditions in the if can be stored in name and then can be used in the if s. e.g. pos = a > 0 neg = a < 0 num = float(input( Enter a number: )) if neg : print(num, is a negative number ) elif pos : print(num, is a positive number ) print(num, is equal to zero ) Practice Questions: Q1. Correct the following code fragment: if(x == 1) k = 100 else k = 10 Q2. What will be the output of following code fragment if the input given is (i) 7 and (ii) 5? a = input( Enter a number: ) if (a == 5) : print( Five ) print( Not Five ) Q3. What is the output of following code? if ( 4 + 5 == 10) : print( TRUE ) print( FALSE ) print( TRUE ) Q4. What is the output produced by the following code? x =1 if x > 3 : if x > 4 : print( A, end= ) print( B,end= ) elif x < 2 : if (x!= 0) : P a g e 10 11

print( C, end = ) print( D ) Q5. What is the error in following code? Correct the code: weather = raining if weather = sunny : print( wear sunblock ) elif weather = snow : print( going skiing ) print(weather) Q6. What is the output of the following lines of code? if str(0) == zero : print(0); elif str(0) == 0 : print(str(0)) print( none of the above ) P a g e 11 11