THE IF STATEMENT. The if statement is used to check a condition: if the condition is true, we run a block

Similar documents
Senthil Kumaran S

Decisions, Decisions. Testing, testing C H A P T E R 7

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

Flow Control: Branches and loops

1 Getting used to Python

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Math Day 2 Programming: How to make computers do math for you

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Introduction to Python

Conditional Expressions and Decision Statements

Python for Informatics

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Visualize ComplexCities

Introduction to Bioinformatics

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

Conditionals and Recursion. Python Part 4

The Big Python Guide

Basics of Programming with Python

Text Input and Conditionals

Stratford School Academy Schemes of Work

Outline. Announcements. Homework 2. Boolean expressions 10/12/2007. Announcements Homework 2 questions. Boolean expression

Real Python: Python 3 Cheat Sheet

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

CS Summer 2013

RANDOM NUMBER GAME PROJECT

Most of the class will focus on if/else statements and the logical statements ("conditionals") that are used to build them. Then I'll go over a few

Decision Structures CSC1310. Python Programming, 2/e 1

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #13. Loops: Do - While

NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION

To become familiar with array manipulation, searching, and sorting.

An Introduction to Python

Programming with Python

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

Introduction to Python Code Quality

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

Python for C programmers

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Python - Conditional Execution

Conditional Execution

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

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

EGR 111 Loops. This lab is an introduction to loops, which allow MATLAB to repeat commands a certain number of times.

Python: common syntax

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

CS 1110, LAB 1: PYTHON EXPRESSIONS.

EGR 111 Loops. This lab is an introduction to loops, which allow MATLAB to repeat commands a certain number of times.

Try typing the following in the Python shell and press return after each calculation. Write the answer the program displays next to the sums below.

Control Flow: Branching booleans and selection statements CS GMU

Zipf's Law. This preliminary discussion gives us our first ideas about what the program we're writing needs to do.

Functions Structure and Parameters behind the scenes with diagrams!

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

CSCE 110: Programming I

Introduction to Programming (day 1)

CS Advanced Unix Tools & Scripting

CONTROL FLOW CREATING ALTERNATE PATHS OF EXECUTION USING: BRANCHING WHILE LOOPS FOR LOOPS

Python Games. Session 1 By Declan Fox

How Do Robots Find Their Way?

CME 193: Introduction to Scientific Python Lecture 1: Introduction

Quiz. Introduction: Python. In this project, you ll make a quiz game to challenge your friends. Activity Checklist.

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

Chapter 2 Writing Simple Programs

Conditional Execution

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

6.S189 Homework 1. What to turn in. Exercise 1.1 Installing Python. Exercise 1.2 Hello, world!

LOOPS. Repetition using the while statement

Unit A451: Computer systems and programming. Section 3: Software 1 Intro to software

Exercise: Inventing Language

MATLAB provides several built-in statements that allow for conditional behavior if/elseif/else switch menu

If Statements, For Loops, Functions

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1

CPSC 3740 Programming Languages University of Lethbridge. Control Structures

Python for Beginners Python for Beginners...1

Selection Statement ( if )

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

CS Final Exam Review Suggestions - Spring 2014

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

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

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Introduction to Python (All the Basic Stuff)

Lesson 1 Python: Interactive Fiction

Gold Hw8 Problem 3: TT Securities, Incorporated

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

Boolean Expressions. Is Equal and Is Not Equal

6.189 Project 1. Readings. What to hand in. Project 1: The Game of Hangman. Get caught up on all the readings from this week!

Lists, loops and decisions

Boolean Expressions. Is Equal and Is Not Equal

Python for Non-programmers

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Stored (and reused) Steps

ENGR 102 Engineering Lab I - Computation

Copied from: on 3/20/2017

Variables, expressions and statements

Python Boot Camp. Day 3

Program Planning, Data Comparisons, Strings

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras

EECS 183. Week 3 - Diana Gage. www-personal.umich.edu/ ~drgage

3. Conditional Execution

Chapter 1 Introduction

Comp 151. Control structures.

2.Raspberry PI: Architecture & Hardware Specifications

Transcription:

THE IF STATEMENT The if statement is used to check a condition: if the condition is true, we run a block of statements (called the if-block), elsewe process another block of statements (called the else-block). The else clause is optional. Example (save as if.py): number = 23 guess = int(raw_input('enter an integer : ')) if guess == number: # New block starts here print 'Congratulations, you guessed it.' print '(but you do not win any prizes!)' # New block ends here elif guess < number: # Another block print 'No, it is a little higher than that' # You can do whatever you want in a block...

else: print 'No, it is a little lower than that' # you must have guessed > number to reach here print '' # This last statement is always executed, # after the if statement is executed. Output: Enter an integer : 50 No, it is a little lower than that Enter an integer : 22 No, it is a little higher than that

Enter an integer : 23 Congratulations, you guessed it. (but you do not win any prizes!) How It Works In this program, we take guesses from the user and check if it is the number that we have. We set the variable number to any integer we want, say 23. Then, we take the user s guess using the raw_input() function. Functions are just reusable pieces of programs. We supply a string to the built-in raw_input function which prints it to the screen and waits for input from the user. Once we enter something and press enter key, the raw_input() function returns what we entered, as a string. We then convert this string to an integer using int and then store it in the variable guess. Actually, the int is a class but all you need to know right now is that you can use it to convert a string to an integer (assuming the string contains a valid integer in the text). Next, we compare the guess of the user with the number we have chosen. If they are equal, we print a success message.

Notice that we use indentation levels to tell Python which statements belong to which block. This is why indentation is so important in Python. I hope you are sticking to the "consistent indentation" rule. Are you? Notice how the if statement contains a colon at the end - we are indicating to Python that a block of statements follows. Then, we check if the guess is less than the number, and if so, we inform the user that they must guess a little higher than that. What we have used here is the elif clause which actually combines two related if else-if else statements into one combined if-elif-else statement. This makes the program easier and reduces the amount of indentation required. The elif and else statements must also have a colon at the end of the logical line followed by their corresponding block of statements (with proper indentation, of course) You can have another if statement inside the if-block of an if statement and so on - this is called a nested if statement.

Remember that the elif and else parts are optional. A minimal valid if statement is: if True: print 'Yes, it is true' After Python has finished executing the complete if statement along with the associated elif and else clauses, it moves on to the next statement in the block containing the if statement. In this case, it is the main block (where execution of the program starts), and the next statement is the print '' statement. After this, Python sees the ends of the program and simply finishes up. Even though this is a very simple program, I have been pointing out a lot of things that you should notice. All these are pretty straightforward (and surprisingly simple for those of you from C/C++ backgrounds). You will need to become aware of all these things initially, but after some practice you will become comfortable with them, and it will all feel 'natural' to you. Note for C/C++ Programmers NOTE There is no switch statement in Python. You can use an if..elif..else statement to do the same thing (and in some cases, use a dictionary to do it quickly) Source: http://www.swaroopch.com/notes/python/