Python 3.11.5 (main, Sep 11 2023, 08:31:25) [Clang 14.0.6 ]

Type "copyright", "credits" or "license" for more information.


IPython 8.15.0 -- An enhanced Interactive Python.


Restarting kernel...


In [1]: a = 1


In [2]: a = a + 1


In [3]: a = a + 1


In [4]: a

Out[4]: 3


In [5]: a = a + 1


In [6]: a += 1


In [7]: s = "Hello"


In [8]: help(s.count)

Help on built-in function count:


count(...) method of builtins.str instance

S.count(sub[, start[, end]]) -> int


Return the number of non-overlapping occurrences of substring sub in

string S[start:end]. Optional arguments start and end are

interpreted as in slice notation.



In [9]: runfile('/Users/py4cs/Desktop/feedback/lab3.py', wdir='/Users/py4cs/Desktop/feedback')


In [10]: import math


In [11]: math.__file__

Out[11]: '/Users/py4cs/anaconda3/lib/python3.11/lib-dynload/math.cpython-311-darwin.so'


In [12]: runfile('/Users/py4cs/Desktop/feedback/for-each-and-for-loop.py', wdir='/Users/py4cs/Desktop/feedback')

apple

banana

coconut


In [13]: runfile('/Users/py4cs/Desktop/feedback/for-each-and-for-loop.py', wdir='/Users/py4cs/Desktop/feedback')

apple

banana

coconut

apple

banana

coconut


In [14]: runfile('/Users/py4cs/Desktop/feedback/for-each-and-for-loop.py', wdir='/Users/py4cs/Desktop/feedback')

apple

banana

coconut

apple

banana

coconut


In [15]: runfile('/Users/py4cs/Desktop/feedback/for-each-and-for-loop.py', wdir='/Users/py4cs/Desktop/feedback')

apple

banana

coconut

apple

banana

coconut


In [16]: runfile('/Users/py4cs/Desktop/feedback/for-each-and-for-loop.py', wdir='/Users/py4cs/Desktop/feedback')

apple

dog

banana

cat

coconut

mouse


In [17]: animals

Out[17]: ['dog', 'cat', 'mouse']


In [18]: animals.append("XXX")


In [19]: animals

Out[19]: ['dog', 'cat', 'mouse', 'XXX']


In [20]: runfile('/Users/py4cs/Desktop/feedback/for-each-and-for-loop.py', wdir='/Users/py4cs/Desktop/feedback')

apple

dog

banana

cat

coconut

mouse

apple dog

banana cat

coconut mouse


In [21]: assert True


In [22]: assert False

Traceback (most recent call last):


Cell In[22], line 1

assert False


AssertionError



In [23]: assert 10 > 20

Traceback (most recent call last):


Cell In[23], line 1

assert 10 > 20


AssertionError



In [24]: runfile('/Users/py4cs/Desktop/feedback/for-each-and-for-loop.py', wdir='/Users/py4cs/Desktop/feedback')

Traceback (most recent call last):


File ~/anaconda3/lib/python3.11/site-packages/spyder_kernels/py3compat.py:356 in compat_exec

exec(code, globals, locals)


File ~/Desktop/feedback/for-each-and-for-loop.py:10

assert len(fruits) == len(animals)


AssertionError



In [25]: runfile('/Users/py4cs/Desktop/feedback/for-each-and-for-loop.py', wdir='/Users/py4cs/Desktop/feedback')


In [26]: runfile('/Users/py4cs/Desktop/feedback/for-each-and-for-loop.py', wdir='/Users/py4cs/Desktop/feedback')

apple

dog

banana

cat

coconut

mouse

apple dog

banana cat

coconut mouse


In [27]: runfile('/Users/py4cs/Desktop/fifoqueue.py', wdir='/Users/py4cs/Desktop')


In [28]: %reset

Once deleted, variables cannot be recovered. Proceed (y/[n])? y


In [29]: runfile('/Users/py4cs/Desktop/fifoqueue.py', wdir='/Users/py4cs/Desktop')


In [30]: length()

Out[30]: 0


In [31]: runfile('/Users/py4cs/Desktop/fifoqueue.py', wdir='/Users/py4cs/Desktop')


In [32]: show()

None


In [33]: animals = ['dog', 'cat', 'mouse']


In [34]: animals.reverse?

Signature: animals.reverse()

Docstring: Reverse *IN PLACE*.

Type: builtin_function_or_method


In [35]: help(animals.reverse)

Help on built-in function reverse:


reverse() method of builtins.list instance

