" # # if $ " %&% # ifelse $ " #&% # ifelif-else $ +bool ##%# # #.* $ ## # .# *#%$ % ## % .#*#%*

Size: px
Start display at page:

Download "" # # if $ " %&% # ifelse $ " #&% # ifelif-else $ +bool ##%# # #.* $ ## # .# *#%$ % ## % .#*#%*"

Transcription

1 ! " if " %&% ifelse!()!() " &% ifelif-else "*+ % + & "*- +bool (.%) "%.* *%!!%.* *%* 0* **!! 0.*%* %. *% % % % +*.* **% *

2 3 4! * convert.py A program to convert Celsius temps to Fahrenheit by: Susan Computewell celsius = input("what is the Celsius temperature? ") fahrenheit = * celsius + 32 print "The temperature is" fahrenheit "degrees Fahrenheit." 3 %%* % % %+!67 4%7 4% %%! main() 5 () *68 * **967 % **97 % "% % " **! 6 7 convert2.py A program to convert Celsius temps to Fahrenheit. This version issues heat and cold warnings. celsius = input("what is the Celsius temperature? ") fahrenheit = * celsius + 32 print "The temperature is" fahrenheit "degrees fahrenheit." if fahrenheit >= 90: print "Its really hot out there be careful!" if fahrenheit <= 30: print "Brrrrr. Be sure to dress warmly" main()

3 "if if <condition>: <body> ".* if "*if 4! *.* + + ** :+ "*if + + *if "&% 4 4 0::; <expr> <relop> <expr> >> 9> 9 => 3 3. > 2.?. 9? <. 5

4 4 <*==*. = *.* *. : = = *& *%& ( - * ) *2? - 0-+!!*( )*( ) 7 * -*bool -!** True False >>> 3 < 4 True >>> 3 * 4 < False >>> "hello" == "hello" True >>> "Hello" < "hello" True 2+ "!%* "* "* %% & 2+ 0%% %main() *!* %!

5 2+?%% % %+= & main if <condition>: main() 2+ 0!! name * >>> import math >>> math. name math 2+ 0 name! math 0!* name main 2 >>> name main 2+ "* %! name %!* 0*%! main 0 ** if name == main : main() B!%= 5 3 :. %* quadratic.py A program that computes the real roots of a quadratic equation. Illustrates use of the math library. Note: This program crashes if the equation has no real roots. import math Makes the math library available. print "This program finds the real solutions to a quadratic" print a b c = input("please enter the coefficients (a b c): ") discroot = math.sqrt(b * b - 4 * a * c) root = (-b + discroot) (2 * a) root2 = (-b - discroot) (2 * a) print print "The solutions are:" root root2 % &@7 :.*! This program finds the real solutions to a quadratic Please enter the coefficients (a b c): 2 Traceback (most recent call last): File "C:\Documents and Settings\Terry\My Documents\Teaching\W04\CS 20\Textbook\code\chapter3\quadratic.py" line 2 in -toplevelmain() File "C:\Documents and Settings\Terry\My Documents\Teaching\W04\CS 20\Textbook\code\chapter3\quadratic.py" line 4 in main discroot = math.sqrt(b * b - 4 * a * c) ValueError: math domain error main() 6 7

6 0:*C * quadratic2.py A program that computes the real roots of a quadratic equation. Bad version using a simple if to avoid program crash import math print "This program finds the real solutions to a quadratic\n" a b c = input("please enter the coefficients (a b c): ") discrim = b * b - 4 * a * c if discrim >= 0: discroot = math.sqrt(discrim) root = (-b + discroot) (2 * a) root2 = (-b - discroot) (2 * a) print "\nthe solutions are:" root root2 0* ( &)::!* % 3:* 0 % %;C0 %; This program finds the real solutions to a quadratic Please enter the coefficients (a b c): >>> "%! %D:% %%% = 0if if discrim < 0: print "The equation has no real roots!" "%:*% 0! %%+! (*discrim >= 0 discrim < 0*!!) %&% else if "if-else if <condition>: <statements> <statements>

