Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.

Slides:



Advertisements
Similar presentations
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Advertisements

CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Introduction to Computing Science and Programming I
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Introduction to Python
Strings Victor Norman CS104 Calvin College. Reading Quiz Counts toward your grade.
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Introduction to Python
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine.
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012.
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
CIT 590 Intro to Programming Lecture 4. Agenda Doubts from HW1 and HW2 Main function Break, quit, exit Function argument names, scope What is modularity!
By the end of this session you should be able to...
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
Intro Python: Variables, Indexing, Numbers, Strings.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
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)
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
CS 1 with Robots Variables, Data Types & Math Institute for Personal Robots in Education (IPRE)‏ Sec 9-7 Web Design.
Iteration Hussein Suleman UCT Dept of Computer Science CS115 ~ 2004.
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.
Lecture 13: Arrays, Pointers, Code examples B Burlingame 2 Dec 2015.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
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.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Lists Victor Norman CS104. Reading Quiz Lists Our second collection data type – elements are in order (like strings) – indexed from 0 to n – 1 (like.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
CS106 Mid-term Quiz Not counted in your grade.. Q1 Write code to create a variable message that refers to a string Hello world. Answer: message = “Hello.
Course A201: Introduction to Programming 09/09/2010.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
More about Iteration Victor Norman CS104. Reading Quiz.
String and Lists Dr. José M. Reyes Álamo.
Containers and Lists CIS 40 – Introduction to Programming in Python
Variables, Expressions, and IO
Lecture 07 More Repetition Richard Gesick.
Repeating code We could repeat code we need more than once: i = 1 print (i) i += 1 print (i) #… stop when i == 9 But each line means an extra line we might.
Lecture 4B More Repetition Richard Gesick
Topics Introduction to File Input and Output
An Introduction to Python
Teaching London Computing
CISC101 Reminders Assn 3 due tomorrow, 7pm.
T. Jumana Abu Shmais – AOU - Riyadh
ARRAYS 1 GCSE COMPUTER SCIENCE.
Coding Concepts (Basics)
String and Lists Dr. José M. Reyes Álamo.
CS2011 Introduction to Programming I Arrays (I)
Loops.
CHAPTER 4: Lists, Tuples and Dictionaries
Python Review
Topics Introduction to File Input and Output
CISC101 Reminders Assignment 3 due today.
While Loops in Python.
Presentation transcript:

Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015

Interactive vs. Source code modes Q: Is source code just what we are typing into pyCharm? A: Yes! When you create a file, and put python in it, you are creating source code. When you hit “Run” in pyCharm, you are actually launching the python interpreter and sending it the file you have been editing. This is “source code” or “non-interactive” or “program” mode. When you just launch python without sending it a file, you are in interactive mode: like a calculator, you can type stuff in, and the interpreter runs it, giving back results for each line.

Properties of Source Code vs. Interactive Modes Source Code Mode Python interpreter reads code in from a file, and runs it. Prints out results only when the code says to print something. Exits when the code is done running. Interactive Mode Python interpreter started without being given any code to run. Shows a prompt: >>> Prints out result after every line is entered by the user. Does not exit until you type exit() or Ctrl-D. Very good for checking something quickly. Nothing you type in is saved for later.

User vs. Programmer Just hinted at in the book A programmer needs to think about what the user sees when they run the code Is it obvious what is happening? Is the user getting the feedback they need/want? Can the user customize the output? Often, you are the programmer and the user…

Augmented assignment operators Q: Can you explain how to properly use the += sign? A: What if we could write this in python?: aVal = 7 change aVal by 1 What would that mean? Means add 1 to the value in aVal. aVal += 1 Equivalent to aVal = aVal + 1 Similarly for -= *= /=

How print works… When you call print x, y, z, w + 3, len(guests) these things happen: Each argument to the print statement is evaluated (converted into a value). Each value is converted to a str (if it isn’t a string already). Essentially str(arg) is called on each. Values are printed out with a space between each. A newline is outputted, unless the print ends with a comma.

Printing strings Q: What will the output look like?: print "Hi", "there" print "Hi" + "there" A: Hi there

How many values? Q: How many values are being passed to the print command?: print "Today’s date is", month, "/", day, "/" + str(year) + "." A: 5

Q3 Q: Write the output: print "I am the very model", print "of a modern major general" A: I am the very model of a modern major general

Practice printing Q: Write this output: for i in range(10): print i, ", ", print A: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, (and next output is on a new line)

What does this code do? What does this code output? for i in range(2, 5): print “jsv” + i Syntax error: cannot concatenate string and integer How to make it print 3 userIds correctly? for i in range(2, 5): print “jsv” + str(i)

Q5 Q: What is the problem here, and how do you fix it? i = 42 print "The answer is " + i A: Problem: cannot concatenate a string and int. print "The answer is " + str(i) or print "The answer is", i

For loop syntax Q: In the first example of for loops on page 126, where did the person identifier come from? (Assume guests refers to a list.) for person in guests: print person A: The pattern for for loops is: for in : If doesn’t exist already, python creates it, just like in an assignment.

Loop variable declaration/use Q: When the code reads: for person in guests: print person are we in fact assigning the variable name person to every item in guests (in this case a list)? A: Yes! The variable person is defined and then set to iterate through each element of guests. It is just like a variable declaration in an assignment.

Element-based vs. Index-based loop A loop is a loop – the loop variable iterates through the items. An element-based loop is just this: for elem in someList: # do something with each elem in someList. do stuff with elem An index-based loop is the same syntax, but a different idea: Each element in a list is at a certain index. Access the elements via the index. for idx in range(len(someList)): # sequence is indices now. do stuff with someList[idx]

When do you use which? Element-based is so easy to read and understand. Use when you just need each element, and Don’t care where the element is in the list. Index-based is more general. Use when you need to know where the element is in the list. Use when you need to iterate through multiple lists of the same length. Use when you need to access elements before or after the current idx. When you need to change contents of the list.

Welcome to the Cheese Shop! Q: Write code that iterates through a list cheeses and prints out i. for each item. A: for i in range(len(cheeses)): print str(i) + ". " + cheeses[i] (or...)

Which to use? Q: Suppose you are given 2 lists: guys and girls. guys = [“Georg”, “Homer”, “Ichabod” ] girls = [“Gertrudella”, “Helga”, “Ingmar”] Write code to print out all pairs, like Georg, Gertrudella Homer, Helga Ichabod, Ingmar A: for i in range(len(guys)): print guys[i] + ", " + girls[i]

Using multiple consecutive items Write code that repeatedly prints out two consecutive items from list aList. E.g., if aList = [ “hi”, 1, True ] it will print out hi1, 1True (each on its own line). for i in range(len(aList) - 1): # generate indices 0, 1, …, n – 2. # convert each item in aList to string before concatenating. print str(aList[i]) + str(aList[i+1])

Why doesn’t this work? We want to make every string in a list all lower case: # guests is a list of strings for person in guests: person = person.lower() But, it doesn’t work. Why not? A: Because strings are immutable! So, person.lower() returns a new string, all lower-case. And, person refers to it, but the “slot” in the list does not change. How to fix this?

Weird loop? Q: What is different about this for loop: for num in range(1000): val = random.randint(3) do_something(val) A: the loop variable num isn't used. This construct is how we do a loop a certain number of times.

What does this do? Q: What does this code do, assuming charges is a list of floating point numbers?: total = 0.0 for charge in charges: total += charge print total A: prints the sum of all the values in charges.

Challenge Q: Suppose you are given 2 lists: guys and girls. Write code to print out all possible pairs, like Georg, Gertrudella Georg, Helga... A: for guy in guys: for girl in girls: print guy + ", " + girl

Real challenge! Q: Write code to take a line of words and produce a string reversed_words that has the same words, each having been reversed. (Note: use a slice to reverse the word.) A: rev_words = [] for word in line.split(): rev_words.append(word[::-1]) reverse_words = " ".join(rev_words)

More practice Given a string referred to by variable data, write code to print out its 1 st letter, then 1 st and 2 nd letter, then first 3 letters, etc. Example: data = “CS106” Output: C CS CS1 CS10 CS106

More practice Now, write code to print it out this way: Output: C CS CS1 CS10 CS106

Practice Write code to interleave two lists. E.g., muscles = [“bicep”, “tricep”, “quad”] bones = [“elbow”, “head”, “nose”] Interleave into list mandb : [“bicep”, “elbow”, “tricep”, “head”, “quad”, “nose”] You may assume the lists are the same length.

Lists of floats… Write code that creates a list of floats [0.0, 0.1, 0.2, 0.3, 0.4, …, 9.8, 9.9] Write code that starts with a list of integers iList and produces a list of floats fList where each float in fList is a float that is one-tenth of the corresponding value in iList. E.g., given iList = [3, 5, 7, -33], fList would be [0.3, 0.5, 0.7, -3.3]

A really good challenge! Q: Write the loop to print out the nth Fibonacci term, assuming n >= 3. A: prev_term = prev_prev_term = 1 for i in range(3, n+1): term = prev_term + prev_prev_term prev_prev_term = prev_term prev_term = term print "nth fib is ", term