Reverse *IN PLACE*.



In [36]: animals

Out[36]: ['dog', 'cat', 'mouse']


In [37]: animals.reverse()


In [38]: animals

Out[38]: ['mouse', 'cat', 'dog']


In [39]: runfile('/Users/py4cs/Desktop/fifoqueue.py', wdir='/Users/py4cs/Desktop')


In [40]: show()

[]


In [41]: animals.copy()

Out[41]: ['mouse', 'cat', 'dog']


In [42]: dir(q)

Out[42]:

['__add__',

'__class__',

'__class_getitem__',

'__contains__',

'__delattr__',

'__delitem__',

'__dir__',

'__doc__',

'__eq__',

'__format__',

'__ge__',

'__getattribute__',

'__getitem__',

'__getstate__',

'__gt__',

'__hash__',

'__iadd__',

'__imul__',

'__init__',

'__init_subclass__',

'__iter__',

'__le__',

'__len__',

'__lt__',

'__mul__',

'__ne__',

'__new__',

'__reduce__',

'__reduce_ex__',

'__repr__',

'__reversed__',

'__rmul__',

'__setattr__',

'__setitem__',

'__sizeof__',

'__str__',

'__subclasshook__',

'append',

'clear',

'copy',

'count',

'extend',

'index',

'insert',

'pop',

'remove',

'reverse',

'sort']


In [43]: q.insert?

Signature: q.insert(index, object, /)

Docstring: Insert object before index.

Type: builtin_function_or_method


In [44]: animals

Out[44]: ['mouse', 'cat', 'dog']


In [45]: animals.insert(0, 'rat')


In [46]: animals

Out[46]: ['rat', 'mouse', 'cat', 'dog']


In [47]: runfile('/Users/py4cs/Desktop/fifoqueue.py', wdir='/Users/py4cs/Desktop')


In [48]: add("Peter")


In [49]: add("Mary")


In [50]: add("Paul")


In [51]: show()

['Paul', 'Mary', 'Peter']


In [52]: runcell(0, '/Users/py4cs/Desktop/fifoqueue.py')


In [53]: runfile('/Users/py4cs/Desktop/fifoqueue.py', wdir='/Users/py4cs/Desktop')

Traceback (most recent call last):


File ~/anaconda3/lib/python3.11/site-packages/spyder_kernels/py3compat.py:356 in compat_exec

exec(code, globals, locals)


File ~/Desktop/fifoqueue.py:27

add("Peter")


File ~/Desktop/fifoqueue.py:18 in add

q.insert(name)


TypeError: insert expected 2 arguments, got 1



In [54]: runfile('/Users/py4cs/Desktop/fifoqueue.py', wdir='/Users/py4cs/Desktop')


In [55]: show()

['Paul', 'Mary', 'Peter']


In [56]: animals.pop?

Signature: animals.pop(index=-1, /)

Docstring:

Remove and return item at index (default last).


Raises IndexError if list is empty or index is out of range.

Type: builtin_function_or_method


In [57]: animals

Out[57]: ['rat', 'mouse', 'cat', 'dog']


In [58]: animals.pop()

Out[58]: 'dog'


In [59]: animals

Out[59]: ['rat', 'mouse', 'cat']


In [60]: runfile('/Users/py4cs/Desktop/fifoqueue.py', wdir='/Users/py4cs/Desktop')


In [61]: show()

['Paul', 'Mary', 'Peter']


In [62]: next()

Out[62]: 'Peter'


In [63]: show()

['Paul', 'Mary']


In [64]: add("AgentX")


In [65]: next_()

Traceback (most recent call last):


Cell In[65], line 1

next_()


NameError: name 'next_' is not defined



In [66]: runfile('/Users/py4cs/Desktop/fifoqueue.py', wdir='/Users/py4cs/Desktop')


In [67]: next_()

Out[67]: 'Peter'


In [68]: next_()

Out[68]: 'Mary'


In [69]: next_()

Out[69]: 'Paul'


In [70]: next_()

Traceback (most recent call last):


Cell In[70], line 1

next_()


File ~/Desktop/fifoqueue.py:24 in next_

next_customer = q.pop()


IndexError: pop from empty list



In [71]: next_()

Traceback (most recent call last):


Cell In[71], line 1

next_()


File ~/Desktop/fifoqueue.py:24 in next_

next_customer = q.pop()


IndexError: pop from empty list



In [72]: %debug

Traceback (most recent call last):


Cell In[72], line 1

get_ipython().run_line_magic('debug', '')


