Iteration. Chapter 7. Prof. Mauro Gaspari: Mauro Gaspari - University of Bologna -

Size: px
Start display at page:

Download "Iteration. Chapter 7. Prof. Mauro Gaspari: Mauro Gaspari - University of Bologna -"

Transcription

1 Iteration Chapter 7 Prof. Mauro Gaspari: gaspari@cs.unibo.it

2 Multiple assigments bruce = 5 print bruce, bruce = 7 print bruce

3 Assigment and equality With multiple assignment it is especially important to distinguish between an assignment operation (=) and a statement of equality (==). Equality is a symmetric relation and assignment is not. Furthermore, in mathematics, a statement of equality is either true or false, for all time. If a = b now, then a will always equal b. In Python, an assignment statement can make two variables equal, but they don t have to stay that way: a = 5 b = a # a and b are now equal a = 3 # a and b are no longer equal

4 Updating variables One of the most common forms of multiple assignment is an update, where the new value of the variable depends on the old. X = X + 1 If you try to update a variable that doesn t exist, you get an error. Before you can update a variable, you have to initialize it, usually with a simple assignment: Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement.

5 Iteration Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. We can program repetition with recursion, however: The programming task is sometimes difficult. Maximum recursion depth problem. Python provides several language features to make repetition easier. One is the while statement and another is the for statement.

6 The while statement: def countdown(n): while n > 0: print n n = n 1 print "Blastoff!" Note: recursion is not used. You can almost read the while statement as if it were English. It means, While n is greater than 0, display the value of n and then reduce the value of n by 1. When the condition becomes false the while terminates and the next instruction is executed.

7 Semantics of while 1) Evaluate the boolean condition. 2) If the condition is false, exit the while statement and continue execution at the next statement. 3) If the condition is true, execute the body and then go back to step 1. This type of flow is called a loop because the third step loops back around to the top. The body of the loop should change the value of one or more. variables so that eventually the condition becomes false and the loop terminates. Otherwise the loop will repeat forever (infinite loop).

8 Examples def nlines(n): while n!= 0: print n = n 1 What happens if you remove the last line?

9 Try this example while True: print Sorry

10 break Sometimes you don t know it s time to end a loop until you get half way through the body. In that case you can use the break statement to jump out of the loop. Suppose you want to take input from the user until they type exit. while True: line = raw_input('>> ') if line == 'exit': break print line print 'Stopped!'

11 Exercise 1 Write a dummy python interpreter using while and break to exit. The dummy interpeter returns False when reads True and viceversa, otherwise always returns syntax error.

12 Tables One of the things loops are good for is generating tabular data. Tables can be useful for displaying financial data. As characters and strings are displayed on the screen, an invisible marker called the cursor keeps track of where the next character will go. After a print statement, the cursor normally goes to the beginning of the next line. The tab character shifts the cursor to the right until it reaches one of the tab stops. Tabs are useful for making columns of text line up.

13 Example of a table The following program outputs a sequence of values in the left column and their logarithms in the right column: import math x = 1.0 while x < 20.0: print x, '\t', math.log(x) x = x + 1.0

14 Considerations Remember that the log function uses base e. Since powers of two are so important in computer science, we often want to find logarithms with respect to base 2. To do that, we can use the following formula: log 2 (x) = log e (x)/log e (2) The log 2 table can be computed changing the output statement to: print x, '\t', math.log(x)/math.log(2.0)

15 Exercise 2 Modify the program to show logarithms of other powers of two only. Hint: x should be a power of two.

16 A string is a sequence A string is a sequence of characters. You can access the characters one at a time with the bracket operator: Example >>> fruit = "banana" >>> letter = fruit[1] >>> print letter a The expression in brackets is called an index. Why 'a'??? The first letter of banana is not 'a'.

17 Understanding strings The index is an offset from the beginning of the string, and the offset of the first letter is 0. So if a string has n chars its indexes ranges from 0 to n-1. You can use any expression, including variables and operators, as an index, but the value of the index has to be an integer. >>> letter = fruit[0] >>> letter2 = banana [0] >>> print letter b >>> type(letter) <type 'str'> >>> print letter2 b

18 Length of a string: len >>> fruit = "banana" >>> len(fruit) 6 Accessing the last letter: length = len(fruit) last = fruit[length] last = fruit[length 1] # ERROR!

19 Traversal with a for loop index = 0 while index < len(fruit): letter = fruit[index] print letter index = index + 1 It is possible to specify this in this way: for char in fruit: print char

20 Example >>>prefixes = "JKLMNOPQ" >>>suffix = "ack" >>>for letter in prefixes:... print letter + suffix Jack Kack Lack Mack Nack Oack Pack Qack

21 Exercise 3 Write a function indent_string(n,string) which prints the string n+1 times indenting it from 0 to n as follows: indent_string(5, duffy ) duffy duffy duffy duffy duffy duffy n+1 Hint: use the expression ' '*i to print i blanks.

22 Exercise 4 GREATEST COMMON DIVISOR IMPERATIVE KNOWLEDGE (EUCLID) IF A<B, exchange A and B. Divide A by B and get the remainder, R. If R=0, GCD(A,B) = B. Replace A by B and replace B by R. Return to the previous step. Write a function gcd that takes two arguments and returns the greatest common divisor.

Functions and Recursion

Functions and Recursion Functions and Recursion Chapter 5 Prof. Mauro Gaspari: gaspari@cs.unibo.it Example import math def area(radius): temp = math.pi * radius**2 return temp # or def area(radius): return math.pi * radius**2

More information

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment Iteration 6.1. Multiple assignment As you may have discovered, it is legal to make more than one assignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop

More information

Unit 2. Srinidhi H Asst Professor

Unit 2. Srinidhi H Asst Professor Unit 2 Srinidhi H Asst Professor 1 Iterations 2 Python for Loop Statements for iterating_var in sequence: statements(s) 3 Python for While Statements while «expression»: «block» 4 The Collatz 3n + 1 sequence

More information

The second statement selects character number 1 from and assigns it to.

The second statement selects character number 1 from and assigns it to. Chapter 8 Strings 8.1 A string is a sequence A string is a sequence of characters. You can access the characters one at a time with the bracket operator: The second statement selects character number 1

More information

Chapter 7. Iteration. 7.1 Multiple assignment

Chapter 7. Iteration. 7.1 Multiple assignment Chapter 7 Iteration 7.1 Multiple assignment You can make more than one assignment to the same variable; effect is to replace the old value with the new. int bob = 5; System.out.print(bob); bob = 7; System.out.println(bob);

More information

Conditionals and Recursion. Python Part 4

Conditionals and Recursion. Python Part 4 Conditionals and Recursion Python Part 4 Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print (remainder) 1 Boolean expressions An expression that

More information

Week - 01 Lecture - 03 Euclid's Algorithm for gcd. Let us continue with our running example of gcd to explore more issues involved with program.

Week - 01 Lecture - 03 Euclid's Algorithm for gcd. Let us continue with our running example of gcd to explore more issues involved with program. Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 01 Lecture - 03 Euclid's Algorithm

More information

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

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

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

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 2 Control 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Control: A Quick Overview 2 Selection

More information

DM536 Introduction to Programming. Peter Schneider-Kamp.

DM536 Introduction to Programming. Peter Schneider-Kamp. DM536 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm536/! DEFINING FUNCTIONS 2 Function Definitions functions are defined using the following grammar

More information

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

CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi CMPT 120 Control Structures in Python Summer 2012 Instructor: Hassan Khosravi The If statement The most common way to make decisions in Python is by using the if statement. The if statement allows you

More information

At full speed with Python

At full speed with Python At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3

More information

Text Input and Conditionals

Text Input and Conditionals Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

More information

Introduction to Python (All the Basic Stuff)

Introduction to Python (All the Basic Stuff) Introduction to Python (All the Basic Stuff) 1 Learning Objectives Python program development Command line, IDEs, file editing Language fundamentals Types & variables Expressions I/O Control flow Functions

More information

Conditionals !

Conditionals ! Conditionals 02-201! Computing GCD GCD Problem: Compute the greatest common divisor of two integers. Input: Two integers a and b. Output: The greatest common divisor of a and b. Exercise: Design an algorithm

More information

Lecture Notes on Contracts

Lecture Notes on Contracts Lecture Notes on Contracts 15-122: Principles of Imperative Computation Frank Pfenning Lecture 2 August 30, 2012 1 Introduction For an overview the course goals and the mechanics and schedule of the course,

More information

Names and Functions. Chapter 2

Names and Functions. Chapter 2 Chapter 2 Names and Functions So far we have built only tiny toy programs. To build bigger ones, we need to be able to name things so as to refer to them later. We also need to write expressions whose

More information

Repetition, Looping CS101

Repetition, Looping CS101 Repetition, Looping CS101 Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

More information

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

Python review. 1 Python basics. References. CS 234 Naomi Nishimura Python review CS 234 Naomi Nishimura The sections below indicate Python material, the degree to which it will be used in the course, and various resources you can use to review the material. You are not

More information

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

Decisions, Decisions. Testing, testing C H A P T E R 7 C H A P T E R 7 In the first few chapters, we saw some of the basic building blocks of a program. We can now make a program with input, processing, and output. We can even make our input and output a little

More information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

More information

CS 1301 CS1 with Robots Summer 2007 Exam 1

CS 1301 CS1 with Robots Summer 2007 Exam 1 Your Name: 1 / 6 CS 1301 CS1 with Robots Summer 2007 Exam 1 1. Vocabulary Matching: (15 points) Write the number from the correct definition in the blank next to each term on the left: _12_Print statement

More information

1/11/2010 Topic 2: Introduction to Programming 1 1

1/11/2010 Topic 2: Introduction to Programming 1 1 Topic 2: Introduction to Programming g 1 1 Recommended Readings Chapter 2 2 2 Computer Programming Gain necessary knowledge of the problem domain Analyze the problem, breaking it into pieces Repeat as

More information

LOOPS. Repetition using the while statement

LOOPS. Repetition using the while statement 1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while

More information

Python: Functions. Thomas Schwarz, SJ Marquette University

Python: Functions. Thomas Schwarz, SJ Marquette University Python: Functions Thomas Schwarz, SJ Marquette University History Early computer programming was difficult Not only because interacting with the computer was difficult Data was entered by setting switches,

More information

DM536 Introduction to Programming. Peter Schneider-Kamp.

DM536 Introduction to Programming. Peter Schneider-Kamp. DM536 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm536/! Python & Linux Install Party next week (Tuesday 14-17) NEW Fredagsbar ( Nedenunder ) Participants

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

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016 Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada Under Supervision of: Dr. Richard Kelley Chief Engineer, NAASIC March 6th, 2016 Science Technology Engineering

More information

Loops. In Example 1, we have a Person class, that counts the number of Person objects constructed.

Loops. In Example 1, we have a Person class, that counts the number of Person objects constructed. Loops Introduction In this article from my free Java 8 course, I will discuss the use of loops in Java. Loops allow the program to execute repetitive tasks or iterate over vast amounts of data quickly.

More information

What is recursion? Recursion. How can a function call itself? Recursive message() modified. contains a reference to itself. Week 7. Gaddis:

What is recursion? Recursion. How can a function call itself? Recursive message() modified. contains a reference to itself. Week 7. Gaddis: Recursion What is recursion? Week 7! Generally, when something contains a reference to itself Gaddis:19.1-19.4! Math: defining a function in terms of itself CS 5301 Fall 2013 Jill Seaman 1! Computer science:

More information

DM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp.

DM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp. DM536 / DM550 Part 1 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm536/! RECURSION 2 Recursion a function can call other functions a function can

More information

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

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture 18 Switch Statement (Contd.) And Introduction to

More information

CS1 Lecture 3 Jan. 18, 2019

CS1 Lecture 3 Jan. 18, 2019 CS1 Lecture 3 Jan. 18, 2019 Office hours for Prof. Cremer and for TAs have been posted. Locations will change check class website regularly First homework assignment will be available Monday evening, due

More information

Chapter 4. Conditionals and recursion. 4.1 The modulus operator. 4.2 Conditional execution

Chapter 4. Conditionals and recursion. 4.1 The modulus operator. 4.2 Conditional execution Chapter 4 Conditionals and recursion 4.1 The modulus operator The modulus operator works on integers (and integer expressions) and yields the remainder when the first operand is divided by the second.

More information

Conditionals: Making Choices

Conditionals: Making Choices Announcements ry to get help from me and tutors Reading assignment for this week: Chapters 5 and 6 of Downey Conditionals: Making Choices When you see a page on the web, be sure to reload it to see the

More information

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn CPS109 Course Notes 6 Alexander Ferworn Unrelated Facts Worth Remembering Use metaphors to understand issues and explain them to others. Look up what metaphor means. Table of Contents Contents 1 ITERATION...

More information

CS 102 Lab 3 Fall 2012

CS 102 Lab 3 Fall 2012 Name: The symbol marks programming exercises. Upon completion, always capture a screenshot and include it in your lab report. Email lab report to instructor at the end of the lab. Review of built-in functions

More information

Week - 01 Lecture - 04 Downloading and installing Python

Week - 01 Lecture - 04 Downloading and installing Python Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 01 Lecture - 04 Downloading and

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

Controls Structure for Repetition

Controls Structure for Repetition Controls Structure for Repetition So far we have looked at the if statement, a control structure that allows us to execute different pieces of code based on certain conditions. However, the true power

More information

Compound Data Types 1

Compound Data Types 1 Compound Data Types 1 Chapters 8, 10 Prof. Mauro Gaspari: mauro.gaspari@unibo.it Compound Data Types Strings are compound data types: they are sequences of characters. Int and float are scalar data types:

More information

Number System. Introduction. Natural Numbers (N) Whole Numbers (W) Integers (Z) Prime Numbers (P) Face Value. Place Value

Number System. Introduction. Natural Numbers (N) Whole Numbers (W) Integers (Z) Prime Numbers (P) Face Value. Place Value 1 Number System Introduction In this chapter, we will study about the number system and number line. We will also learn about the four fundamental operations on whole numbers and their properties. Natural

More information

Variables, expressions and statements

Variables, expressions and statements Variables, expressions and statements 2.1. Values and data types A value is one of the fundamental things like a letter or a number that a program manipulates. The values we have seen so far are 2 (the

More information

Flow Control: Branches and loops

Flow Control: Branches and loops Flow Control: Branches and loops In this context flow control refers to controlling the flow of the execution of your program that is, which instructions will get carried out and in what order. In the

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 02 / 15 / 2016 Instructor: Michael Eckmann Questions? Comments? Loops to repeat code while loops for loops do while loops Today s Topics Logical operators Example

More information

If Statements, For Loops, Functions

If Statements, For Loops, Functions Fundamentals of Programming If Statements, For Loops, Functions Table of Contents Hello World Types of Variables Integers and Floats String Boolean Relational Operators Lists Conditionals If and Else Statements

More information

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors First Program Compilation and Execution Simplifying Fractions Loops If Statements Variables Operations Using Functions Errors C++ programs consist of a series of instructions written in using the C++ syntax

More information

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself?

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself? Recursion Chapter 8 CS 3358 Summer I 2012 Jill Seaman What is recursion? Generally, when something contains a reference to itself Math: defining a function in terms of itself Computer science: when a function

More information

Topic 2: Introduction to Programming

Topic 2: Introduction to Programming Topic 2: Introduction to Programming 1 Textbook Strongly Recommended Exercises The Python Workbook: 12, 13, 23, and 28 Recommended Exercises The Python Workbook: 5, 7, 15, 21, 22 and 31 Recommended Reading

More information

(Refer Slide Time: 00:26)

(Refer Slide Time: 00:26) Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute Technology, Madras Module 07 Lecture 07 Contents Repetitive statements

More information

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

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control Chapter 2 Control, Quick Overview Control Selection Selection Selection is how programs make choices, and it is the process of making choices that provides a lot of the power of computing 1 Python if statement

More information

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

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison

More information

How to Design Programs

How to Design Programs How to Design Programs How to (in Racket): represent data variants trees and lists write functions that process the data See also http://www.htdp.org/ 1 Running Example: GUIs Pick a fruit: Apple Banana

More information

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Loops and Files Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Chapter Topics o The Increment and Decrement Operators o The while Loop o Shorthand Assignment Operators o The do-while

More information

Introduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Introduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Introduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture - 23 Introduction to Arduino- II Hi. Now, we will continue

More information

Repetition CSC 121 Fall 2014 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal Repetition CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

CSCE 110: Programming I

CSCE 110: Programming I CSCE 110: Programming I Sample Questions for Exam #1 February 17, 2013 Below are sample questions to help you prepare for Exam #1. Make sure you can solve all of these problems by hand. For most of the

More information

Lecture Notes for Chapter 2: Getting Started

Lecture Notes for Chapter 2: Getting Started Instant download and all chapters Instructor's Manual Introduction To Algorithms 2nd Edition Thomas H. Cormen, Clara Lee, Erica Lin https://testbankdata.com/download/instructors-manual-introduction-algorithms-2ndedition-thomas-h-cormen-clara-lee-erica-lin/

More information

Built-in functions. You ve used several functions already. >>> len("atggtca") 7 >>> abs(-6) 6 >>> float("3.1415") >>>

Built-in functions. You ve used several functions already. >>> len(atggtca) 7 >>> abs(-6) 6 >>> float(3.1415) >>> Functions Built-in functions You ve used several functions already len("atggtca") 7 abs(-6) 6 float("3.1415") 3.1415000000000002 What are functions? A function is a code block with a name def hello():

More information

Compound Data Types 2

Compound Data Types 2 Compound Data Types 2 Chapters 10, 11, 12 Prof. Mauro Gaspari: gaspari@cs.unibo.it Objects and Values We know that a and b both refer to a string, but we don t know whether they refer to the same string.

More information

Units 0 to 4 Groovy: Introduction upto Arrays Revision Guide

Units 0 to 4 Groovy: Introduction upto Arrays Revision Guide Units 0 to 4 Groovy: Introduction upto Arrays Revision Guide Second Year Edition Name: Tutorial Group: Groovy can be obtained freely by going to http://groovy-lang.org/download Page 1 of 8 Variables Variables

More information

Solutions to the Second Midterm Exam

Solutions to the Second Midterm Exam CS/Math 240: Intro to Discrete Math 3/27/2011 Instructor: Dieter van Melkebeek Solutions to the Second Midterm Exam Problem 1 This question deals with the following implementation of binary search. Function

More information

Introduction to Python Programming

Introduction to Python Programming advances IN SYSTEMS AND SYNTHETIC BIOLOGY 2018 Anna Matuszyńska Oliver Ebenhöh oliver.ebenhoeh@hhu.de Ovidiu Popa ovidiu.popa@hhu.de Our goal Learning outcomes You are familiar with simple mathematical

More information

COMPSCI 230 Discrete Math Prime Numbers January 24, / 15

COMPSCI 230 Discrete Math Prime Numbers January 24, / 15 COMPSCI 230 Discrete Math January 24, 2017 COMPSCI 230 Discrete Math Prime Numbers January 24, 2017 1 / 15 Outline 1 Prime Numbers The Sieve of Eratosthenes Python Implementations GCD and Co-Primes COMPSCI

More information

Programming Training. Main Points: - Python Statements - Problems with selections.

Programming Training. Main Points: - Python Statements - Problems with selections. Programming Training Main Points: - Python Statements - Problems with selections. print() print(value1, value2, ) print( var =, var1) # prints the text var= followed by the value of var print( Here is

More information

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program Overview - General Data Types - Categories of Words - The Three S s - Define Before Use - End of Statement - My First Program a description of data, defining a set of valid values and operations List of

More information

Chapter 5: Control Structures

Chapter 5: Control Structures Chapter 5: Control Structures What we will learn: Selection structures Loops What you need to know before: Data types Functions For loop While loop If selection If else structures Control structures are

More information

CS1 Lecture 3 Jan. 22, 2018

CS1 Lecture 3 Jan. 22, 2018 CS1 Lecture 3 Jan. 22, 2018 Office hours for me and for TAs have been posted, locations will change check class website regularly First homework available, due Mon., 9:00am. Discussion sections tomorrow

More information

AP Computer Science A

AP Computer Science A AP Computer Science A 1st Quarter Notes Table of Contents - section links Click on the date or topic below to jump to that section Date : 9/8/2017 Aim : Java Basics Objects and Classes Data types: Primitive

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

ELEMENTARY NUMBER THEORY AND METHODS OF PROOF

ELEMENTARY NUMBER THEORY AND METHODS OF PROOF CHAPTER 4 ELEMENTARY NUMBER THEORY AND METHODS OF PROOF Copyright Cengage Learning. All rights reserved. SECTION 4.8 Application: Algorithms Copyright Cengage Learning. All rights reserved. Application:

More information

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

CS 115 Lecture 4. More Python; testing software. Neil Moore CS 115 Lecture 4 More Python; testing software Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 8 September 2015 Syntax: Statements A statement

More information

Unit 6 - Software Design and Development LESSON 3 KEY FEATURES

Unit 6 - Software Design and Development LESSON 3 KEY FEATURES Unit 6 - Software Design and Development LESSON 3 KEY FEATURES Last session 1. Language generations. 2. Reasons why languages are used by organisations. 1. Proprietary or open source. 2. Features and tools.

More information

1 Elementary number theory

1 Elementary number theory Math 215 - Introduction to Advanced Mathematics Spring 2019 1 Elementary number theory We assume the existence of the natural numbers and the integers N = {1, 2, 3,...} Z = {..., 3, 2, 1, 0, 1, 2, 3,...},

More information

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

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops PRG PROGRAMMING ESSENTIALS 1 Lecture 2 Program flow, Conditionals, Loops https://cw.fel.cvut.cz/wiki/courses/be5b33prg/start Michal Reinštein Czech Technical University in Prague, Faculty of Electrical

More information

CS 1301 Exam 1 Answers Fall 2009

CS 1301 Exam 1 Answers Fall 2009 Page 1/6 CS 1301 Fall 2009 Exam 1 Your Name: I commit to uphold the ideals of honor and integrity by refusing to betray the trust bestowed upon me as a member of the Georgia Tech community. CS 1301 Exam

More information

Introduction. C provides two styles of flow control:

Introduction. C provides two styles of flow control: Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

More information

Control structure: Repetition - Part 2

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

More information

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Register Machines. Connecting evaluators to low level machine code

Register Machines. Connecting evaluators to low level machine code Register Machines Connecting evaluators to low level machine code 1 Plan Design a central processing unit (CPU) from: wires logic (networks of AND gates, OR gates, etc) registers control sequencer Our

More information

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself? contains a reference to itself.

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself? contains a reference to itself. Recursion Chapter 8 CS 3358 Summer II 2013 Jill Seaman What is recursion?! Generally, when something contains a reference to itself! Math: defining a function in terms of itself! Computer science: when

More information

More Programming Constructs -- Introduction

More Programming Constructs -- Introduction More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and

More information

Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona

Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona Defining Functions CSc 372 Comparative Programming Languages 5 : Haskell Function Definitions Department of Computer Science University of Arizona collberg@gmail.com When programming in a functional language

More information

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Real Python: Python 3 Cheat Sheet

Real Python: Python 3 Cheat Sheet Real Python: Python 3 Cheat Sheet Numbers....................................... 3 Strings........................................ 5 Booleans....................................... 7 Lists.........................................

More information

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid: 1 STRINGS Objectives: How text data is internally represented as a string Accessing individual characters by a positive or negative index String slices Operations on strings: concatenation, comparison,

More information

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

THE AUSTRALIAN NATIONAL UNIVERSITY Mid Semester Examination September COMP1730 / COMP6730 Programming for Scientists THE AUSTRALIAN NATIONAL UNIVERSITY Mid Semester Examination September 2016 COMP1730 / COMP6730 Programming for Scientists Study Period: 15 minutes Time Allowed: 2 hours Permitted Materials: One A4 page

More information

Chapter 9: Dealing with Errors

Chapter 9: Dealing with Errors Chapter 9: Dealing with Errors What we will learn: How to identify errors Categorising different types of error How to fix different errors Example of errors What you need to know before: Writing simple

More information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

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

Statements 2. a operator= b a = a operator b Statements 2 Outline Note: i=i+1 is a valid statement. Don t confuse it with an equation i==i+1 which is always false for normal numbers. The statement i=i+1 is a very common idiom: it just increments

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

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

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators JAVA Standard Edition Java - Basic Operators Java provides a rich set of operators to manipulate variables.

More information

SNS COLLEGE OF ENGINEERING,

SNS COLLEGE OF ENGINEERING, SNS COLLEGE OF ENGINEERING, COIMBATORE Department of Computer Science and Engineering QUESTION BANK(PART A) GE8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING TWO MARKS UNIT-I 1. What is computer? Computers

More information

Problem Solving for Intro to Computer Science

Problem Solving for Intro to Computer Science Problem Solving for Intro to Computer Science The purpose of this document is to review some principles for problem solving that are relevant to Intro to Computer Science course. Introduction: A Sample

More information

Reading 8 : Recursion

Reading 8 : Recursion CS/Math 40: Introduction to Discrete Mathematics Fall 015 Instructors: Beck Hasti, Gautam Prakriya Reading 8 : Recursion 8.1 Recursion Recursion in computer science and mathematics refers to the idea of

More information

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk Control Statements ELEC 206 Prof. Siripong Potisuk 1 Objectives Learn how to change the flow of execution of a MATLAB program through some kind of a decision-making process within that program The program

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

Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore

Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore Lecture - 20 Intermediate code generation Part-4 Run-time environments

More information

Test #2 October 8, 2015

Test #2 October 8, 2015 CPSC 1040 Name: Test #2 October 8, 2015 Closed notes, closed laptop, calculators OK. Please use a pencil. 100 points, 5 point bonus. Maximum score 105. Weight of each section in parentheses. If you need

More information

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

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the

More information