7 0* *!* if + ** else + *% if-else +** + quadratic3.py A program that computes the real roots of a quadratic equation. Illustrates use of a two-way decision import math print "This program finds the real solutions to a quadratic\n" a b c = input("please enter the coefficients (a b c): ") discrim = b * b - 4 * a * c if discrim < 0: print "\nthe equation has no real roots!" discroot = math.sqrt(b * b - 4 * a * c) root = (-b + discroot) (2 * a) root2 = (-b - discroot) (2 * a) print "\nthe solutions are:" root root2 main() 5 >>> This program finds the real solutions to a quadratic Please enter the coefficients (a b c): 2 The equation has no real roots! >>> This program finds the real solutions to a quadratic Please enter the coefficients (a b c): The solutions are: A&0 "%.:= This program finds the real solutions to a quadratic Please enter the coefficients (a b c): 2 The solutions are: A&0 0 * *:: : %= % +7 ::%&% = A&0 Check the value of discrim when < 0: handle the case of no roots when = 0: handle the case of a double root when > 0: handle the case of two distinct roots 0%%*& *

8 A&0 A&0 if discrim < 0: print "Equation has no real roots" if discrim == 0: root = -b (2 * a) print "There is a double root at" root Do stuff for two roots A&0 *%:*!& % "ifelse %*!= "! else *%if elif A&0 if <condition>: <case statements> elif <condition2>: <case2 statements> elif <condition3>: <case3 statements> <default statements> A&0 "*** +!:! : *** * + +* if-elif-else *else * A&0 "else * elsed: %+ 5 5

9 A&0 quadratic4.py A program that computes the real roots of a quadratic equation. Illustrates use of a multi-way decision import math print "This program finds the real solutions to a quadratic\n" a b c = input("please enter the coefficients (a b c): ") discrim = b * b - 4 * a * c if discrim < 0: print "\nthe equation has no real roots!" elif discrim == 0: root = -b (2 * a) print "\nthere is a double root at" root discroot = math.sqrt(b * b - 4 * a * c) root = (-b + discroot) (2 * a) root2 = (-b - discroot) (2 * a) print "\nthe solutions are:" root root2 6. %!:.*!! & "* 7.+%: * sqrt *%:*!% * 2 *. (.!!%:%! %.) discrt = othersqrt(b*b - 4*a*c) if discrt < 0: print "No real roots.... :* *%! %+! " % % % * % "! +: quadratic5.py A program that computes the real roots of a quadratic equation. Illustrates exception handling to avoid crash on bad inputs import math print "This program finds the real solutions to a quadratic\n" try: a b c = input("please enter the coefficients (a b c): ") discroot = math.sqrt(b * b - 4 * a * c) root = (-b + discroot) (2 * a) root2 = (-b - discroot) (2 * a) print "\nthe solutions are:" root root2 except ValueError: print "\nno real roots" 6

10 "try *% * try: <body> except <ErrorType>: <handler> 0try + *+ *try except *%+ :*+% ** + " %! Traceback (most recent call last): File "C:\Documents and Settings\Terry\My Documents\Teaching\W04\CS20\Textbook\code\chapter3\quadratic.py" line 2 in -toplevelmain() File "C:\Documents and Settings\Terry\My Documents\Teaching\W04\CS 20\Textbook\code\chapter3\quadratic.py" line 4 in main discroot = math.sqrt(b * b - 4 * a * c) ValueError: math domain error "EValueError: math domain errorf** CD% This program finds the real solutions to a quadratic Please enter the coefficients (a b c): No real roots * + "try except :*!* *+ *. *( unpack tuple of wrong sizef) * *(NameError)!+(TypeError) try! except 5 quadratic6.py A program that computes the real roots of a quadratic equation. Illustrates robust exception handling to avoid crash on bad inputs import math print "This program finds the real solutions to a quadratic\n" try: a b c = input("please enter the coefficients (a b c): ") discroot = math.sqrt(b * b - 4 * a * c) root = (-b + discroot) (2 * a) root2 = (-b - discroot) (2 * a) print "\nthe solutions are:" root root2 except ValueError excobj: msg = str(excobj) if msg == "math domain error": print "\nno Real Roots" elif msg == "unpack tuple of wrong size": print "\nyou didnt give me the right number of coefficients." print "\nsomething went wrong sorry!" 6 except NameError: print "\nyou didnt enter three numbers." except TypeError: print "\nyour inputs were not all numbers." except SyntaxError: print "\nyour input was not in the correct form. Missing comma(s) perhaps?" except: print "\nsomething went wrong sorry!" if name == main : main() 7 7