File ~/anaconda3/lib/python3.11/site-packages/IPython/core/interactiveshell.py:2432 in run_line_magic

result = fn(*args, **kwargs)


File ~/anaconda3/lib/python3.11/site-packages/IPython/core/magics/execution.py:469 in debug

self._debug_post_mortem()


File ~/anaconda3/lib/python3.11/site-packages/IPython/core/magics/execution.py:483 in _debug_post_mortem

self.shell.debugger(force=True)


File ~/anaconda3/lib/python3.11/site-packages/IPython/core/interactiveshell.py:1146 in debugger

self.InteractiveTB.debugger(force=True)


File ~/anaconda3/lib/python3.11/site-packages/IPython/core/ultratb.py:1253 in debugger

self.pdb.interaction(None, exc)


File ~/anaconda3/lib/python3.11/site-packages/spyder_kernels/customize/spyderpdb.py:330 in interaction

self.setup(frame, traceback)


File ~/anaconda3/lib/python3.11/pdb.py:278 in setup

self.stack, self.curindex = self.get_stack(f, tb)


File ~/anaconda3/lib/python3.11/bdb.py:535 in get_stack

if t and t.tb_frame is f:


AttributeError: 'IndexError' object has no attribute 'tb_frame'



In [73]: add("Peter")


In [74]: add("Peter2")


In [75]: add("Peter3")


In [76]: length()

Out[76]: 3


In [77]: show()

['Peter3', 'Peter2', 'Peter']


In [78]: next_()

Out[78]: 'Peter'


In [79]: show()

['Peter3', 'Peter2']


In [80]: next_()

Out[80]: 'Peter2'


In [81]: length()

Out[81]: 1


In [82]: add("X")


In [83]: a

Traceback (most recent call last):


Cell In[83], line 1

a


NameError: name 'a' is not defined



In [84]: a = [0, 2, 4, 6] # bind name 'a' to list


In [85]: a

Out[85]: [0, 2, 4, 6]


In [86]: b = a


In [87]: b

Out[87]: [0, 2, 4, 6]


In [88]: b[0] = 100


In [89]: b

Out[89]: [100, 2, 4, 6]


In [90]: a

Out[90]: [100, 2, 4, 6]


In [91]: id(a)

Out[91]: 5232662720


In [92]: id(b)

Out[92]: 5232662720


In [93]: id(a) == id(b)

Out[93]: True


In [94]: a is b

Out[94]: True


In [95]: a

Out[95]: [100, 2, 4, 6]


In [96]: b

Out[96]: [100, 2, 4, 6]


In [97]: a == b

Out[97]: True


In [98]: c = 1


In [99]: d = 1.0


In [100]: id(c)

Out[100]: 4309624024


In [101]: id(d)

Out[101]: 5226043216


In [102]: c is b

Out[102]: False


In [103]: c == 1

Out[103]: True


In [104]: c == d

Out[104]: True


In [105]: c is d

Out[105]: False


In [106]: reset

Once deleted, variables cannot be recovered. Proceed (y/[n])? y


In [107]: f = open('test.txt', 'wt') # default mode read text


In [108]: type(f)

Out[108]: _io.TextIOWrapper


In [109]: dir(f)

Out[109]:

['_CHUNK_SIZE',

'__class__',

'__del__',

'__delattr__',

'__dict__',

'__dir__',

'__doc__',

'__enter__',

'__eq__',

'__exit__',

'__format__',

'__ge__',

'__getattribute__',

'__getstate__',

'__gt__',

'__hash__',

'__init__',

'__init_subclass__',

'__iter__',

'__le__',

'__lt__',

'__ne__',

'__new__',

'__next__',

'__reduce__',

'__reduce_ex__',

'__repr__',

'__setattr__',

'__sizeof__',

'__str__',

'__subclasshook__',

'_checkClosed',

'_checkReadable',

'_checkSeekable',

'_checkWritable',

'_finalizing',

'buffer',

'close',

'closed',

'detach',

'encoding',

'errors',

'fileno',

'flush',

'isatty',

'line_buffering',

'mode',

'name',

'newlines',

'read',

'readable',

'readline',

'readlines',

'reconfigure',

'seek',

'seekable',

'tell',

'truncate',

'writable',

'write',

'write_through',

'writelines']


In [110]: f.write("first line\nsecond line")

Out[110]: 22


In [111]: f.close()


In [112]: help(open)

Help on function open in module io:


open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Open file and return a stream. Raise OSError upon failure.


