INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0

Similar documents
Boolean Expressions. Is Equal and Is Not Equal

Boolean Expressions. Is Equal and Is Not Equal

Visualize ComplexCities

Programming with Python

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

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions. Eric McCreath

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

cs1114 REVIEW of details test closed laptop period

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

Programming in Python 3

Python Input, output and variables

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016

Text Input and Conditionals

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Program Planning, Data Comparisons, Strings

Chapter 3 : Informatics Practices. Class XI ( As per CBSE Board) Python Fundamentals. Visit : python.mykvs.in for regular updates

QUIZ: What value is stored in a after this

CS 1110, LAB 1: PYTHON EXPRESSIONS.

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Control Structures 1 / 17

And Parallelism. Parallelism in Prolog. OR Parallelism

Python Programming: An Introduction to Computer Science

CMSC201 Computer Science I for Majors

Chapter 2. Python Programming for Physicists. Soon-Hyung Yook. March 31, Soon-Hyung Yook Chapter 2 March 31, / 52

OCR Pseudocode to Python

Pupil Name. Year. Teacher. Target Level. Key Stage 3 Self-Assessment Year 9 Python. Spelling Test No 3. Spelling Test No 2. Spelling Test No 1

Python Programming: An Introduction to Computer Science

CMSC 201 Computer Science I for Majors

CMSC201 Computer Science I for Majors

Real Python: Python 3 Cheat Sheet

Python for Informatics

Introduction to Computer Programming for Non-Majors

Functional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute

The Big Python Guide

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

Operators. Java operators are classified into three categories:

