Lecture Notes for CPSC 121 (Fall 2012) - Myro Functions, Lists, and For Loops, Study notes of Computer Science

The lecture notes for cpsc 121 (computer science principles) class held in fall 2012. The notes cover myro functions, basic list operations, list functions, and the use of for loops. The document also includes exercises for practicing these concepts.

Typology: Study notes

2012/2013

Uploaded on 09/28/2013

noob
noob 🇮🇳

4.4

(25)

105 documents

1 / 8

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Lecture Notes CPSC 121 (Fall 2012)
Today ...
Myro functions
More lists
For loops (intro)
Reading
Ch 4
HW
HW 6 out
Proj 1 out
S. Bowers 1 of 8
pf3
pf4
pf5
pf8

Partial preview of the text

Download Lecture Notes for CPSC 121 (Fall 2012) - Myro Functions, Lists, and For Loops and more Study notes Computer Science in PDF only on Docsity!

Today ...

  • Myro functions
  • More lists
  • For loops (intro)

Reading

  • Ch 4

HW

  • HW 6 out
  • Proj 1 out

Some basic Myro functions

  • beep(d, f) ... beeps duration d with frequency f
  • getName() ... name of your robot
  • getInfo() ... get information about robot
  • setName(s) .. set robot name to str s
  • forward(a, s) ... move forward speed a, seconds s
  • backward(a, s) ... move backward speed a, seconds s
  • turnLeft(a, s) ... turn left speed a, seconds s
  • turnRight(a, s) ... turn right speed a, seconds s There are lots more functions
  • e.g., for interacting with sensors
  • we’ll look at more as we go

List Functions

The len function returns the length of a list

len([10, 20, 30]) 3 empty = [] len(empty) 0 The append function adds an element to the end of a list empty.append(10) print(empty) [10] empty.append(20) print(empty) [10, 20]

The remove function removes the first matching value in a list

empty.remove(10) print(empty) [20]

The del keyword deletes an element at a given index (subscript)

del empty[0] print(empty) []

The reverse function reverses a list

the list = ["spam", "ham", "eggs"] the list.reverse() print(the list) ["eggs", "ham", "spam"]

More on indexing

my_list = [6, 7, 9] Q: What is the length of the list? Q: What function do we call to get the length ... len() list_length = len(my_list) print(list_length) 3

Q: What is the index of the first list element?

my_list = [6, 7, 9] elem = my_list[0] print(elem) 6

  • list elements are indexed from 0 to length - 1

Q: What happens if we give an index outside of 0 to length - 1?

elem = my_list[3] IndexError: list index out of range elem = my_list[-1] # a special case! print(elem) 9 elem = my_list[-4] IndexError: list index out of range

The for statement

Iteration (looping) allows us to repeat blocks of code For example, instead of writing: the list = ["spam", "ham", "eggs"] print(the list[0]) print(the list[1]) print(the list[2])

We can use a for statement: for v in the list: print(v)

  • Note we don’t need to know the length of the list here!