CS1110 PRELIM1

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

def middle(text)

Returns middle 3rd of text but string must have length divisible by 3

s1.count(s2)

Returns number of times s2 appears inside of s1

s1.index(s2)

Returns position of first instance of s2 in s1

def second(thelist)

Returns second word in list of words separated by commas second('A, B, C' 'B'

def firstparens(text)

Returns substring in () using the first set of parents >>> s = 'One (Two) Three' >>> firstparens(s) 'Two'

'x' in s

0

9 % 3

0

target = 'HeLLo:WorLd!' 'target'.index('target')

0

3//2

1

s.find('e')

1

'e' in s

1 (returns index of 'e' in string)

s.strip()

Returns a copy of s with white-space removed at ends

s1.upper()

Returns an upper case version

change_hrs("9:04", 5)

"14:04"

change_hrs("9:04", 29)

"14:04" because 29=24+5

change_hrs("9:04",-10)

"23:04"

change_hrs("9:04",-5)

"4:04"

What does this expression evaluate to? >>> t = 'Hello all' >>> t[3:6]

"lo "

Explain the different components of a module text file

# my_module.py """This is a simple module. It shows how modules work""" x = 1+2 Single line comment starts with # and is NOT executed Docstring is a multi-line comment useful for code documentation (note triple quotes) Commands are executed on import

change_hrs('23:14', 1)

'0:14'

change_hrs('11:14', 24+2)

'13:14'

change_hrs('9:04', -36)

'21:04'

change_hrs('0:00', -25)

'23:00'

change_hrs('9:04', -1)

'8:04'

'A double quote: "'

'A double quote: "'

s[0:len(s)]

'HeLLo World!'

s[0:11]

'HeLLo World'

target = 'HeLLo:WorLd!' target[:5]

'HeLLo'

target = 'HeLLo:WorLd!' target[:7]

'HeLLo:W'

>>> t = 'Hello all' >>> t[:3]

'Hel'

'Output: ' + str(6 / 2)

'Output: 3.0'

'Output: ' + '6 / 2'

'Output: 6 / 2'

' a b '.strip()

'a b'

target = 'HeLLo:WorLd!' target[1]

'e'

target = 'HeLLo:WorLd!' target[1:7]

'eLLo:W'

What about this? >>> s = 'heygorl' >>> s[1:len(s)-1]

'eygor'

'now ' + 'here now' + 'here'

'now here nowhere'

s[4:]

'o World!'

What is narrowing converstion?

- Going from a more expressive type to a less expressive type, which results in a loss of information (NO ROUNDING, just cuts off) - Python NEVER does this automatically

What is widening conversion?

- Going from a narrower type to wider type (e.g. int to float) - Python does automatically if needed

Operator s1 in s2

- Tests if s1 "a part of' s2 - Evaluates to a bool Examples >>> s = 'hey bestie' >>> 'e' in s True >>> 'boo' in s False

Built-in function len(s)

- Value is # of characters in s - Evaluates to an int Examples >>> s = 'heygorl' >>> len(s) 7

random

- generate random numbers - can pick any distribution

s.find('x')

-1

3.0/2.0

1.0

3/2

1.5

len(s)

12 (returns number of characters that string is)

2**4**0

2

8 % 3

2

s.count('o')

2

s.index('L')

2

What does this evaluate to? >>> s = 'heygorl' >>> len(s[1:5])

4

target = 'HeLLo:WorLd!' target.index(':')

5

s.index('L', 5)

9

What functions can you access by using the import command?

<module name>.<function name>(<arguments>) >>> import math >>> p=math.sqrt(9.0) >>> p 3.0

How do you access modules that have variables?

<module name>.<variable> >>> import math >>> math.pi 3.1415...

Method calls

<string name>.<method name>(x,y..>)

How do you see what functions and variables are available after importing a module?

>>> help(<module name>)

Function middle

>>> middle('aaabbbccc') 'bbb'

How do you test a type with a boolean expression?

>>>type(2) == int True

How do you test the type of a variable?

>>>x=5 >>>type(x) <class 'int'>

What is a call frame?

A call frame is a representation of function call

What is the difference between a function definition and a function call?

A function definition defines what the function does and declares the parameters. Meanwhile, a function call is the command that actually does the function.

What must a variable name start with?

A letter or underscore

What does A or B mean in python?

A or B or both

What are types?

A set of values and operations on these values

What is an argument?

An input value to assign to the function parameter when it is called

What are values?

Approximations of real values (without decimal: int, with decimal: float)

What is 2 in this line of code? increment(2)

Argument, which is an input value that is assigned to the function parameter when it is called

What arguments and how do you write them?

Arguments are separated by commas and can be any expression

change_hrs('09:04', 5)

BAD

change_hrs('0:0', 3)

BAD

change_hrs('123:31', 9)

BAD

change_hrs('9:4', 1)

BAD

Modules

Built in libraries of functions and variables

What happens when you type C:\> python script.py

C:/> No output, you're back at the command line!

How does avoiding form keep variables separate

C:\> python >>> e = 12345 >>> import math >>> math.e 2.71... >>> e 12345

How do you import a module from inside Python?

C:\> python >>> import my_module >>> my_module.x 9 Needs to be the same name as the file without the ".py" (in this case, the module text file was titled my_module.py)

What does "+" mean for strings?

Catenation

What does python do for the following code: >>>1/2.6

Convert 1 to float 1.0, then calculate 1.0/2.6=0.3846

'A double quote "

ERROR

'Output: ' + 6 / 2

ERROR

(5 / 0 > 1) and False

ERROR

(5 / 0 > 1) or False

ERROR

False or (5 / 0 > 1)

ERROR

s.index('x')

ERROR

s[15]

ERROR

target = 'HeLLo:WorLd!' 'target'.index(target)

ERROR

true

ERROR

What does python do with expressions?

Evaluate

Is x==5 an expression or statement?

Expression

Expression vs. statements

Expression - represents something - python evaluates it - results is a value Statement - does something - python executes it - doesn't need to result in a value

False and (5 / 0 > 1)

False

False or False

False

True and False

False

True or false: a type represents something

False, expressions represent something

How do you run a script?

From the command line, type: C:/> python my_module.py

What are variables in global space called?

Global variables

Where can functions access variables?

In their call frame or the global space

What does python do when reading a function?

It learns about the function but skips everything inside the function until the function called (doesn't execute function body until function is called).

What happens if you enter the following code into python? >>>x=5

It looks like nothing happened but Python assigned the variable 5 to x

What does it mean for python to be dynamically typed?

Its variables can hold values of any type and can hold different types at different times

What is rule #1 of running a script?

Make sure you are in the command line. If you see >>>, exit python interactive mode!

Variable

Named memory location (box) that contains a value

When updating the value of x, do you create a new box?

No, cross out old one and write the new one on the side.

What is n in this line of code? def increment(n)

Parameter, which is a variable where input to a function is stored

Operation precedence

Paratheses highest, logical ops lowest

What is the global space?

Purple box that we previously labeled; what python can access directly

What are floating point errors?

Python can't store most real numbers exactly, which results in representation error

What happens with the following code: >>>1/int(2.6)

Python turns 2.6 into 2 Then, it casts 1 to 1.0 and 2 to 2.0 because / is float division

How are strings indexed?

Starting from 0, each character in a string is assigned a number

Is x=5 an expression or statement?

Statement

Variable assignment/assignment statement

Takes an expression on RHS, executes it, and then stores the value in a variable on the LHS

What are call stacks?

The place in memory where call frames live

What does return <expression> do?

The return statement passes a value from the function to the caller

What happens when you write a function in a script and run it? For example: #simple_math.py """script that defines and calls one simple math function""" def increment(n): """Returns: n+1""" return n+1 x = increment(2)

The script doesn't print anything. The function returns the value (it gets saved in x) but does not print it. C:/> python simple_math.py C:/>

What happens with function body statements placed after a return statement?

They are ignored

How do you draw call frames?

Top left - function name Top right - instruction counter (line number of the NEXT statement in the function body to execute, starts with 1st statement in function body) Draw parameters as variables

3 < 5

True

True

True

True and True

True

True or (False and True)

True

True or False

True

True or false: functions can access anything global space

True

True or false: python is dynamically typed

True

True or false: a type determines the meaning of an operation

True, "+" means something different for strings vs. integers

What is the difference between type(2) vs. float(2)?

Type(2) tells you the type of the value 2 >>>type(2) <class 'int'> Float(2) converts the value 2 to an integer >>>float(2) 2.0

What do types belong to?

Types belong to values, not variables

How do you access a module in Python?

Use import command: import <module name> >>>import math

Type: boolean

Values are True or False (must be capitalized)

Type: int

Values are real numbers without decimals

Type: str

Values are sequence of characters

What is a parameter?

Variable where input to function is stored

How do you access characters?

With [] - called "string slicing" >>> s = "abc d" >>> s[0] 'a'

How do you convert from one type to another?

Write out the type that you are trying to convert to followed by parantheses >>>float(2) 2.0 >>>int(2.7) 2

Is the following acceptable in python? >>>x=1 >>>x/2.0

Yes!

Can you import everything from a module?

Yes, but not recommended C:\> python >>> from math import * >>> pi 3.1415...

What does it mean if you see > instead of >>>?

You're not in python interactive mode!

What's the difference between calling math.e and e?

e = 12345 >>> math.e 2.71... >>> e 12345

def change_hrs(timestr, change): """ Returns a new 24-hour string derived by updating timestr by change hours. The returned string is formatted as given in the preconditions for timestr. Preconditions: timestr: An "hours:minutes" 24-hour time as a string. No leading or trailing spaces. No leading zeros in the hours part, except that hours can be just "0". The minutes part is exactly two digits. Both the hours and minutes are non-negative. 0 <= hours <= 23 0 <= minutes <=59 change: An int """

find_colon = timestr.index(':') hours_int = int(timestr[:find_colon]) new_hours_int = ((change+hours_int)%24) outstr = str(new_hours_int)+timestr[colon:] return outstr

What is an alternative way of importing?

from command: from<module>import <function name> C:\> python >>> from math import pi >>> pi 3.1415...

sys

information about your OS

Always-available built in functions

int(), float(), bool(), type(), exit()

def replace_first(word, target, rep): """Returns: a copy of string `word` with the FIRST instance of string `target` in `word` replaced by string `rep`. Example: replace_first('THanks', 'H', 'h') -> 'Thanks' Preconditions: `target` has length >=1 and appears in `word`. As mentioned, all the arguments have type str. """

pos = word.index(target) print('pos is:' + repr(pos)) before = word[:target] print('before is:' + repr(before)) after = word[pos+len(target):] print('after is:' + repr(after)) result = before + rep + after return result

How do you create evidence that a script ran?

print(<expression>)

io

read/write from files

How do you write function calls?

this_my_function(x,y)

How do you determine a value's type in python?

type( )

string

useful string functions


Set pelajaran terkait

Art Appreciation - Three-Dimensional Media:Craft

View Set

APEH Chapter 20-25 question 1-30

View Set

Developmental Psych 3341 Michalski- Exam #1

View Set

MSF (Motorcycle Safety Foundation) Rider's Course

View Set

VARCAROLIS Chapter 28: Child, Older Adult, and Intimate Partner Violence

View Set

relations & functions assignment

View Set