cast int( x float( x str( x hex( int string int oct( int string int bin( int string int chr( int int ord( ch

Project 3: RPN Calculator


Chapter 3: Operators, Expressions and Type Conversion

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018

(Python) Chapter 3: Repetition

NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION

Python for Non-programmers

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

Variables and Values

JavaScript Basics. The Big Picture

Introduction to Computer Programming for Non-Majors

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

Lecture #7: Recursion (and a data structure)

JAVA Programming Fundamentals

ME30 Lab3 Decisions. February 20, 2019

CS 115 Lecture 4. More Python; testing software. Neil Moore

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

PYTHON- AN INNOVATION

More about Binary 9/6/2016

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

Python Programming: An Introduction to Computer Science

Bits, Words, and Integers

Introduction to Python Code Quality

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

MITOCW watch?v=se4p7ivcune

5. Control Statements

Introduction to Programming

CS177 Recitation. Functions, Booleans, Decision Structures, and Loop Structures

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Conditional Expressions and Decision Statements

Chapter 4 : Informatics Practices. Data Handling. Class XI ( As per CBSE Board) Visit : python.mykvs.in for regular updates

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

CPTS 111, Fall 2011, Sections 6&7 Exam 3 Review

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

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

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

Part 6b: The effect of scale on raster calculations mean local relief and slope

Unit 3. Operators. School of Science and Technology INTRODUCTION

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

CSC201, SECTION 002, Fall 2000: Homework Assignment #2

CSC148, Lab #4. General rules. Overview. Tracing recursion. Greatest Common Denominator GCD

Introduction to programming with Python

If Statements, For Loops, Functions

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

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

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

Computer Science 217

CS 360: Programming Languages Lecture 10: Introduction to Haskell

Getting Started Values, Expressions, and Statements CS GMU

Topic Notes: Bits and Bytes and Numbers

Introduction to computers and Python. Matthieu Choplin

The following expression causes a divide by zero error:

Course Schedule. CS 221 Computer Architecture. Week 3: Plan. I. Hexadecimals and Character Representations. Hexadecimal Representation

1.2 Adding Integers. Contents: Numbers on the Number Lines Adding Signed Numbers on the Number Line

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

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

CMSC201 Computer Science I for Majors

UNIT- 3 Introduction to C++

Learning the Language - V

Transcription:

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0 OCTOBER 2014

Python Selection and Conditionals 1 SELECTION AND CONDITIONALS WHAT YOU MIGHT KNOW ALREADY You will probably be familiar with basic conditional operators used with if and while statements. height = 1.3 if height > 1.2: print('you can ride this roller coaster') You may also know about the six conditional operators x > 5 #Greater than x >= 5 #Greater than or equal x < 5 #Less than x <= 5 #Less than or equal x == 5 #Equal x!= 5 #Not equal ELSE The else statement lets you do something else if the test isn't true. The code will do one or the other: height = 1.17 if height > 1.2: print('you can ride this roller coaster') else: print('sorry, you are not tall enough for this ride') ELIF The elif statement lets you add one or more extra test clauses. In this case, we are checking for kids who are almost tall enough, and giving them a slightly different message. Remember that with elif, only one clause is executed (the first one which is true). height = 1.17 if height > 1.2: print('you can ride this roller coaster') elif height > 1.15: print('you are not quite tall enough, come back next year') else: print('sorry, you are not tall enough for this ride') COMPOUND CONDITIONS Sometimes you need to check more than one thing in an if statement. To make lemonade you need at least 10 lemons AND at least 2kg of sugar. Note that you do not need parentheses around the comparison clauses. Your code will be a lot more readable (and look more "normal" to other Python programmers) if you leave them out.

Python Selection and Conditionals 2 lemons = 12 sugar_kg = 3 if lemons >= 10 and sugar_kg >= 2: print("let's make lemonade") Sometimes we need to test whether one thing or another is true. day = 'monday' if day == 'monday' or day == 'thursday': print("it's bath night!") The not operator is used to test for false. For example, the function is_integer() returns true if a float value happens to be a whole number. If we want to check if a float is not a whole number, we can do this: a = 1.1 if not a.is_integer(): print('a is not an integer') USING == ON LISTS We use == to check if two values are equal. It works for number, strings, and other things like lists, tuples etc. a = 1 b = 1 a = 'abc' b = 'def' a = [1, 2, 3] b = [1, 2, 3] For two lists to be equal, they must be the same type (a list and a tuple can never be equal even if they have identical elements). They must be the same length. Each element must be identical. IN OPERATOR The in operator is used to test if a string contains a particular character, or a list contains a particular element. a = 'abcdef' print('b' in a) a = [1, 2, 3, 4] print(3 in a) print(3 not in a) The not in operator returns true if the element is not in the string or list. In this case it is false because the list does include 3.

Python Selection and Conditionals 3 PRECEDENCE Here is a complete table of operator precedence for arithmetic, bitwise and logical operators. Calculation and bitwise operations are done first, followed by the various comparison operators. Finally the Boolean operators are evaluated. If you have a complex expression involving a mix of and and or operators, you might use parentheses to make it clearer. ** Power +x, -x, ~x Positive, negative, bitwise not *, /, //, % Multiply, divide, remainder +, - Add, subtract <<, >> Bitwise shift & Bitwise and ^ Bitwise xor Bitwise or in, not in, Comparisons. See the exercises for an explanation of the is operator. is, is not, <, <=, >, >=,!=, == not Boolean not and Boolean and or Boolean or TRUE AND FALSE VALUES Python uses True and False to represent Boolean values. But other values also count as true or false, for example an integer value of 0 represents false, any other value represents true. False False, None Integer 0 Float 0.0 Imaginary 0j, 0+0j Empty string, list, tuple, set etc True True Any other integer Any other float Any other non-zero complex/imaginary Non-empty string, list, tuple, set etc Other types are true by default. If you create your own types, you can make your own rules for if they are true or false. SHORT CIRCUIT EVALUATION Python has a really neat feature called short circuit evaluation. Consider this code: a = 6 b = 0 if a or b: print('true') Of course a (value 6) is true, b (value0) is false so ORing a and b will be true. But what about this: a = 6 b = 0 print(a or b)

Python Selection and Conditionals 4 You might expect this to print True, but what it actually prints is 6! Well, there are two things happening: Python spots that a is 6, which is a true value. Since it is an or statement, Python doesn't need to check b, in fact it promises not to. At this point, Python could just return a value of true. But instead it returns 6, the value at the point where it was able to decide the result. 6 will always count as true, but sometimes having the value 6 is more useful than just having true or false. Look at this code: u = input('username?') print('hello', u or 'Guest') It prompts the user for their name and says hello. If the user types in a name, u will be true so the or statement will return the value of u. If the user just hits return, u will be an empty string which counts as false. So the or statement will evaluate the second term and return 'Guest'. Of course in a real program you would have to do a few more checks.

Python Selection and Conditionals 5 EXERCISES COMPOUND STATEMENTS 1. It is quite common to want to check that a value is within a certain range. Here is some code to check your body temperature. temp = 37.0 if temp >= 36.5 and temp <= 37.5: print('your temperature is fine') Here is an alternative way to do the same thing. It looks a bit neater, but more importantly it makes it clear what the code is for. It isn't just some random and clause, it is specifically intended to check that temp is within range. temp = 37.0 if 36.5 <= temp <= 37.5: print('your temperature is fine') Try these examples, make sure you understand how they work. OTHER COMPARISONS ON STRINGS, LISTS 1. You can use all six comparison operators on strings, not just ==. For example you can test if one string is greater than another: s1 = 'abc' s2 = 'xyz' print(s2>s1) Can you understand the result? 2. Here is a slightly different case: s1 = 'abc' s2 = 'abcd' print(s2>s1) 3. Here s1 is longer, but s2 is alphabetically higher. Which wins? s1 = 'aaaa' s2 = 'abc' print(s2>s1) 4. You have probably worked out that string > is equivalent to alphabetical ordering, but only if the strings contain only lower case letters. If your strings contain upper case characters, digits or punctuation, the comparison is based on the ASCII codes of each character. Look it up if you are not familiar. Unless you know ASCII it is anybody's guess! s1 = 'Who?' s2 = 'Whoah' print(s2>s1)

Python Selection and Conditionals 6 Strictly, Python uses Unicode characters, but for the characters you find on a normal UK/US English keyboard it is equivalent to ASCII. Unicode is like an extended version of ASCII which includes all the characters in almost every language in the world. 5. Try the same exercise with lists. Can you invent the equivalent tests for lists, like the string cases we just tried? k1 = [1, 2, 3] k2 = [4, 5, 6] print(k2>k1) SHORT CIRCUIT EVALUATION 1. Can you predict what would be printed in these cases? Test your predictions. print([] and 6) print([] or 6) print('abc' and 6) print('abc' or 6) print('abc' and 0.0) print('abc' or 0.0) print(not []) print(not 'xyz') print((1 and 2) or (3 and 4)) IN OPERATOR FOR STRINGS 1. What is this code doing? s = 'abcde' print('bcd' in s) 2. Why doesn't this work? s = 'abcde' print('ace' in s) 3. Does it work for lists? k = [1, 2, 3, 4] print([3, 4] in k) Hint: a list can contain elements of any type, including lists. Try this, can you say why the code above cannot return true? #A list containing two lists k = [[1, 2], [3, 4]] print([3, 4] in k) IF ELSE TERNARY OPERATOR 1. You can use if and else in a slightly different way: x = 1 s = '+ve' if x>=0 else '-ve' print(s) This identifies x and positive or negative. The statement works exactly how it reads in your head "The result is positive if x is greater than or equal to zero, otherwise it is negative".

Python Selection and Conditionals 7 Some people consider this to be against the spirit of Python. Look at this code: x = -1 print('yes') if x>=0 else print('no') You might think that this code implies it always prints "yes" and then prints "no" if x is less than zero. It doesn't. Or you might find it reads in your head just fine. It is part of the language, but if you feel it makes your code hard to read just use a normal if statement. IS OPERATOR 1. Try the following code: a = [1, 2, 3] b = [1, 2, 3] print(a is b) We have created two lists, a and b. They happen to be equal, so == return true. The is operator checks if a and b are the same actual list, they are not. Try: a = [1, 2, 3] b = a print(a is b) The important thing to understand here is that the list is not stored inside the variable. When a list is created, it is stored somewhere in the computer memory, and the variable a simply points at (or references) that location. When we assign a to b, we are making b reference the same location. a and b reference the same list, so is returns true