COP3035 Exam

Ace your homework & exams now with Quizwiz!

Python Interactive Mode

$ python >>> print "Hello, World!" Hello, World! >>> hellostring = "Hello, World!" >>> hellostring 'Hello, World!' >>> 2*5 10

How do you remove white space in a string?

''.join(str.split())

Disadvantage of a Set

...

How do you make: 1. Single-line Comment 2. Multi-line Comment

1. # 2. """ .... """

Scipy

A collection of mathematical algorithms and convenience functions built on the Numpy extension of Python. It adds significant power to the interactive Python session by providing the user with high-level commands and classes for manipulating and visualizing data. With SciPy an interactive Python session becomes a data-processing and system-prototyping environment rivaling systems such as MATLAB, IDL, Octave, R-Lab, and SciLab.

Module

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module's name (as a string) is available as the value of the global variable __name__. Example: ''' Module fib.py ''' from __future__ import print_function #Note that we can only access the definitions of fib as members of the fib object.

What is an object?

An object has both a state and behavior. The state defines the object, and the behavior defines what the object does.

Pyplot

At the center of most matplotlib scripts is pyplot. The pyplot module is stateful and tracks changes to a figure. All pyplot functions revolve around creating or manipulating the state of a figure. The plot function can actually take any number of arguments. Common usage of plot: plt.plot(x_values, y_values, format_string [, x, y, format, ])

What is the role of handling exceptions?

Explicitly handling exceptions allows us to control otherwise undefined behavior in our program, as well as alert users to errors. Use try/except blocks to catch and recover from exceptions.

re.match

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match. Note that even in MULTILINE mode, re.match() will only match at the beginning of the string and not at the beginning of each line. re.match(pattern, string)

What kind of package is Numpy, Scipy, and Plotting?

NumPy/SciPy - numerical and scientific function libraries. Plotting - Matplotlib for complex scientific applications

Basic Data Types are comprised of:

Numeric & Sequence Data Types

f.read()

Returns the entire contents of a file as a string. Provide an argument to limit the number of characters you pick up.

re.search()

Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. re.search(pattern, string) re.search("c", "abcdef") # Match

Set

Set: An unordered collection of unique objects Frozenset: An immutable version of set Example: >>> a = set('abracadabra') >>> b = set('alacazam') >>> a set(['a', 'r', 'b', 'c', 'd']) >>> a - b set(['r', 'd', 'b']) >>> a | b set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])

Define a turtle named Tess and its pensize

Tess = turtle.Turtle() Tess.pensize(5)

Numpy

The key to NumPy is the ndarray object, an n-dimensional array of homogeneous data types, with many operations being performed in compiled code for performance. There are several important differences between NumPy arrays and the standard Python sequences: NumPy arrays have a fixed size. Modifying the size means creating a new array. NumPy arrays must be of the same data type, but this can include Python objects. More efficient mathematical operations than built-in sequence types.

T / F are strings immutable?

True We cannot change them! Changing a string through re-assignment means creating a new string object and reassigning the name.!

Matplotlib

We're going to continue our discussion of scientific computing with matplotlib. Matplotlib is an incredibly powerful (and beautiful!) 2-D plotting library. It's easy to use and provides a huge number of examples for tackling unique problems.

What is the purpose of constructor__init__

__init__ method an take any number of arguments in __init__, self refers to the object currently being created; so, in other class methods, it refers to the instance whose method was called

if statement (include elif)

a = 1 b = 0 c = 2 if a > b: if a > c: print "a is greatest" else: print "c is greatest" elif b > c: print "b is greatest" else: print "c is greatest"

3. Suppose listExample is ['h','e','l','l','o'], what is len(listExample)? a) 5 b) 4 c) None d) Error

a) 5

18. If a module is executed directly, the value of the global variable __name__ will be "__main__"? a) True b) False

a) True

Is a list mutable in python? a) True b) False

a) True

2. What is the result when we execute list("hello")? a) ['h', 'e', 'l', 'l', 'o']. b) ['hello']. c) ['llo']. d) ['olleh'].

a) ['h', 'e', 'l', 'l', 'o'].

6. Suppose list1 is [2, 33, 222, 14, 25], What is list1[:-1] ? a) [2, 33, 222, 14]. b) Error c) 25 d) [25, 14, 222, 33, 2].

a) [2, 33, 222, 14].

15. If d is a valid dictionary, then circle the valid operations? a) d.keys() b) d.values() c) d.items() d) d.reverse()

a) d.keys() b) d.values() c) d.items()

7. Which of the following is a Python tuple? a) [1, 2, 3] b) (1, 2, 3) c) {1, 2, 3} d) {}

b) (1, 2, 3)

13. What would be the output of int(6.3)? a) 5 b) 6 c) 7 d) 8

b) 6

17. Both mutable and immutable objects can be changed in the called function in python? a) True b) False

b) False

24. What is the output of the following code? class Demo: def __init__(self): pass def test(self): print(__name__) obj = Demo() obj.test() a) Exception is thrown b) __main__ c) Demo d) test

b) __main__

20. The readlines() method returns a) str b) a list of lines c) a list of single characters d) a list of integers

b) a list of lines

12. If a={5,6,7}, what happens when a.add(5) is executed? a) a={5,5,6,7} b) a={5,6,7} c) Error as there is no add function for set data type d) Error as 5 already exists in the set

b) a={5,6,7}

18. To open a file c:\scores.txt for reading, we use a) infile = open("c:\scores.txt", "r") b) infile = open("c:\\scores.txt", "r") c) infile = open(file = "c:\scores.txt", "r") d) infile = open(file = "c:\\scores.txt", "r")

b) infile = open("c:\\scores.txt", "r")

15. Suppose d = {"john":40, "peter":45}. To obtain the number of entries in dictionary which command do we use? a) d.size() b) len(d) c) size(d) d) d.len()

b) len(d)

8. Suppose t = (1, 2, 4, 3), which of the following is incorrect? a) print(t[3]) b) t[3] = 45 c) print(max(t)) d) print(len(t))

b) t[3] = 45

25. What happens when '1' == 1 is executed? a) we get a True b) we get a False c) a TypeError occurs d) a ValueError occurs

b) we get a False

24. Which one of these is a Fibonacci series? a. 1,2,5,6,7,8 b. 1,2,3,5,8,11 c. 1,2,3,4,5,6 d. None of the above

b. 1,2,3,5,8,11

21. What will the following produce? >>> 1.1 * 3.0 == 3.3 a. True b. False

b. False (HINT: 3.3000000000000003)

22. Which one of these provide a set of recommendations about how to write readable Python programs? a. PPP b. PEP 8 c. Jython d. None of the above

b. PEP 8

What would be the printed outputs for the following program? for i in range(20,14,-2): print i a) 18,19,20 b) 20,19,18,17 c) 20,18,16 d) 20,18,16,14

c) 20,18,16

5. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1]? a) Error b) None c) 25 d) 2

c) 25

10. What is the output for the following code? nums = set([1,1,2,3,3,4,4]) print(len(nums)) a) 7 b) Error, invalid syntax for formation of set c) 4 d) 8

c) 4

16. Suppose d = {"john":40, "peter":45}, what happens when we try to retrieve a value using the expression d["susan"]? a) Since "susan" is not a value in the set, Python raises a KeyError exception b) It is executed fine and no exception is raised, and it returns None c) Since "susan" is not a key in the set, Python raises a KeyError exception d) Since "susan" is not a key in the set, Python raises a syntax error

c) Since "susan" is not a key in the set, Python raises a KeyError exception

4. Which one of the following numeric data types does not support typical numeric operations? a) int b) float c) complex d) long

c) complex

14. Suppose d = {"john":40, "peter":45}, to delete the entry for "john" what command do we use a) d.delete("john":40) b) d.delete("john") c) del d["john"]. d) del d("john":40)

c) del d["john"].

19. To read the next line of the file from a file object infile, we use a) infile.read(2) b) infile.read() c) infile.readline() d) infile.readlines()

c) infile.readline()

9. Which of the following turtle methods leaves an impression of the turtle methods? a) left b) right c) stamp d) shape

c) stamp

22. When will the else part of try-except-else be executed? a) always b) when an exception occurs c) when no exception occurs d) when an exception occurs in to except block

c) when no exception occurs

Creating an instance for the class

class Circle Data Fields: radius is ____ Methods: getArea Circle Object 1 Data Fields: radius is 10 Circle Object 2 Data Fields: radius is 25

Define a class

class car 4 wheels... subclass volvo other attributes? Class - Special data type which defines how to build a certain kind of object - Data items are shared by all instances Instances - Objects that are created which follow the definition given inside of a class

13. Which of the following statements create a dictionary? a) d = {} b) d = {"john":40, "peter":45} c) d = {40:"john", 45:"peter"} d) All of the mentioned

d) All of the mentioned

17. Which of the following statements are true? a) When you open a file for reading, if the file does not exist, an error occurs b) When you open a file for writing, if the file does not exist, a new file is created c) When you open a file for writing, if the file exists, the existing file is overwritten with the new file d) All of the mentioned

d) All of the mentioned

21. What is Instantiation in terms of OOP terminology? a) Deleting an instance of class b) Modifying an instance of class c) Copying an instance of class d) Creating an instance of class

d) Creating an instance of class

9. Which of these about a set is not true? a) Mutable data type b) Allows duplicate values c) Data type with unordered values d) Immutable data type

d) Immutable data type

11. If a={5,6,7,8}, which of the following statements is false? a) print(len(a)) b) print(min(a)) c) a.remove(5) d) a[2]=45

d) a[2]=45

1. Which of the following commands will create a list? a) list1 = list() b) list1 = [ ] c) list1 = list([1, 2, 3]) d) all of the mentioned

d) all of the mentioned

4. Suppose list1 is [4, 2, 2, 4, 5, 2, 1, 0], Which of the following is correct syntax for slicing operation? a) print(list1[0]) b) print(list1[:2]) c) print(list1[:-2]) d) all of the mentioned

d) all of the mentioned

23. When is the "finally" block executed? a) when there is no exception b) when there is an exception c) only if some condition that has been specified is satisfied d) always

d) always

How do you define a function?

def somefunction (): .......... .......... ..........

What are the different ways you can open a file and what are the differences?

f = open("somefile.txt, 'r') - Opens a file for read only f = open("somefile.txt, 'w') - Opens a file for writing only f = open("somefile.txt, 'a') - Opens a file for appending f = open("somefile.txt, 'rb') - Opens a file for read only in binary format

How do you close a file?

f.close()

Loop over the file object

for line in f: print(line)

Example of providing control flows

for num in range(10,20): if num%2 == 0: continue for i in range(3,num): if num%i == 0: break else: print num, 'is a prime number'

for loop

for var in sequence: statements

How do you import a module

from __name__ import some_function

How do you import scipy?

from scipy import special

How do you import Matplotlib?

import matplotlib.pyplot as plt

How do you import numpy?

import numpy as np

How do you import a file

import somefile - everything from somefile gets imported from somefile import * - everything from somefile gets imported from somefile import className className.method("abc")# imported myFunction(34)# Not imported

How do you use the regular expression?

import sys import re pattern = "Fred" regexp = re.compile(pattern) # prepares the regular expression for line in sys.stdin: (compare line in regEx) if RegEx matches: sys.stdout.write(line)

Numeric Data Types

int, long, float, complex

Python Normal Mode

print "Hello, World!"

How are format strings constructed?

print("Sammy the {} has a pet {}!".format(Variable1, Variable2))

Formatting with the format method

print("Your total Correct is: {} ".format(Correct)) print("Your total Incorrect is: {} ".format(Incorrect))

re.compile

re.compile(pattern) Compile a regular expression pattern into a regular expression object, which can be used for matching using its match() and search() methods, described below. The expression's behavior can be modified by specifying a flags value. Values can be any of the following variables, combined using bitwise OR (the | operator). prog = re.compile(pattern) result = prog.match(string)

What are the built-in string methods?

s.upper() - Returns in all CAPS s.lower - Returns in all lower s.split() - Lets you separate a string by providing what separates them s.isalpha() - Returns T/F if its all letters s.isdigit() - Returns T/F if its a digit s.isalum() - Returns T/F if it is alphanumeric string s.isspace() - Returns T/F if there's white space

How do you change 1 letter in a string?

text = 'abcdefg' new = list(text) new[6] = 'W' ''.join(new)

What are the different time modules and what do they do?

time.time() - returns the time in seconds since the epoch (typically 1/1/1970), simply measures elapsed wall clock time. time.sleep(s) - suspends execution for s seconds. time.clock() - returns the current processor time in seconds. Only measures time during which the CPU is actively working on behalf of the program

Create a window in turtle programming

wn = turtle.Screen()

What is the sys module and how do you use it?

The sys module provides access to some variables used or maintained by the interpreter as well as some methods for interacting with the interpreter. It allows you to receive information about the runtime environment as well as make modifications to it. To use the sys module, just execute the import sys statement.

sys.argv

- Internal system variable - Used to obtain command line arguments - Processes inputs The first element of the sys.argv list is always the module name, followed by the whitespace-separated arguments. import sys for i in range(len(sys.argv)): print "sys.argv[" + str(i) + "] is " + sys.argv[i] sys.argv[0] is testargs.py sys.argv[1] is here

Disadvantages of Dictionaries

(i) Dictionaries are unordered. In cases where the order of the data is important. (ii) Take up a lot more space than other data structures. The amount of space occupied increases drastically when there are many Python Dictionary keys.

Disadvantages of using a Tuple

* You can't add an element but in a list you can * You can't sort a tuple but in a list you can * You can't delete an element but you can in a list * You can't replace an element but you can in a list

What is __name__ ?

Within a module, the module's name (as a string) is available as the value of the global variable __name__. If a module is executed directly however, the value of the global variable __name__ will be "__main__".

What are the four statements provided for manipulating loop structures and their definition?

break: terminates the current loop. continue: immediately begin the next iteration of the loop. pass: do nothing. Use when a statement is required syntactically. else: represents a set of statements that should execute when a loop terminates.

When should you use a List?

When you need: A collection of elements of varying type. The ability to order your elements. The ability to modify or add to the collection. When you don't require elements to be indexed by a custom value. When you need a stack or a queue. Your elements are not necessarily unique.

Significance of whitespace

Whitespace is significant in Python. Where other languages may use {} or (), Python uses indentation to denote code blocks.

sys private versions

...

6. Which of the following is immutable? a) string b) list c) dictionary d) set

A) string

How do you create, access, and modify a Tuple?

Create: t1 = (1, 2, 3, 4) t2 = "a", "b", "c", "d" t3 = () t4 = ("red", ) Access: TupleName[index] s = "Susan", 19, "CS" # tuple packing >>> name, age, major = s # tuple unpacking Modify: Tuples are immutable

5. Circle the sequence data types in python? a) string b) list c) tuple d) dictionary

5. Circle the sequence data types in python? a) string b) list c) tuple

Subclasses

A class can extend the definition of another class - Allows use (or extension ) of methods and attributes already defined in the previous one. - New class: subclass. Original: parent, ancestor or superclass To define a subclass, put the name of the superclass in parentheses after the subclass's name on the first line of the definition. Class Cs_student(student): - Python has no 'extends' keyword like Java. - Multiple inheritance is supported. Example: class car 4 wheels... subclass volvo other attributes?

What is a Regular Expression?

A sequence of characters that forms a search pattern. RegEx can be used to check if a string contains the specified search pattern. - "digits1234" - [a-z][0-9] - Pattern says any letter a-z and number 0-9 - If it contains any of the following you'll have a match - Compile -> search -> lets you know if there's a match

How is a program executed?

By an interpreter: The interpreter translates Python code into bytecode, and this bytecode is executed by the Python VM (similar to Java).

Methods

Classes have associated methods, which are just a special kind of function. Consider the expression alex.forward(50) The interpreter first looks up alex and finds that it is an instance of the class Turtle. Then it looks up the attribute forward and finds that it is a method. Since there is a left parenthesis directly following, the interpreter invokes the method, passing 50 as a parameter.The only difference between a method invocation and other function calls is that the object instance itself is also passed as a parameter. Thus alex.forward(50) moves alex, while tess.forward(50) moves tess.

How do you create, access, and modify a Dictionary?

Create: d1 = {} d2 = dict() # both empty d3 = {"Name": "Susan", "Age": 19, "Major": "CS"} d4 = dict(Name="Susan", Age=19, Major="CS") d5 = dict(zip(['Name', 'Age', 'Major'], ["Susan", 19, "CS"])) d6 = dict([('Age', 19), ('Name', "Susan"), ('Major', "CS")]) Access: DictionaryName[KeyValue] DictName.has_key(KeyValue) - Returns T / F DictName.keys() - Returns a list of keys DictName.items() - Returns list of key:value pairs DictName.values() - Returns a list of values Modify: Dictname[KeyValue] = Value del Dictname[KeyValue] Dictname.clear()

How do you create, access, and modify a List?

Create: mylist1 = [] mylist2 = [expression1, expression2, ...] mylist3 = [expression for variable in sequence] mylist1 = list() mylist2 = list(sequence) mylist3 = list(expression for variable in sequence) Access: mylist[index] mylist.index(Value that your looking for the index) Modify: mylist.insert(values) mylist.append(value) - Add element to existing list mylist.extend(value) - Add all of the items from another list mylist.reverse() mylist.sort()

How do you create, access, and modify a Set?

Create: myset = set(sequence) myset2 = {expression for variable in sequence} Access: s1 = set('abracadabra') s2 = set('bard') s1 >= s2 - Returns True s1 > s2 - Returns True s1 <= s2 - Returns False Union: set | other | ... - Return a new set with elements from the set and all others. Intersection: set & other & ... - Return a new set with elements common to the set and all others. Difference: set - other - ... - Return a new set with elements in the set that are not in the others. Symmetric Difference: set ^ other - Return a new set with elements in either the set or other but not both. Modify: s.copy() - returns a shallow copy of the set s. s.isdisjoint(other) - returns True if set s has no elements in common with set other. s.issubset(other) - returns True if set s is a subset of set other. len, in, and not in are also supported.

Disadvantages of a List

Data is mutable, so you shouldn't use it if you want things stored permanently

Dict

Dict: Hash tables, maps a set of keys to arbitrary objects Creating a Word Dictionary: Student = { "First Name: "John", "Last Name": "Doe", "Age": 20 }

Lists as Queues

Lists can be used as queues natively since insert() and pop() both support indexing. However, while appending and popping from a list are fast, inserting and popping from the beginning of the list are slow. Use the special deque object from the collections module. from collections import deque queue = deque([35, 19, 67]) queue.append(42) queue.append(23) queue.popleft() #Returns 35 queue.popleft() #Returns 19 queue #Returns deque([67, 42, 23])

String Object Representation

Name is bound to an object at some point, but this may change. The name is not synonymous with a specific address is memory.!

f.readline()

One by one, returns each line of a file as a string (ends with a newline). End-of-file reached when return string is empty.

Class Attributes

Owned by the class as a whole All class instances share the same value for it Called "static" variables in some languages Good for (1) class-wide constants and (2) building counter of how many instances of the class have been made Because all instances of a class share one copy of a class attribute, when any instance changes it, the value is changed for all instances Class attributes are defined within a class definition and outside of any method Since there is one of these attributes per class and not one per instance, they're accessed via a different notation: Access class attributes using self.__class__.name notation -- This is just one way to do this & the safest in general.

Python Typing

Python is a strongly, dynamically typed language. Strong typing: Explicit conversions are required in order to mix types. Example: 2 + "four" not going to fly Dynamic Typing: All type checking is done at runtime. No need to declare a variable or give it a type before use.

using the open() method

The first argument is the filename, the second is the mode. f = open("filename.txt", 'rb')

Self

The first argument of every method is a reference to the current instance of the class By convention, we name this argument self Although you must specify self explicitly when defining the method, you don't include it when calling the method. Python passes it for you automatically Defining a method: def set_age(self, num): self.age = num Calling a method: x.set_age(23)

sys.path

The sys.path variable specifies the locations where Python will look for imported modules. The sys.path variable is also a list and may be freely manipulated by the running program. The first element is always the "current" directory where the top-level module resides. import sys print "path has", len(sys.path), "members" sys.path.insert(0, "./samples") import sample sys.path = [] import math

sys.stdin , sys.stdout , sys.stderr

The sys.stdin, sys.stdout, and sys.stderr attributes hold the file objects corresponding to standard input, standard output, and standard error, respectively. Just like every other attribute in the sys module, these may also be changed at any time! f = open("somefile.txt", "w") sys.stdout = f print "This is going to be written to the file!" sys.stdout = sys.__stdout__ If you want to restore the standard file objects to their original values, use the sys.__stdin__, sys.__stdout__, and sys.__stderr__ attributes.

Built-in constants

There are a few built-in constants defined by the standard library: True: true value of a bool type. False: false value of a bool type.

Data Attributes

Variable owned by a particular instance of a class Each instance has its own value for it These are the most common kind of attribute Data attributes are created and initialized by an __init__() method. Simply assigning to a name creates the attribute Inside the class, refer to data attributes using self for example, self.full_name

When should you use a Tuple?

When storing elements that will not need to be changed. When performance is a concern. When you want to store your data in logical immutable pairs, triples, etc.

When should you use a set?

When the elements must be unique. When you need to be able to modify or add to the collection. When you need support for mathematical set operations. When you don't need to store nested lists, sets, or dictionaries as elements.

When should you use Dictionaries?

When you need to create associations in the form of key:value pairs. When you need fast lookup for your data, based on a custom key. When you need to modify or add to your key:value pairs.

Using Lists as Stacks

You can use lists as a quick stack data structure. The append() and pop() methods implement a LIFO structure. The pop(index) method will remove and return the item at the specified index. If no index is specified, the last item is popped from the list. stack.append(value) - Adds value to end stack.pop() - Removes last value

7. In turtle programming, turning 30 to the left will leave you facing in the same direction as turning 330 to the right? a) True b) False

a) True

20. Given: for i in range(1, 10): print(i) Which one of the following is the correct implementation using "while" loop for the above? Please circle. a) i = 1 while (i < 10) print(i) i = i + 1 b) i = 1 while (i <= 10) print(i) i = i + 1

a) i = 1 while (i < 10) print(i) i = i + 1

2. Circle the numeric data types in python? a) int b) float c) string d) list

a) int b) float

14. Circle the functions that are used for creating a range of integers? a) range() b) xrange() c) prange() d) mrange()

a) range() b) xrange()

23. What are the modes in which we can run python code? Circle all that apply. a. Normal mode b. Interpreted mode c. Infinite mode d. All of the above

a. Normal mode b. Interpreted mode

19. Arguments with default values can appear at the start of the arguments list of a function? a) True b) False

b) False

11. Multi-line comments begin and end with three #s in python? a) True b) False

b) False (HINT: Use """ comments """).

10. In python 3, the statement - print "Hello, World!" - will run without any error? a) True b) False

b) False (HINT: Use print ("Hello, World!"))

12. Circle the true statements for python? a) Python supports strong typing b) Python supports dynamic typing c) 2+"six" will not give any error

b) Python supports dynamic typing

3. What does alex.forward(-100) mean in Turtle Programming when you want the turtle "Alex" to be moved? a) alex moves forward by 100 units b) alex moves backward by 100 units c) alex turn left by 100 degree d) alex turn right by 100 degree

b) alex moves backward by 100 units

8. Which of the following will make alex to go at slowest speed? a) alex.speed(0) b) alex.speed(1) c) alex.speed(10)

b) alexa.speed(1)

Explain function implementation with an example

def sumProd(x,y): answer = x + y print answer x = input("enter the first number: ") y = input("enter the second number: ") sumProd(x,y)

What are each of the statements used when handling exceptions?

except: Catch all (or all other) exception types except name: Catch a specific exception only except name as value: Catch the listed exception and its instance except (name1, name2): Catch any of the listed exceptions except (name1, name2) as value: Catch any of the listed exceptions and its instance else: Run if no exception is raised finally: Always perform this block

Create an example of a turtle program

import turtle #turtle librarywn = turtle.Screen() #wn is an instance. Screen is a class for graphic window.alex = turtle.Turtle() #alex is the turtle's name. An instance of the class.alex.forward(150)alex.left(90)alex.forward(75)alex.salary = 50000 #alex has an attribute salary whose value is 50000.print(alex.salary)turtle.done()

Slicing

mylist[start:end] # items start to end-1 mylist[start:] # items start to end of the array mylist[:end] # items from beginning to end-1 mylist[:] # a copy of the whole array mylist[start:end:step] # start to end-1, by step mylist[-1] # last item in the array mylist[-2:] # last two items in the array mylist[:-2] # everything except the last two items

Difference between input() and raw_input()

raw_input() Asks the user for a string of input, and returns the string. If you provide an argument, it will be used as a prompt. input() Uses raw_input() to grab a string of data, but then tries to evaluate the string as if it were a Python expression. Returns the value of the expression. Dangerous - don't use it.

Creating a string

s1 = 'This is a string!' s2 = "Python is so awesome."

Sequence Data Types

strings, list, tuple

Trimming a string

txt = "some string" txt = txt[0:4] print txt #Output = some

How do you handle exceptions?

while True: try: x = int(raw_input("Enter a number: ")) except ValueError: print("Ooops !! That was not a valid number. Try again.") except (TypeError, IOError) as e: print(e) else: print("No errors encountered!") finally: print("We may or may not have encountered errors...")


Related study sets

Nur 211 Module 7 - Management of Patients with Oral and Esophageal Disorders Pt 2

View Set

Unit 3: Global Security: Old Issues, New Realities

View Set

Verbs - expressing physical, mental action or a state of being

View Set

Ch. 8 - Product Architecture and Product Design

View Set

GEB Chapter 13, Chapter 9 ,10,11,12

View Set

Higher Electricity- Operational Amplifiers

View Set

Unit 8.10 Investment Co Act of 1940

View Set

LearningCurve: 14d. Schizophrenia

View Set

Chapter 57: Drugs Affecting Gastrointestinal Secretions

View Set

Complete First - Unit 14 Reading and Use of English pt. 6 pgs. 154-155

View Set