11 "excepts :elifs* %except : ** "except : else % * *%except *except %!* **%% *except % * + except ValueError excobj: msg = str(excobj) if msg == "math domain error": print "\nno Real Roots" elif msg == "unpack tuple of wrong size": print "\nyou didnt give me the right number of coefficients." print "\nsomething went wrong sorry!" A+*" <%%! %! "! % = % * * A+*" x x2 x3 = input("please enter three values: ") missing code sets max to the value of the largest print "The largest value is" max 2 "::&% %%+* *% max = x max = x2 max = x3 %%* *% =

12 2 3 :%+ if x >= x2 >= x3: max = x ; A %% % D.! !% %. 0+ * :; G %!== :!**.% %+ +;! ; 0D! *++%:% +9>++9>+ 0%= if x >= x2 and x >= x3: max = x elif x2 >= x and x2 >= x3: max = x2 max = x3 0D! % " 0%*%% *+**!!; 0%*- + ** H:= 0!*! %%x >= x2" ::x x2* + *% % x x3

13 " " if x >= x2: if x >= x3: max = x max = x3 if x2 >= x3: max = x2 else max = x3 ". ":+% * *! C%! *"* +**! ifelse!% C%%!; H: :%% -% *%!* ; : * 0* :: **!:! ::.. " max = x if x2 > max: max = x2 if x3 > max: max = x3 5

14 . "! * 0*% +* %+!. maxn.py Finds the maximum of a series of numbers n = input("how many numbers are there? ") Set max to be the first value max = input("enter a number >> ") Now compare the n- successive values for i in range(n-): x = input("enter a number >> ") if x > max: max = x 6 print "The largest value is" max 57 I &* max * x x2 x3 = input("please enter three values: ") print "The largest value is" max(x x2 x3) 3 " %! * *": :* % H*:* *!* * *%* :*%%! " *%* *? * * *+* %+*% : * 5 5

15 3!% *! *! ** *= * += "+ :%% % 5

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures Python Programming, 2/e 1 Objectives n To understand the programming pattern simple decision and its implementation

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 7 Part 1 The Department of Computer Science Objectives 2 To understand the programming pattern simple decision and its implementation

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 7 Part 1 Instructor: Long Ma The Department of Computer Science Objectives---Decision Structures 2 To understand the programming

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 7 Part 2 The Department of Computer Science Quick review one-way or simple decision if : two-way decision

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 7 Part 2 The Department of Computer Science Quick review one-way or simple decision if : two-way decision

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 7 Part 2 Instructor: Long Ma The Department of Computer Science Quick review one-way or simple decision if :

More information

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures Python Programming, 2/e 1 Objectives æ To understand the programming pattern simple decision and its implementation

More information

File processing and decision structures

File processing and decision structures File processing and decision structures Michael Mandel Lecture 4 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture04final.ipynb

More information

Multi-Way Decisions. The newest program is great, but it still has some quirks! This program finds the real solutions to a quadratic

Multi-Way Decisions. The newest program is great, but it still has some quirks! This program finds the real solutions to a quadratic Multi-Way Decisions The newest program is great, but it still has some quirks! This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 1,2,1 The solutions are: -1.0-1.0

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 3 Instructor: Long Ma The Department of Computer Science Review of Chapter 2 Stages of creating a program: Analyze the problem

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 3 The Department of Computer Science Review of Chapter 2 Stages of creating a program: Analyze the problem Determine specifications

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 3 The Department of Computer Science Review of Chapter 2 Stages of creating a program: Analyze the problem Determine specifications

More information

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers Python Programming, 2/e 1 Objectives n To understand the concept of data types. n To be familiar with the basic

More information

Chapter 2 Writing Simple Programs

Chapter 2 Writing Simple Programs Chapter 2 Writing Simple Programs Charles Severance Textbook: Python Programming: An Introduction to Computer Science, John Zelle (www.si182.com) Software Development Process Figure out the problem - for

More information

Lecture Numbers. Richard E Sarkis CSC 161: The Art of Programming

