Control flow statements

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


Conditional Expressions and Decision Statements

Selection Statement ( if )

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

CONTROL AND HIGHER ORDER FUNCTIONS 1

ENGR 101 Engineering Design Workshop

CS Name : Grading TA:

Flow Control. CSC215 Lecture

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

Introduction. C provides two styles of flow control:

Visualize ComplexCities

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

Lecture 3 (02/06, 02/08): Condition Statements Decision, Operations & Information Technologies Robert H. Smith School of Business Spring, 2017

Python BASICS. Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc.

Algorithms and Data Structures

Conditionals and Recursion. Python Part 4

Fundamentals of Programming (Python) Getting Started with Programming

Text Input and Conditionals

Algorithm. Building blocks of algorithm

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

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Geophysics 501. Computa3onal Methods for the Geosciences. Flow Control and Lists. Zach Zens

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Tensorflow Example: Fizzbuzz. Sargur N. Srihari

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

Hello, World! An Easy Intro to Python & Programming. Jack Rosenthal

Basic Python Revision Notes With help from Nitish Mittal

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

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.

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

Internet & World Wide Web How to Program, 5/e by Pearson Education, Inc. All Rights Reserved.

1 Docstrings. COSC 101 Lecture #14 Handout: Defining Functions, Part 4 Spring 2015

CS 112: Intro to Comp Prog

Branching. Chapter 5 11/14/16 & 11/15/16

Problem Solving and 'C' Programming

Structure and Interpretation of Computer Programs

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0

Control of Flow. There are several Python expressions that control the flow of a program. All of them make use of Boolean conditional tests.

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Impera've Programming

BRANCHING if-else statements

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Introduction to Computer Programming for Non-Majors

MODULE 2: Branching and Looping

Fundamentals of Programming (Python) Control Structures. Sina Sajadmanesh Sharif University of Technology Fall 2017

Beyond Blocks: Python Session #1

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

OCR Pseudocode to Python

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Introduction to Python (All the Basic Stuff)

Here n is a variable name. The value of that variable is 176.

HW3: CS 110X C Domain Information. Final Version: 1/29/2014

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

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


Ruby: Introduction, Basics

Intro. Scheme Basics. scm> 5 5. scm>

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

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Python Programming: An Introduction to Computer Science

Introduction to Computer Programming for Non-Majors

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

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

Python Activity 5: Boolean Expressions and Selection Statements

CMSC 201 Spring 2018

Introduction to Computer Programming for Non-Majors

5. Selection: If and Switch Controls

Python Programming: An Introduction to Computer Science

YEAH 2: Simple Java! Avery Wang Jared Bitz 7/6/2018

Lecture 4 8/24/18. Expressing Procedural Knowledge. Procedural Knowledge. What are we going to cover today? Computational Constructs

Flow Control: Branches and loops

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

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

Control Structures 1 / 17

CMSC201 Computer Science I for Majors

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

MEIN 50010: Python Flow Control

Outline. 1 If Statement. 2 While Statement. 3 For Statement. 4 Nesting. 5 Applications. 6 Other Conditional and Loop Constructs 2 / 19

Ruby: Introduction, Basics

SCoLang - Language Reference Manual

Decision Making -Branching. Class Incharge: S. Sasirekha

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

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

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

THE AUSTRALIAN NATIONAL UNIVERSITY Mid Semester Examination September COMP1730 / COMP6730 Programming for Scientists

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

CS101: Intro to Computing Summer Week 2

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

SFU CMPT Topic: Control Statements

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

Real Python: Python 3 Cheat Sheet

(Python) Chapter 3: Repetition

Loops (while and for)

COE 212 Engineering Programming. Welcome to Exam II Monday May 13, 2013

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

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

CSE 115. Introduction to Computer Science I

Transcription:

Control flow statements It is important to make decisions in programming about how your code will be looked at. You may need to be selective, iterative or repetitive with the code statements. Python provides us some control flow statements as mentioned below to do this task. a) if-elif-else ladder to make decisions b) for loop for iteration and repetition c) while loop for selective repetition In addition to this it also offers some keywords like break, continue, pass for further control. if-else condition For decision making if-else condition is the option python provides. To understand it's importance let us look at the example below: # Example: Voter application validation age = int(input("dear applicant, please enter your age: ")) if age>18: print("your application is accepted.") print("you are underage now. Please come back later.") In this example the program control does not flow over both the print statements. The selection here is based on a Boolean condition following if keyword. If the condition outcome is True it selects the statement under 'if block' otherwise under 'else block'. The same would have been very difficult without it. Furthermore, if more such conditions participate in the selection process the keyword use is elif, which is like 'else if'. Syntax: if Boolean_condition: True statement elif Boolean_condition: True statement elif Boolean_condition: True statement False statement Note: else nevers takes a condition and is not compulsory in the above decision making ladder. Ternary operator: A one-liner shortcut to if-else condition Syntax: if- True if condition else False