file is either a text or byte string giving the name (and the path

if the file isn't in the current working directory) of the file to

be opened or an integer file descriptor of the file to be

wrapped. (If a file descriptor is given, it is closed when the

returned I/O object is closed, unless closefd is set to False.)


mode is an optional string that specifies the mode in which the file

is opened. It defaults to 'r' which means open for reading in text

mode. Other common values are 'w' for writing (truncating the file if

it already exists), 'x' for creating and writing to a new file, and

'a' for appending (which on some Unix systems, means that all writes

append to the end of the file regardless of the current seek position).

In text mode, if encoding is not specified the encoding used is platform

dependent: locale.getencoding() is called to get the current locale encoding.

(For reading and writing raw bytes use binary mode and leave encoding

unspecified.) The available modes are:


========= ===============================================================

Character Meaning

--------- ---------------------------------------------------------------

'r' open for reading (default)

'w' open for writing, truncating the file first

'x' create a new file and open it for writing

'a' open for writing, appending to the end of the file if it exists

'b' binary mode

't' text mode (default)

'+' open a disk file for updating (reading and writing)

========= ===============================================================


The default mode is 'rt' (open for reading text). For binary random

access, the mode 'w+b' opens and truncates the file to 0 bytes, while

'r+b' opens the file without truncation. The 'x' mode implies 'w' and

raises an `FileExistsError` if the file already exists.


Python distinguishes between files opened in binary and text modes,

even when the underlying operating system doesn't. Files opened in

binary mode (appending 'b' to the mode argument) return contents as

bytes objects without any decoding. In text mode (the default, or when

't' is appended to the mode argument), the contents of the file are

returned as strings, the bytes having been first decoded using a

platform-dependent encoding or using the specified encoding if given.


buffering is an optional integer used to set the buffering policy.

Pass 0 to switch buffering off (only allowed in binary mode), 1 to select

line buffering (only usable in text mode), and an integer > 1 to indicate

the size of a fixed-size chunk buffer. When no buffering argument is

given, the default buffering policy works as follows:


* Binary files are buffered in fixed-size chunks; the size of the buffer

is chosen using a heuristic trying to determine the underlying device's

"block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.

On many systems, the buffer will typically be 4096 or 8192 bytes long.


* "Interactive" text files (files for which isatty() returns True)

use line buffering. Other text files use the policy described above

for binary files.


encoding is the name of the encoding used to decode or encode the

file. This should only be used in text mode. The default encoding is

platform dependent, but any encoding supported by Python can be

passed. See the codecs module for the list of supported encodings.


errors is an optional string that specifies how encoding errors are to

be handled---this argument should not be used in binary mode. Pass

'strict' to raise a ValueError exception if there is an encoding error

(the default of None has the same effect), or pass 'ignore' to ignore

errors. (Note that ignoring encoding errors can lead to data loss.)

See the documentation for codecs.register or run 'help(codecs.Codec)'

for a list of the permitted encoding error strings.


newline controls how universal newlines works (it only applies to text

mode). It can be None, '', '\n', '\r', and '\r\n'. It works as

follows:


* On input, if newline is None, universal newlines mode is

enabled. Lines in the input can end in '\n', '\r', or '\r\n', and

these are translated into '\n' before being returned to the

caller. If it is '', universal newline mode is enabled, but line

endings are returned to the caller untranslated. If it has any of

the other legal values, input lines are only terminated by the given

string, and the line ending is returned to the caller untranslated.


* On output, if newline is None, any '\n' characters written are

translated to the system default line separator, os.linesep. If

newline is '' or '\n', no translation takes place. If newline is any

of the other legal values, any '\n' characters written are translated

to the given string.


If closefd is False, the underlying file descriptor will be kept open

when the file is closed. This does not work when a file name is given

and must be True in that case.


A custom opener can be used by passing a callable as *opener*. The

underlying file descriptor for the file object is then obtained by

calling *opener* with (*file*, *flags*). *opener* must return an open

file descriptor (passing os.open as *opener* results in functionality

similar to passing None).


open() returns a file object whose type depends on the mode, and

through which the standard file operations such as reading and writing

are performed. When open() is used to open a file in a text mode ('w',

'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open

a file in a binary mode, the returned class varies: in read binary

mode, it returns a BufferedReader; in write binary and append binary

modes, it returns a BufferedWriter, and in read/write mode, it returns

a BufferedRandom.


It is also possible to use a string or bytearray as a file for both

reading and writing. For strings StringIO can be used like a file

opened in a text mode, and for bytes a BytesIO can be used like a file

opened in a binary mode.



In [113]: f = open(file='test.txt', mode='wt') # default mode read text


In [114]: f = open(mode='wt', file='test.txt') # default mode read text


In [115]: f.write("first line\nsecond line")

Out[115]: 22


In [116]: f.close()


In [117]: f = open(mode='at', file='test.txt') # default mode read text


In [118]: f.write("\nthird line")

Out[118]: 11


In [119]: f.close()


In [120]: open(mode='at', file='test.txt') # default mode read text

Out[120]: <_io.TextIOWrapper name='test.txt' mode='at' encoding='UTF-8'>


In [121]: f = open(file="test.txt", mode='rt')


In [122]: f.read()

Out[122]: 'first line\nsecond line\nthird line'


In [123]: f.read()

Out[123]: ''


In [124]: f.close()


In [125]: f = open(file="test.txt", mode='rt'); f.readlines(); f.close()


In [126]: f = open(file="test.txt", mode='rt')


In [127]: f.readlines()

Out[127]: ['first line\n', 'second line\n', 'third line']


In [128]: f = open(file="test.txt", mode='rt'); lines = f.readlines(); f.close()


In [129]: lines

Out[129]: ['first line\n', 'second line\n', 'third line']


In [130]: lines[0]

Out[130]: 'first line\n'


In [131]: lines[0].strip()

Out[131]: 'first line'


In [132]: g

Traceback (most recent call last):


Cell In[132], line 1

g


NameError: name 'g' is not defined



In [133]: g = "Hello World"


In [134]: g

Out[134]: 'Hello World'


In [135]: f = open(file="test.txt", mode='rt'); data = f.read(); f.close()


In [136]: data

Out[136]: 'first line\nsecond line\nthird line'


In [137]: data.count('i')

Out[137]: 5


In [138]: with open('test.txt', 'rt') as f:

     ...: lines = f.readlines()

     ...:


In [139]: data

Out[139]: 'first line\nsecond line\nthird line'


In [140]: data.index('i')

Out[140]: 1


In [141]: data.index('third')

Out[141]: 23


In [142]: data

Out[142]: 'first line\nsecond line\nthird line'


In [143]: data.split()

Out[143]: ['first', 'line', 'second', 'line', 'third', 'line']


In [144]: len(data.split())

Out[144]: 6


In [145]: data.split(sep='\n')

Out[145]: ['first line', 'second line', 'third line']


In [146]: data.split(sep='\n')[-1]

Out[146]: 'third line'


In [147]: data.split(sep='\n')[-1].split()

Out[147]: ['third', 'line']


In [148]: data.split(sep='\n')[-1].split()[0]

Out[148]: 'third'


In [149]: data

Out[149]: 'first line\nsecond line\nthird line'


In [150]: data.split('i')

Out[150]: ['f', 'rst l', 'ne\nsecond l', 'ne\nth', 'rd l', 'ne']


In [151]: data.split('i')

Out[151]: ['f', 'rst l', 'ne\nsecond l', 'ne\nth', 'rd l', 'ne']


In [152]: data.split('i')[2]

Out[152]: 'ne\nsecond l'


In [153]: data.split('i')[2].split('\n')

Out[153]: ['ne', 'second l']


In [154]: reset -f


In [155]: runcell(0, '/Users/py4cs/Desktop/shopping_cost.py')


In [156]: lines

Out[156]:

['bread 1 1.39\n',

'tomatoes 6 0.26\n',

'milk 3 1.45\n',

'coffee 3 2.99\n']


In [157]: line = lines[0]


In [158]: line

Out[158]: 'bread 1 1.39\n'


In [159]: line.split()

Out[159]: ['bread', '1', '1.39']


In [160]: words = line.split()


In [161]: itemname = words[0]


In [162]: words[1]

Out[162]: '1'


In [163]: type(words[1])

Out[163]: str


In [164]: int(words[1])

Out[164]: 1


In [165]: float(words[2])

Out[165]: 1.39


In [166]: runcell(1, '/Users/py4cs/Desktop/shopping_cost.py')


In [167]: words[0]

Out[167]: 'coffee'


In [168]: int(words[0])

Traceback (most recent call last):


Cell In[168], line 1

int(words[0])


ValueError: invalid literal for int() with base 10: 'coffee'



In [169]: int('1.39')

Traceback (most recent call last):


Cell In[169], line 1

int('1.39')


ValueError: invalid literal for int() with base 10: '1.39'



In [170]: