Input and typing trouble! print 'Please input a number of meters' meters = input() # get input from user cm = meters * 100 # convert to centimeters print.

Slides:



Advertisements
Similar presentations
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Advertisements

Programming TBE 540 Farah Fisher. Objectives After viewing this presentation, the learner will be able to… Given a task, create pseudocode Given pseudocode,
EECS 110: Lec 11: Indefinite Loops and Program Design Aleksandar Kuzmanovic Northwestern University
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Computer Science 1620 Programming & Problem Solving.
Complexity (Running Time)
Fundamentals of Python: From First Programs Through Data Structures
Adapted from slides by Marie desJardins
CS140: Intro to CS An Overview of Programming in C by Erin Chambers.
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Fundamentals of Python: First Programs
An Introduction to Textual Programming
by Chris Brown under Prof. Susan Rodger Duke University June 2012
High-Level Programming Languages: C++
CIS Computer Programming Logic
Introduction to Python
* What kind of loop would I use to complete the following: A. Output all of the prime numbers that are less than 100,000 B. Output the Fibonacci sequence.
Algorithmic Problem Solving CMSC 201 Adapted from slides by Marie desJardins (Spring 2015 Prof Chang version)
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Chapter 2 - Algorithms and Design
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
Now String theory To Do: Lists This stuff hurts my brane. when you learn string theory from google images… Goal: Thinking like a machine You should now.
Today  Table/List operations  Parallel Arrays  Efficiency and Big ‘O’  Searching.
Flow of Control Part 1: Selection
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
IS 313: Putting loops to work for you What's next? [ 1, 11, 21, 1211, , ? ] [ -35, -24, -13, -2, 9, 20, 31, ? ] [ 2, 22, 222, ? ] [ 26250, 5250,
CSC 211 Data Structures Lecture 13
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping with.
EECS 110: Lec 11: Indefinite Loops and Program Design Aleksandar Kuzmanovic Northwestern University
1 Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping.
For loops in programming Assumes you have seen assignment statements and print statements.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
PROGRAMMING In Lesson 2. STARTER ACTIVITY Complete the starter activity in your python folder – lesson 2 Now we will see how you got on and update your.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
CS140: Intro to CS An Overview of Programming in C by Erin Chambers.
Course A201: Introduction to Programming 09/30/2010.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Homework 8 Due ( MT sections ) ( WTh sections ) at midnight Sun., 10/28 Mon., 10/29 Problems Reading is under week 7, however.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
EECS 110: Lec 3: Data Aleksandar Kuzmanovic Northwestern University
EGR 115 Introduction to Computing for Engineers Branching & Program Design – Part 3 Friday 03 Oct 2014 EGR 115 Introduction to Computing for Engineers.
Controlling Program Flow with Decision Structures.
ALGORITHMS AND FLOWCHARTS. Why Algorithm is needed? 2 Computer Program ? Set of instructions to perform some specific task Is Program itself a Software.
GCSE Computing: Programming GCSE Programming Remembering Python.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Loops Brent M. Dingle Texas A&M University Chapter 6 – Section 6.3 Multiway Branches (and some from Mastering Turbo Pascal 5.5, 3 rd Edition by Tom Swan)
Introduction to Python
EECS 110: Lec 11: Indefinite Loops and Program Design
ECS10 10/10
Programming 101 Programming for non-programmers.
While Loops in Python.
EECS 110: Lec 10: Definite Loops and User Input
Lesson 2 Programming constructs – Algorithms – Scratch – Variables Intro.
Input and typing trouble!
For -G7 programing language Teacher / Shamsa Hassan Alhassouni.
TIPS: How to Be Successful
Module 4 Loops.
Flowcharts and Pseudo Code
While Loops in Python.
Presentation transcript:

Input and typing trouble! print 'Please input a number of meters' meters = input() # get input from user cm = meters * 100 # convert to centimeters print ('That is', cm, 'cm.’) # print out the result What is python thinking ?!?

Fix #1: use a type converter print 'Please input a number of meters' meters = int(input()) cm = meters * 100 print ('That is', cm, 'cm.’) check out my newly installed int converter! The type of variable (box) matters! name: meters type: int name: cm type: int 1 100

Fix #1: use a type converter print 'Please input a number of meters' meters = int(input()) # get int input from user cm = meters * 100 print ('That is', cm, 'cm.’) print 'Please input a number of meters' meters = float(input()) # get float input from user cm = meters * 100 print ('That is', cm, 'cm.’) str converts to string type

Fix #2: use input() print 'Please input a number of meters' meters = eval(input()) # get processed input from user cm = meters * 100 print ('That is', cm, 'cm.’) Why not ALWAYS use eval() ?