Lecture Numbers. Richard E Sarkis CSC 161: The Art of Programming Lecture Numbers Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda To understand the concept of data types To be familiar with the basic numeric data types in Python To be able

More information

CITS 1401 Problem Solving & Programming

CITS 1401 Problem Solving & Programming CITS 1401 Problem Solving & Programming Tim French Lecture 03 Numeric Data Processing (These slides are based on John Zelle s powerpoint slides for lectures accompanied with the text book) Objectives of

More information

SI Networked Computing: Storage, Communication, and Processing, Winter 2009

SI Networked Computing: Storage, Communication, and Processing, Winter 2009 University of Michigan Deep Blue deepblue.lib.umich.edu 2009-01 SI 502 - Networked Computing: Storage, Communication, and Processing, Winter 2009 Severance, Charles Severance, C. (2008, December 19). Networked

More information

Writing Python Programs, Numerical Data Types

Writing Python Programs, Numerical Data Types Writing Python Programs, Numerical Data Types Michael Mandel Lecture 2 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture02final.ipyn

More information

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers Python Programming, 3/e 1 Objectives n To understand the concept of data types. n To be familiar with the basic

More information

Decision Structures CSC1310. Python Programming, 2/e 1

Decision Structures CSC1310. Python Programming, 2/e 1 Decision Structures CSC1310 Python Programming, 2/e 1 Simple Decisions Decision structures, which are statements that allow a program to execute different sequences of instructions for different cases,

More information

Decision structures. A more complex decision structure is an if-else-statement: if <condition>: <body1> else: <body2>

Decision structures. A more complex decision structure is an if-else-statement: if <condition>: <body1> else: <body2> Decision structures Read: Chapter 7, Sections 8.1-8.2 from Chapter 8 from textbook Decisions about what to do next in a program are based on logical conditions: these are conditions that evaluate to either

More information

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures Python Programming, 2/e 1 Simple Decisions So far, we ve viewed programs as sequences of instructions that are followed

More information

Getting Started with Python

Getting Started with Python Fundamentals of Programming (Python) Getting Started with Python Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Python Programming: An Introduction to Computer Science Chapter 2 Python Programming, 2/e 1 Objectives n To be able to understand and write Python statements to output information to the screen, assign

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 2 Instructor: Long Ma The Department of Computer Science Review Install and test python Basic concept of computers Test simple

More information

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Python Programming: An Introduction to Computer Science Chapter 2 Writing Simple Programs Python Programming, 3/e 1 Objectives n To know the steps in an orderly software development process. n To understand

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 2 The Department of Computer Science Chapter 2 Elements of Programs-Objectives To be able to understand and write Python

More information

CITS 4406 Problem Solving & Programming

CITS 4406 Problem Solving & Programming CITS 4406 Problem Solving & Programming Tim French Lecture 02 The Software Development Process (These slides are based on John Zelle s powerpoint slides for lectures accompanied with the text book) Objectives

More information

Fundamentals of Programming (Python) Getting Started with Programming

Fundamentals of Programming (Python) Getting Started with Programming Fundamentals of Programming (Python) Getting Started with Programming Ali Taheri Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

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

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Simple Data Types There are a number of data types that are considered primitive in that they contain only a single value. These data

More information

Lecture Writing Programs. Richard E Sarkis CSC 161: The Art of Programming

Lecture Writing Programs. Richard E Sarkis CSC 161: The Art of Programming Lecture Writing Programs Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda To be able to understand and write Python statements to output information to the screen To assign values

More information

CS 105 Lab As a review of what we did last week a. What are two ways in which the Python shell is useful to us?

CS 105 Lab As a review of what we did last week a. What are two ways in which the Python shell is useful to us? 1 CS 105 Lab 3 The purpose of this lab is to practice the techniques of making choices and looping. Before you begin, please be sure that you understand the following concepts that we went over in class:

More information

Last Time. integer/float/string. import math math.sqrt() math.pi. Python Programming, 2/e 2

Last Time. integer/float/string. import math math.sqrt() math.pi. Python Programming, 2/e 2 1 Last Time integer/float/string import math math.sqrt() math.pi Python Programming, 2/e 2 Extra Ques:on from Lab 2 Using loops and two print statements, have Python print out the following: * * * * *

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 1 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

