Q and A for Section 4.4 CS 106, Fall 2015. If statement syntax Q: The syntax for an if statement (or conditional statement) is: if _______________ : _____________.

Slides:



Advertisements
Similar presentations
Chapter 4 - Control Statements
Advertisements

The if-else Statements
Selection Victor Norman CS104 Calvin College. Reading Quiz Counts toward your grade.
James Tam Making Decisions In Python In this section of notes you will learn how to have your Pascal programs choose between alternative courses of action.
July 13 th.  If/ Else if / Else  Variable Scope  Nested if/else's  Switch statements  Conditional Operator.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
true (any other value but zero) false (zero) expression Statement 2
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 Lecture 7:Control Structures I (Selection) Introduction to Computer Science Spring 2006.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Making Decisions In Python
Logical Operators and Conditional statements
Chapter 4 Making Decisions
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Q and A for Section 4.4 CS 106, Fall Q1 Q: The syntax for an if statement (or conditional statement) is: if _______________ : _____________ A: if.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Chapter 2 - Algorithms and Design
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Other Conditional Methods. Conditional Operator Conditional Operator (?:) Conditional operator ( ?: ) – Ternary operator: 3 arguments expression1 ? expression2.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Computer Science 111 Fundamentals of Programming I Making Choices with if Statements.
ㅎㅎ logical operator if if else switch while do while for Third step for Learning C++ Programming Repetition Control Structures.
Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping with.
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 7 Conditionals and Loops 4/18/09 Python Mini-Course: Day 2 - Lesson 7.
Python Conditionals chapter 5
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Selection Statements. Introduction Today we learn more about learn to make decisions in Turing ▫Nested if statements, ▫case statements.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
CS 106 Introduction to Computer Science I 09 / 26 / 2007 Instructor: Michael Eckmann.
James Tam Making Decisions In Python In this section of notes you will learn how to have your programs choose between alternative courses of action.
The If Statement There are no switch statements in Python. You need to use just if statements. There are no switch statements in Python. You need to use.
Student Q and As from 5.1 – 5.7, 5.11 Students of CS104, Fall 2013 (and me)
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Today… Operators, Cont. Operator Precedence Conditional Statement Syntax. Winter 2016CISC101 - Prof. McLeod1.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
Lecture 3 Selection Statements
Control Flow (Python) Dr. José M. Reyes Álamo.
Chapter 3 Selection Statements
Selection (also known as Branching) Jumail Bin Taliba by
EGR 2261 Unit 4 Control Structures I: Selection
Basic operators - strings
Other Conditional Methods
Chapter 4: Control Structures I (Selection)
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Comparing Data & the ‘switch’ Statement
Comparing Data & the ‘switch’ Statement
Presentation transcript:

Q and A for Section 4.4 CS 106, Fall 2015

If statement syntax Q: The syntax for an if statement (or conditional statement) is: if _______________ : _____________ A: if : When is this used? When you have to do something when a certain condition is true, and nothing in all other cases.

Use an if statement Q: Write code that prints out "Brilliant!" if the value in variable food is "spam". A: if food == "spam": print "Brilliant!"

Q3 Q: What happens if the value of food is "bubble and squeak"? A: Nothing.

Compound bool expression Q: Write code to print "Brilliant!" if food is "spam" and how_prepared is "on toast". A: if food == "spam" and how_prepared == "on toast": print "Brilliant!” If food is not “spam”, then short-circuiting is used: how_prepared won’t even be evaluated

if-else syntax Q: An if-else statement has this format: if _____________ : ___________ else: ___________ A: ; ; When is this used?: when there are only two choices/options, and you have to do something in each case.

Use if-else Q: Suppose you have a function is_prime(x) that returns True if x is a prime number. Write code to add x to a list primes if x is prime and to a list non_primes otherwise. A: if is_prime(x): primes.append(x) else: non_primes.append(x)

More practice Q: Write code that prints "NaN" if the list nums is empty or, otherwise, computes and prints the average of the list of floats. A: if len(nums) == 0: print "NaN" else: print sum(nums) / len(nums)

if-elif syntax An if-else statement has this format: if : elif : # elif : can repeat elif part # else: # else is optional When is this used? When there are > 2 choices to match and code has to do something different for each.

Counting Q: You are given a long string gen containing only As, Gs, Ts, and Cs. Write code to count the number of As and the number of Gs in the string. countAs = 0 countGs = 0 for ch in gen: if ch == 'A': countAs += 1 elif ch == 'G': countGs += 1