Fix #2: use input() print 'Please input a number of meters' meters = eval(input()) # get processed input from user cm = meters * 100 print 'That is', cm, 'cm.' Why not ALWAYS use input() ? input() always returns input as a string! eval(s) processes string s as if typed into Python Input allows you to specify a prompt string

input vs. eval(input()) reply = input( 'Enter a string and I\'ll tell you what I see.' ) for c in reply: print ('I see a(n) ', c) interprets what the user types as a string of characters reply = eval(input( 'Enter any list and I\'ll tell you what I see.' )) for c in reply: print ('I see a(n) ', c) processes what the user types just as python would

import random escape = 0 while escape != 42: print ('Help! Let me out!’) escape = random.choice([41,42,43]) print ('At last!’) how could we make it easier/harder to escape? how could we count the number of loops we run? Give me a break ! Every while loop can be a while True: loop! I'll figure out later how to get out of this loop! OK – I'll stop when the guess is correct! Try it!

I've always thought there were indeed two kinds of people in the world - those who divide the world into two kinds of people, and those who don't. The boolean type There are 10 kinds of people in the world: those who understand binary, and those who don't.

The boolean type is either True or False. It's needed in if and while statements: if test: print ('test was True!’) do something more … while test: print ('test was True!’) do something more … You can even convert to the boolean type with bool bool(42) bool('hi') bool([1,2,3]) these both have to be boolean.

A guessing game… import random myNumber = random.choice(range(1000)) yourGuess = -1 while yourGuess != myNumber: yourGuess = eval(input('Guess my number: ')) print ('You got it! It was', myNumber) This is too difficult! Notice – we don't know how many times we need to loop!

Give me a break ! import random myNumber = random.randrange(0,1000) while True: yourGuess = input('Guess my number: ') if yourGuess == myNumber: break print 'You got it! It was', myNumber Every while loop can be a while True: loop! I'll figure out later how to get out of this loop! OK – I'll stop when the guess is correct! Try it!

Loops ! Hey, could you change the channel? And some more chips would be nice…. for c in 'a gratuitously big string': print ('I see a(n) ', c) print 'Phew! Can I go watch TV now?' A three-line program… this is a for loop you can use any variable name you want! c will become each item in the list once for each value of c, the computer does everything in the loop (the indented block) this can be ANY list, even a variable! This will not happen until after the for loop is finished.

Loops ! Hey, could you change the channel? And some more chips would be nice…. Who (or what) should be doing most of the work around here ?!! reply = input( 'Enter a string and I\'ll tell you what I see.' ) for c in reply: print ('I see a(n) ', c) What if we input a list here? this can be ANY list, even a variable! (and not just a string…)

Accumulating an answer… Suppose we want to find and print the sum of an arbitrary list: [ 9, 42, 1, 77, 15, 76, 100, -5, 3.14 ] How could we use a loop? Try it out! L = eval(input('Enter a list '))

Accumulating an answer… L = eval(input('Enter a list ')) sumSoFar = 0 for x in L: sumSoFar = sumSoFar + x print ('sum is', sumSoFar) Finding the sum of a list: shortcut available! No return needed if you are just printing the value! Accumulator!

Typing trouble! print ('Please input a number of meters’) meters = input() # get input from user cm = meters * 100 # convert to centimeters print ('That is', cm, 'cm.’) # print out the result The type of variable (box) matters! name: meters type: string name: cm type: string '1' '111…11' (100 of them!) Variables are registers or storage spaces… how to fix this?

Smaller of Two… print 'Please input two numbers' n1 = eval(input()) n2 = eval(input()) if n1 > n2: print ('The smaller number is', n2) else: print ('The smaller number is', n1) for the visually minded… ?

minOf2 print a message get n1 get n2 is n1>n2 ? TRUEFALSE print that n2 is the min print that n1 is the min Flow Chart ifelse print 'Please input two numbers' n1 = eval(input()) n2 = eval(input()) if n1 > n2: print ('The smaller number is', n2) else: print ('The smaller number is', n1)

Accumulate! print 'Please input two numbers' n1 = eval(input()) n2 = eval(input()) if n1 > n2: min = n2 else: min = n1 print ('The minOf2 is', min) Accumulator min what's different here?

print 'Please input two numbers' n1 = eval(input()) n2 = eval(input()) if n1 > n2: min = n2 else: min = n1 print ('The minOf2 is', min) Smaller of Two… print a message get n1 get n2 is n1>n2 ? TRUEFALSE print min set min to be n1 ifelse set min to be n1 Accumulator min

One problem Two algorithms Both are correct. Which is easier to extend to minOf3 ? print a message get n1 get n2 is n1>n2 ? TRUEFALSE print that n2 is the min print that n1 is the min ifelse print a message get n1 get n2 is n1>n2 ? TRUEFALSE print min set min to be n1 ifelse set min to be n1

List applications LightPath, late 1999 "broker than before"

List applications LightPath, early 2000

broker than before… LightPath, 2006…

T. T. Securities The future of securities trading and analysis!

T. T. Securities Input stock prices for a number of days in a row, and then analyze that data…. Software Stock-price Analysis maximum price day of the max price minimum price day of the min price sum of all of them average of all of them standard deviation of all of them find the best T.T.S. strategy… mode (most common value - extra)

T. T. Securities Input stock prices for a number of days in a row, and then analyze that data…. Software Stock-price Analysis maximum price day of the max price minimum price day of the min price sum of all of them average of all of them standard deviation of all of them find the best T.T.S. strategy… mode (most common value - extra)

Given a list of stock prices L = [ 20, 21, 22, 100, 570, 35, 10, 3.5 ] maximum price day of the max price minimum price day of the min price sum of all of them average of all of them standard deviation of all of them find the best T.T.S. strategy… mode (most common value) Print them nicely… And print the following data: Day: 0 Price: 20 Day: 1 Price: 21 Day: 2 Price: 22 Day: 3 Price: 100 Day: 4 Price: 570 Day: 5 Price: 35 Day: 6 Price: 10 Day: 7 Price: 3.5

Accumulating a max… Remember the work of max/min? Suppose we have to find the max of a HUGE list … [ 20, 21, 22, 100, 570, 35, 10, 3.5 ]

Accumulating an answer… L = eval(input('Enter a list ')) maxSoFar = 0 for x in L: if x > maxSoFar: maxSoFar = x print ('max is', maxSoFar) Finding the max of a list: something's wrong! printing one's mind!

Accumulating an answer… L = eval(input('Enter a list ')) maxSoFar = L[0] for x in L[1:]: if x > maxSoFar: maxSoFar = x print ('max is', maxSoFar) Finding the max of a list: Indexing Slicing what day?

Accumulating an answer… [ 20, 21, 22, 100, 570, 35, 10, 3.5 ] L = eval(input('Enter a list ')) maxSoFar = L[0] for x in L[1:]: if x > maxSoFar: maxSoFar = x print ('max is', maxSoFar) accumulator variable how many times will this happen? Finding the maximum

Determine the max's day … L = eval(input('Enter a list ')) maxSoFar = L[0] for x in L[1:]: if x > maxSoFar: maxSoFar = x print ('max is', maxSoFar) print ('the day of the max is', ???? Finding the day of the max of a list:

Slow… Accumulation … [ 20, 21, 22, 100, 570, 35, 10, 3.5 ] Printing a list of days and prices Day: 0 Price: 20 Day: 1 Price: 21 Day: 2 Price: 22 Day: 3 Price: 100 Day: 4 Price: 570 Day: 5 Price: 35 Day: 6 Price: 10 Day: 7 Price: 3.5 desired output what's accumulating here?

Slow Accumulation … L = eval(input('Enter a list ')) day = 0 for x in L: print ('Day:', day, 'Price:', x) [ 20, 21, 22, 100, 570, 35, 10, 3.5 ] Printing a list of days and prices something's wrong here!

Slow Accumulation … L = eval(input('Enter a list ')) day = 0 for x in L: print ('Day:', day, 'Price:', x) day = day + 1 [ 20, 21, 22, 100, 570, 35, 10, 3.5 ] Printing a list of days and prices This reminds me of another 90's breakout album…

A good reason not to be a computer! Finding the standard deviation of a list … (L[i] - L av ) 2  len(L) URL (1) find the average, L av (2) find the sum of ( x-L av ) 2 for x in L (3) divide by the length of L (4) import math math.sqrt (…)

TTS ? Find the most profitable strategy for buying and selling the stock among the prices in the array... Day 0 Price is 90.0 Day 1 Price is 10.0 Day 2 Price is 60.0 Day 3 Price is 42.0 Day 4 Price is 75.0 Day 5 Price is 5.0 L = [ 90, 10, 60, 42, 75, 5] Buy on ANY day… Sell on ANY day… (but, to be realistic, we have to sell AFTER we buy!) This is the old 23rd- century model !

Do you remember? most crucial least crucial Use eval(input()) for processed values; input() for strings. Loops repeat an action: Loops can run by element or by index: An accumulator is a variable that may update each iteration. for x in L: sumSoFar = sumSoFar + x for i in range(0,len(L)): sumSoFar = sumSoFar + L[i] for each list element for each item index while a test is True use break to escape from a loop any time!

s = 'gattacaaggtaaaatgca' N = 0 for i in range(0,len(s)): if s[i] == 'a': N = N + 1 print ('N is', N) What do these loops print? What do they do? s = 'gattacaaggtaaaatgca' N = 0 for i in range(1,len(s)): if s[i] == 'a' and s[i-1] == 't': N = N + 1 print ('N is', N) s = 'gattacaaggtaaaatgca' MAX = 0 cur = 0 for i in range(0,len(s)): if s[i] == 'a': if s[i-1] != 'a': cur = 1 else: cur = cur + 1 if cur > MAX: MAX = cur print ('Max is', MAX) s = 'gattacaaggtaaaatgca' N = 0 for i in range(0,len(s)): if s[i] == 'a' or s[i] == 't': N = N + 1 print ('N is', N)

Loopy thinking s = 'gattacaaggtaaaatgca' How could we find the longest sequence of 'a' s ? How could we find the number of 'a' s ? How about 'a' s and 't' s? How could we find the number of 'ta' s ?

Loopy thinking s = 'gattacaaggtaaaatgca' How could we find the longest sequence of 'a' s ? How could we find the number of 'a' s ? How about 'a' s and 't' s? How could we find the number of 'ta' s ? s = 'gattacaaggtaaaatgca' N = 0 for i in range(0,len(s)): if s[i] == 'a': N = N + 1 print ('N is', N)

Loopy thinking s = 'gattacaaggtaaaatgca' How could we find the longest sequence of 'a' s ? How could we find the number of 'a' s ? How about 'a' s and 't' s? How could we find the number of 'ta' s ? s = 'gattacaaggtaaaatgca' N = 0 for i in range(0,len(s)): if s[i] == 'a' or s[i] == 't': N = N + 1 print ('N is', N)

Loopy thinking s = 'gattacaaggtaaaatgca' How could we find the longest sequence of 'a' s ? How could we find the number of 'a' s ? How about 'a' s and 't' s? How could we find the number of 'ta' s ? s = 'gattacaaggtaaaatgca' N = 0 for i in range(1,len(s)): if s[i] == 'a' and s[i-1] == 't': N = N + 1 print ('N is', N)

Loopy thinking s = 'gattacaaggtaaaatgca' How could we find the longest sequence of 'a' s ?

Planning in "pseudocode" s = 'gattacaaggtaaaatgca' Loop through the string: if we do see an 'a' if the PREVIOUS letter is NOT an 'a' if the PREVIOUS letter IS an 'a' Keep track of CurRun, MaxRun

Planning in "pseudocode" s = 'gattacaaggtaaaatgca' Loop through the string: if we do see an 'a' if the PREVIOUS letter is NOT an 'a' if the PREVIOUS letter IS an 'a' Keep track of CurRun, MaxRun Start a Run! CurRun = 1 Continue our run! CurRun = CurRun + 1 Check for a new maximum…

Planning in "pseudocode" s = 'gattacaaggtaaaatgca' MAX = 0 cur = 0 for i in range(0,len(s)): if s[i] == 'a': if s[i-1] != 'a': cur = 1 else: cur = cur + 1 if cur > MAX: MAX = cur print ('Max is', MAX) Loop through the string: if we do see an 'a' if the PREVIOUS letter is NOT an 'a' if the PREVIOUS letter IS an 'a' Keep track of CurRun, MaxRun Start a Run! Continue our run! Check for a new maximum…

Do you remember? All data is stored in memory as a list. most crucial least crucial Use eval(input()) for processed values; input() for strings. Loops repeat an action for each list element. An accumulator is a variable that may update each iteration. Lists can be indexed and sliced into pieces. Indexing starts at 0 (zero). L[0] is the first list item. - This alters the usual numeric notions of "first," "second," "third," etc.! Slicing includes the left side but excludes the right side.

Silicon Dreams How does a machine think ? Programming Language layers of abstraction Machine Instructions Movement of electrons Algorithms its great- great-… grand- child Shockley’s first transistor loadn r0 5 # p loadn r1 2 # pr/wk mul r0 r0 r1 # answer! p = 5*2 How many problems am I facing in five weeks with two per week ?

Silicon Dreams How does a machine think ? Programming Language layers of abstraction Machine Instructions Movement of electrons Python Algorithms its great- great-… grand- child Shockley’s first transistor our tasks computer’s tasks loadn r0 5 # p loadn r1 2 # pr/wk mul r0 r0 r1 # answer! p = 5*2 How many problems am I facing in five weeks with two per week ?

Silicon Dreams How does a machine think ? Programming Language layers of abstraction Machine Instructions Movement of electrons Python Algorithms its great- great-… grand- child Shockley’s first transistor our tasks computer’s tasks compile run program loadn r0 5 # p loadn r1 2 # pr/wk mul r0 r0 r1 # answer! p = 5*2 How many problems am I facing in five weeks with two per week ?

Fast Accumulation … L = input('Enter a list ') sumSoFar = 0 for x in L: sumSoFar = sumSoFar + x print ('sum is', sumSoFar) ave.? st. dev.? Finding the sum of a list [ 20, 21, 22, 100, 570, 35, 10, 3.5 ]