Python Lists: Example 1: >>> items=[apple, orange,100,25.5] >>> items[0] 'apple' >>> 3*items[:2] Python Lists: Lists are Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). All the items belonging to a list can be of different data type.

More information

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

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted

More information

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT Python The way of a program Srinidhi H Asst Professor Dept of CSE, MSRIT 1 Problem Solving Problem solving means the ability to formulate problems, think creatively about solutions, and express a solution

More information

Computer Science 217

Computer Science 217 Computer Science 217 Midterm Exam October 29, 2014 First Name: Last Name: ID: Class Time (Circle One): 1:00pm 3:00pm Instructions: Neatly print your names and ID number in the spaces provided above. Pick

More information

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

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners Getting Started Excerpted from Hello World! Computer Programming for Kids and Other Beginners EARLY ACCESS EDITION Warren D. Sande and Carter Sande MEAP Release: May 2008 Softbound print: November 2008

More information

Ch.2: Loops and lists

Ch.2: Loops and lists Ch.2: Loops and lists Joakim Sundnes 1,2 Hans Petter Langtangen 1,2 Simula Research Laboratory 1 University of Oslo, Dept. of Informatics 2 Aug 29, 2018 Plan for 28 August Short quiz on topics from last

More information

Lists, loops and decisions

Lists, loops and decisions Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence

More information

Python for Informatics

Python for Informatics Python for Informatics Exploring Information Version 0.0.6 Charles Severance Chapter 3 Conditional execution 3.1 Boolean expressions A boolean expression is an expression that is either true or false.

More information

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Chapter 5: Control Flow This chapter describes related to the control flow of a program. Topics include conditionals, loops,

More information

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

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications Hello World! Computer Programming for Kids and Other Beginners by Warren Sande and Carter Sande Chapter 1 Copyright 2009 Manning Publications brief contents Preface xiii Acknowledgments xix About this

More information

Not-So-Mini-Lecture 6. Modules & Scripts

Not-So-Mini-Lecture 6. Modules & Scripts Not-So-Mini-Lecture 6 Modules & Scripts Interactive Shell vs. Modules Launch in command line Type each line separately Python executes as you type Write in a code editor We use Atom Editor But anything

More information

Lecture 4: Basic I/O

Lecture 4: Basic I/O Lecture 4: Basic I/O CS1068+ Introductory Programming in Python Dr Kieran T. Herley Department of Computer Science University College Cork 2017-2018 KH (21/09/17) Lecture 4: Basic I/O 2017-2018 1 / 20

More information

NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION

NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION LESSON 15 NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION OBJECTIVE Learn to work with multiple criteria if statements in decision making programs as well as how to specify strings versus integers in

More information

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

Lab1. Introduction to Python. Lab 4: Selection Statement. Eng. Mai Z. Alyazji Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Introduction to Computers Lab (ENGG 1003) Lab1 Introduction to Python Lab 4: Selection Statement Eng. Mai Z. Alyazji In this

More information

Class extension and. Exception handling. Genome 559

Class extension and. Exception handling. Genome 559 Class extension and Exception handling Genome 559 Review - classes 1) Class constructors - class myclass: def init (self, arg1, arg2): self.var1 = arg1 self.var2 = arg2 foo = myclass('student', 'teacher')

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 06 Decision Structures Prof. Katherine Gibson Prof. Jeremy Dixon Based on concepts from: https://blog.udemy.com/python-if-else/ Last Class We Covered Just

More information

Variable and Data Type I

Variable and Data Type I Islamic University Of Gaza Faculty of Engineering Computer Engineering Department Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad September 24, 2016 Variable is reserved a location in memory to store

More information

UNDERSTANDING PROBLEMS AND HOW TO SOLVE THEM BY USING COMPUTERS

UNDERSTANDING PROBLEMS AND HOW TO SOLVE THEM BY USING COMPUTERS UNDERSTANDING PROBLEMS AND HOW TO SOLVE THEM BY USING COMPUTERS INTRODUCTION TO PROBLEM SOLVING Introduction to Problem Solving Understanding problems Data processing Writing an algorithm CONTINUE.. Tool

More information

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3] What is an Exception? Exception Handling BBM 101 - Introduction to Programming I Hacettepe University Fall 2016 Fuat Akal, Aykut Erdem, Erkut Erdem An exception is an abnormal condition (and thus rare)