if-elif- True_for_if if cond1 else True_for_elif if cond2 else False # Example: Equilateral triangle sidea, sideb, sidec = -3,-3,-3 if sidea == sideb == sidec and sidea>0: print("it is equilateral") print("not an equilateral") # Same code with ternary operatot print("it is equilateral") if sidea == sideb == sidec and sidea>0 else prin t("not an equilateral") for loop for loop servers two important purposes: a) repeated execution of a code block b) iteration over sequence Example for i in range(3): print("line 1") print("line 2") Line 1 Line 2 Line 1 Line 2 Line 1 Line 2 for i in "hello": h e l l o Deep-dive into for loop 1. 'for' is a keyword to define 'for loop'. 2. 'i' is just a variable name which can be replaced with any other varibale not defined in the same scope. 3. 'in' is another keyword and membership operator which returns True if the operand is present in the sequence, otherwise it return False. 4. Last part in the 'for loop' definition is a sequence object like string, list or tuple. range() function also defines a sequence object. Syntax: range(start=0,end=len(sequence),step=1) list(range(1,5))

list(range(1,5)) [0,1,2,3,4] list(range(1,10,2)) [1,3,5,7,9] while loop It repeats over the code block as long as entry condition is True Example n = 5 i = 0 while i<n: print(i,"hello world") i += 1 0 Hello world 1 Hello world 2 Hello world 3 Hello world 4 Hello world # Sometimes entry condition can be replaced by True to make an infinite loo p while True: print("infinite loop") Loop keywords: break and continue break : It use used to break the loop at any given condition. As a result, the program control comes out of the loop. In case of nested loop break breaks only the innermost loop. continue : It skips the current iteration of loop and rejoins from the next iteration. The program control does not leave the loop here, it merely skips the current iteration. for i in "Python": if i=="t": break P y for i in "Python": if i in "aeiou": continue P y t h n pass is another keyword that makes no direct change to program control but can be used in place of

pass is another keyword that makes no direct change to program control but can be used in place of no definition. for i in "Python": pass pass can also be used outside loop but not break and continue try: print(1/0) except: pass Practice Questions 1. Write a program to find if a given number is Even or Odd. def isevenodd(number): if number%2==0: return "Even" return "Odd" 2. Write a program to check if a given number is divisible by 7 or 11. def isdivisible(number): if number%7==0 or number%11==0: return True return False 3. Write a program to find the largest of three numbers. def largestofthree(a,b,c): if a>=b and a>=c: return a elif b>=a and b>=c: return b return c 4. Write a program to find the grade of a student. def studentgrade(marks): if marks>=70: return "First class distinction" elif marks>=60: return "First class" elif marks>=50: return "Second class" elif marks>=35:

elif marks>=35: return "Third class" return "Fail" 5. Write a program to print numbers from 1 to 100, but replace the number with "fizz" if it is divisible by 3 and by "buzz" if it is divisible by 4 and "fizzbuzz" if it is divisible by both. def fizzbuzz(): for i in range(1,101): if i%3==0 and i%5==0: print("fizzbuzz") elif i%3==0: print("fizz") elif i%5==0: print("buzz") # one liner answer for fizz buzz for i in range(1,101): print("fizzbuzz") if i%3==0 and i%5==0 else print("fizz") if i%3==0 else print("buzz") if i%5==0 else 6. Write a program to find the count of vowels in a given country name. def countvowels(name): count = 0 for i in name: if i in "aeiouaeiou": count += 1 return count 7. Write a program to delete vowels from a given string. def deletevowels(str1): str2 = "" for i in str1: if i in "aeiouaeiou": continue str2 += i return str2 8. Write a program to print the sqaures of two upto a given number. def twosquares(number): i = 1 while i<=number: print(2**i) i += 1 9. Write a program to break the string on first vowel.

def firstvowel(str1): str2 = "" for i in str1: if i in "aeiouaeiou": break str2 += i return str2 10. Brain teaser: Car Puzzle Consider all four digit car numbers of which one number is True on all the below conditions: a) Last digit is double the first digit, like 1--2 b) Last two digits are double the first two, like 1122 c) Middle digits are same, like -11- Find the number. for i in range(1000,10000): if i%10 == 2*(i//1000) and i%100 == 2*(i//100) and i//100%10 == i%100// 10: print("the car number is", i)