Evaluate a number Given a variable x referring to an number, print “negative”, “0”, or “positive”, as appropriate. A: if x < 0: print “negative” elif x == 0: print “0” else: print “positive”

Letter grades Q: Write code to print out a student's letter grade, based on the value in score. Pick your own scale. A: if score > 92: print 'A' elif score > 85: print 'B' elif score > 77: print 'C' elif score > 70: print 'D' else: print 'F'

Q11 Q: You have 2 operands, op1 and op2, and an operator, op, that is one of '+', '-', '*', '/'. Write code to compute the correct result into res. A: if op == '+': res = op1 + op2 elif op == '-': res = op1 - op2 elif op == '*': res = op1 * op2 elif op == '/': res = op1 / op2

Nested ifs Q: Write code to print "Brilliant!" if food is "spam" and how_prepared is "on toast", and to print "Awesome!" if how_prepared is "in a casserole". A: if food == "spam": if how_prepared == "on toast": print "Brilliant!" if how_prepared == "in a casserole": print "Awesome!"

Rewrite nested if as if-elif Q: Rewrite this code using if-elif: if i < 7: do_something(i) else: if j > 9: do_something_else(j) A: if i < 7: do_something(i) elif j > 9: do_something_else(j)

Nested if vs. elif Q: When would you prefer an if nested inside an else, over using an elif. A: An if-else is a binary decision: there are two choices. An if-elif-elif-else is an n-way decision: some variable can belong to n different “groups” or “classes”. If you are comparing a variable n to something, and then in one of the results have to “classify” some other variable, use a nested if.

Compute the max Given a list of positive numbers nums, write code that leaves the variable maxSeen referring to the largest number in nums. Don’t use the built-in max() function. maxSeen = 0 for num in nums: if num > maxSeen: maxSeen = num

Data cleansing data is a list of weather readings. Each reading is a list with 10 elements. The 3th value is a temperature reading. But sometimes our thermometer goes haywire and reports the temp as In this case, we want to throw out the entire reading. Write a for loop to do this, building a new list called good_data that contains only the good readings. E.g.: data = [ [ 0, 1, 2, 78, 4, 5, 6, 7, 8, 9 ], [ 0, 1, 2, -999, 4, 5, 6, 7, 8, 9 ] ]

Answer good_data = [] for aReading in data: # aReading is a list with 10 elements. # Check if the temp is not bogus. if aReading[3] != -999: good_data.append(aReading) # now good_data is clean. Now, add code to also filter out humidity readings (in the 7 th field) when they are negative. Now, add code to also filter out any readings that don’t have 10 fields in them.

Non-booleans used as booleans Q: In the “for the guru” on page 142, there is code if not dinner:. Can you explain that? A: Why, yes. Yes, I can. The pattern is if : So, if the expression given is not a boolean ( dinner is a string), then it is converted to a boolean, as if bool(dinner) were called. In general, if a value is empty ( “” or [] ), the value is False; else, True.

Q10 Q: You have a list of Room objects, rooms. A Room object has a method anybody_home() that returns True if anyone is there. Write code to count how many rooms are not empty. A: someone_home = 0 for room in rooms: if room.anybody_home(): someone_home += 1 This is like a filter: do something only for certain elems in the sequence

Checking if a value is one of many Q: Write code that prints "Let's go" if the variable response equals either 'y' or 'yes'. A: if response in ('y', 'yes'): print "Let's go" (not if response == 'y' or 'yes' !!)

What kind of triangle? Suppose we have 3 values, s1, s2, and s3, that represent the lengths of the 3 sides of a triangle. Print out “equilateral” if the sides represent an equilateral triangle, “isosceles” for isosceles, or “scalene” otherwise.

Simulating bouncing particles Suppose we are simulating n particles bouncing off the inside of a container’s walls. We have 3 lists: turts is a list of Turtle objects; xvels is a list of x velocities; yvels is a list of y velocities. The next location of a turt is computed by: (turts[i].getX() + xvels[i], turts[i].getY() + yvels[i]) Write code to switch the velocities (from positive to negative or vice-versa) if turts[i] is currently within 3 pixels of the walls of a 600x400 canvas.

Q12 Q: What can we do to the previous code to print out "Oops!" if op contains a bad value? A: Add else: print 'Oops!'