More information

Lecture 1: Hello, MATLAB!

Lecture 1: Hello, MATLAB! Lecture 1: Hello, MATLAB! Math 98, Spring 2018 Math 98, Spring 2018 Lecture 1: Hello, MATLAB! 1 / 21 Syllabus Instructor: Eric Hallman Class Website: https://math.berkeley.edu/~ehallman/98-fa18/ Login:!cmfmath98

More information

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016 12. Logical Maneuvers Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except Loop-Body Returns Loop-Body Returns Another way to terminate a loop. Uses the fact that in a function, control

More information

Introduction to Computational Models Using Python

Introduction to Computational Models Using Python Introduction to Computational Models Using Python Slides 04 Department of Computer Science College of Computing and Software Engineering Kennesaw State University June, 2016 Lists A list in Python is simply

More information

PSEUDOCODE AND FLOWCHARTS. Introduction to Programming

PSEUDOCODE AND FLOWCHARTS. Introduction to Programming PSEUDOCODE AND FLOWCHARTS Introduction to Programming What s Pseudocode? Artificial and Informal language Helps programmers to plan an algorithm Similar to everyday English Not an actual programming language

More information

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except 12. Logical Maneuvers Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except Loop-Body Returns Loop-Body Returns Another way to terminate a loop. Uses the fact that in a function, control

More information

Introduction to python

Introduction to python Introduction to python 13 Files Rossano Venturini rossano.venturini@unipi.it File System A computer s file system consists of a tree-like structured organization of directories and files directory file

More information

Worlframalpha.com Facebook Report

Worlframalpha.com Facebook Report Worlframalpha.com Facebook Report For Tuesday: have read up through chapter 2 Next week will start chapter 3 New lab today: Simple Programs Integer division? o 1//3 o - 1//3 Range start at something other

More information

Programming to Python

Programming to Python Programming to Python Sept., 5 th Slides by M. Stepp, M. Goldstein, M. DiRamio, and S. Shah Compiling and interpreting Many languages require you to compile (translate) your program into a form that the

More information

>>> * *(25**0.16) *10*(25**0.16)

>>> * *(25**0.16) *10*(25**0.16) #An Interactive Session in the Python Shell. #When you type a statement in the Python Shell, #the statement is executed immediately. If the #the statement is an expression, its value is #displayed. #Lines

More information

Class extension and. Exception handling. Genome 559

Class extension and. Exception handling. Genome 559 Class extension and Exception handling Genome 559 Review - classes 1) Class constructors - class MyClass: def init (self, arg1, arg2): self.var1 = arg1 self.var2 = arg2 foo = MyClass('student', 'teacher')

More information

Selection Statement ( if )

Selection Statement ( if ) Islamic University Of Gaza Faculty of Engineering Computer Engineering Department Lab 4 Selection Statement ( if ) Eng. Ibraheem Lubbad October 10, 2016 In this lab we will constructs program that allow

More information

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an  . Michigan State University CSE 231, Fall 2013 CSE 231, Rich Enbody Office Hours After class By appointment send an email 2 1 Project 1 Python arithmetic Do with pencil, paper and calculator first Idle Handin Help room 3 What is a Computer Program?

More information

Python lab session 1

Python lab session 1 Python lab session 1 Dr Ben Dudson, Department of Physics, University of York 28th January 2011 Python labs Before we can start using Python, first make sure: ˆ You can log into a computer using your username

More information

Control structure: Selections

Control structure: Selections Control structure: Selections 01204111 Computers and Programming Chalermsak Chatdokmaiprai Department of Computer Engineering Kasetsart University Cliparts are taken from http://openclipart.org Revised

More information

Built-in Types of Data

Built-in Types of Data Built-in Types of Data Types A data type is set of values and a set of operations defined on those values Python supports several built-in data types: int (for integers), float (for floating-point numbers),

More information

University of Dublin

University of Dublin University of Dublin TRINITY COLLEGE Faculty of Enginering & Systems Sciences School of Engineering Junior Freshman Engineering Trinity Term 2014 Computer Engineering I (1E3) Date Location Time Dr L. Hederman

More information

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming Lecture Loops && Booleans Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda (In-)definite loops (for/while) Patterns: interactive loop and sentinel loop Solve problems using (possibly

More information

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19 1 Classes 2 Exceptions 3 Using Other Code 4 Problems Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, 2009 1 / 19 Start with an Example Python is object oriented Everything is an object

More information

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling COMP1730/COMP6730 Programming for Scientists Exceptions and exception handling Lecture outline * Errors * The exception mechanism in python * Causing exceptions (assert and raise) * Handling exceptions

More information

Variable and Data Type 2

Variable and Data Type 2 The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Intro. To Computers (LNGG 1003) Lab 3 Variable and Data Type 2 Eng. Ibraheem Lubbad March 2, 2017 Python Lists: Lists

More information

1. Consider the following code snippet. Describe what the user will see when it is executed.

1. Consider the following code snippet. Describe what the user will see when it is executed. These are some practice problems for your final. These problems only cover the "new" material we have covered since the last exam. However, your final will be cumulative, with approximately 50% on the

More information

Lecture 4. Defining Functions

Lecture 4. Defining Functions Lecture 4 Defining Functions Academic Integrity Quiz Reading quiz about the course AI policy Go to http://www.cs.cornell.edu/courses/cs11110/ Click Academic Integrity in side bar Read and take quiz in

More information

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS (download slides and.py files and follow along!) 6.0001 LECTURE 7 6.0001 LECTURE 7 1 WE AIM FOR HIGH QUALITY AN ANALOGY WITH SOUP You are making soup but bugs

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College August 31, 2015 Outline Outline 1 Chapter 1 Outline Textbook Data Structures and Algorithms Using Python and C++ David M.

More information

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1 Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1 Motivation In the programs we have written thus far, statements are executed one after the other, in the order in which they appear. Programs often

More information

Scripting Languages. Python basics

Scripting Languages. Python basics Scripting Languages Python basics Interpreter Session: python Direct conversation with python (>>>) Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright",

More information

Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont)

Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont) CP Lect 5 slide 1 Monday 2 October 2017 Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont) Cristina Alexandru Monday 2 October 2017 Last Lecture Arithmetic Quadratic equation

More information

CS150 Introduction to Computer Science 1. Logical Operators and if/else statement

CS150 Introduction to Computer Science 1. Logical Operators and if/else statement 1 Logical Operators and if/else statement 2 If Statement We may want to execute some code if an expression is true, and execute some other code when the expression is false. This can be done with two if

More information

SCHEME INTERPRETER GUIDE 4

SCHEME INTERPRETER GUIDE 4 SCHEME INTERPRETER GUIDE 4 COMPUTER SCIENCE 61A July 28, 2014 1 Scheme Values Back in Python, we had all these objects (i.e. lists, tuples, strings, integers) which inherited from the superclass object.

More information

ALGORITHMS AND FLOWCHARTS

ALGORITHMS AND FLOWCHARTS ALGORITHMS AND FLOWCHARTS ALGORITHMS AND FLOWCHARTS A typical programming task can be divided into two phases: Problem solving phase produce an ordered sequence of steps that describe solution of problem

More information

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A DEBUGGING TIPS COMPUTER SCIENCE 61A 1 Introduction Every time a function is called, Python creates what is called a stack frame for that specific function to hold local variables and other information.

More information

Cosmology with python: Beginner to Advanced in one week. Tiago Batalha de Castro

Cosmology with python: Beginner to Advanced in one week. Tiago Batalha de Castro Cosmology with python: Beginner to Advanced in one week Tiago Batalha de Castro What is Python? (From python.org) Python is an interpreted, object-oriented, high-level programming language with dynamic

More information

CSC A20H3 S 2011 Test 1 Duration 90 minutes Aids allowed: none. Student Number:

CSC A20H3 S 2011 Test 1 Duration 90 minutes Aids allowed: none. Student Number: CSC A20H3 S 2011 Test 1 Duration 90 minutes Aids allowed: none Last Name: Lecture Section: L0101 Student Number: First Name: Instructor: Bretscher Do not turn this page until you have received the signal

More information

The current topic: Python. Announcements. Python. Python

The current topic: Python. Announcements. Python. Python The current topic: Python Announcements! Introduction! reasons for studying languages! language classifications! simple syntax specification Object-oriented programming: Python Types and values Syntax

More information

82 2 Loops and Lists. Exercise 2.6: Compute energy levels in an atom The n-th energy level for an electron in a Hydrogen atom is given by

82 2 Loops and Lists. Exercise 2.6: Compute energy levels in an atom The n-th energy level for an electron in a Hydrogen atom is given by 82 2 Loops and Lists 2.7 Exercises Exercise 2.1: Make a Fahrenheit-Celsius conversion table Write a Python program that prints out a table with Fahrenheit degrees 0; 10; 20; : : : ; 100 in the first column

More information

Variable and Data Type I

Variable and Data Type I The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Intro. To Computers (LNGG 1003) Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad February 18, 2017 Variable is reserved

More information

A453 Task 1: Analysis: Problem: Solution:

A453 Task 1: Analysis: Problem: Solution: : Analysis: Problem: The problem I need to solve is that I need to design, code, and test a program that simulates a dice throw of a 4, 6, or 12 sided die and outputs the result before repeating the process

More information

Hello, World! EMT1111: Logic and Problem Solving Spring 2016 Dr. Mendoza

Hello, World! EMT1111: Logic and Problem Solving Spring 2016 Dr. Mendoza Hello, World! EMT1111: Logic and Problem Solving Spring 2016 Dr. Mendoza LESSON 7 (Labs): Complex Boolean Expressions and Loops Temperature with a function (temperature2.py) Write a Python program to ask

More information

Impera've Programming

Impera've Programming Impera've Programming Python Programs Interac)ve Input/Output One- Way and Two- Way if Statements for Loops User- Defined Func)ons Assignments Revisited and Parameter Passing Python program line1 = 'Hello

More information

UNIVERSITETET I OSLO

UNIVERSITETET I OSLO UNIVERSITETET I OSLO Det matematisk-naturvitenskapelige fakultet Examination in: IN1900 Introduction to programming with scientific applications Day of examination: Tuesday, October 10, 2017 Examination

More information

CS 221 Lecture. Tuesday, 4 October There are 10 kinds of people in this world: those who know how to count in binary, and those who don t.

CS 221 Lecture. Tuesday, 4 October There are 10 kinds of people in this world: those who know how to count in binary, and those who don t. CS 221 Lecture Tuesday, 4 October 2011 There are 10 kinds of people in this world: those who know how to count in binary, and those who don t. Today s Agenda 1. Announcements 2. You Can Define New Functions

More information

Python for C programmers

Python for C programmers Python for C programmers The basics of Python are fairly simple to learn, if you already know how another structured language (like C) works. So we will walk through these basics here. This is only intended

More information

Exception Handling. Genome 559

Exception Handling. Genome 559 Exception Handling Genome 559 Review - classes Use your own classes to: - package together related data - conceptually organize your code - force a user to conform to your expectations Class constructor:

More information

Exceptions & a Taste of Declarative Programming in SQL

Exceptions & a Taste of Declarative Programming in SQL Exceptions & a Taste of Declarative Programming in SQL David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 12 April 18, 2016 Computational Concepts

More information

9/18/11. Type casting, logical operators and if/else statement. Explicit Type Conversion. Example of Type Casting

9/18/11. Type casting, logical operators and if/else statement. Explicit Type Conversion. Example of Type Casting Type casting, logical operators and if/ statement 1 Explicit Type Conversion A type cast expression let s you manually change the data type of a value The syntax for type casting is static_cast(value)

More information

Errors. And How to Handle Them

Errors. And How to Handle Them Errors And How to Handle Them 1 GIGO There is a saying in computer science: Garbage in, garbage out. Is this true, or is it just an excuse for bad programming? Answer: Both. Here s what you want: Can you

More information

***********PYTHON PROGRAMS FOR CLASS XI ******************** """ Program to Calculate Simple Interest """ p = eval(input("enter Principle?

***********PYTHON PROGRAMS FOR CLASS XI ********************  Program to Calculate Simple Interest  p = eval(input(enter Principle? ***********PYTHON PROGRAMS FOR CLASS XI ******************** 1. """ Program to Calculate Simple Interest """ p = eval(input("enter Principle? ")) r = eval(input("enter Rate? ")) t = eval(input("enter Time?

More information