From 9899b859922c71790ba634e4eb20655e1d89bc3b Mon Sep 17 00:00:00 2001 From: sebastian gherghesanu Date: Tue, 8 Jan 2019 10:25:22 +0200 Subject: [PATCH 01/18] chapter2 : run & learn --- Chapter 2 - Strings/creating_strings.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/Chapter 2 - Strings/creating_strings.py b/Chapter 2 - Strings/creating_strings.py index ef49c69..905b117 100644 --- a/Chapter 2 - Strings/creating_strings.py +++ b/Chapter 2 - Strings/creating_strings.py @@ -1,15 +1,28 @@ # The following shows different methods of creating a string + +## +# +## + my_string = "Welcome to Python!" another_string = 'The bright red fox jumped the fence.' a_long_string = '''This is a multi-line string. It covers more than one line''' -# this set of strings shows how to mix single and double-quotes + +print(a_long_string) +# Q: this set of strings shows how to mix single and double-quotes +# A: mixing & nesting the different quotes my_string = "I'm a Python programmer!" otherString = 'The word "python" usually refers to a snake' tripleString = """Here's another way to embed "quotes" in a string""" # cast an integer to a string using Python's str() class my_number = 123 -my_string = str(my_number) \ No newline at end of file +my_string = str(my_number) + +print(my_number) +print(my_string) +# A: you can pass different types to print, without worrying +print(123, "aaaa", 34.0) \ No newline at end of file From c47df67f7f0c061fecea58deb8239797a47fd577 Mon Sep 17 00:00:00 2001 From: sebastian gherghesanu Date: Tue, 8 Jan 2019 10:36:29 +0200 Subject: [PATCH 02/18] chapter2 : run & learn --- Chapter 2 - Strings/creating_strings.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Chapter 2 - Strings/creating_strings.py b/Chapter 2 - Strings/creating_strings.py index 905b117..b433fcc 100644 --- a/Chapter 2 - Strings/creating_strings.py +++ b/Chapter 2 - Strings/creating_strings.py @@ -18,8 +18,22 @@ otherString = 'The word "python" usually refers to a snake' tripleString = """Here's another way to embed "quotes" in a string""" -# cast an integer to a string using Python's str() class +# checking the type my_number = 123 +print("type of my_number:", type(my_number)) + +# checking the id of teh object +print("id of my_number:", id(my_number)) + +# re-assign +my_number = 234 +print("id after re-assignment of my_number:", id(my_number)) # id changed + + +my_number2 = 22.0 +print("type of my_number2:", type(my_number2)) # float + +# cast an integer to a string using Python's str() class my_string = str(my_number) print(my_number) From 0c8bb0e61a23cb8064414606e4362403496ec2b5 Mon Sep 17 00:00:00 2001 From: sebastian gherghesanu Date: Tue, 8 Jan 2019 10:43:16 +0200 Subject: [PATCH 03/18] chapter2 : run & learn --- ...ing_strings.py => 2_1_creating_strings.py} | 17 ++++++++++++++++- .../2_2_string_concatenation.py | 19 +++++++++++++++++++ Chapter 2 - Strings/string_concatenation.py | 4 ---- 3 files changed, 35 insertions(+), 5 deletions(-) rename Chapter 2 - Strings/{creating_strings.py => 2_1_creating_strings.py} (79%) create mode 100644 Chapter 2 - Strings/2_2_string_concatenation.py delete mode 100644 Chapter 2 - Strings/string_concatenation.py diff --git a/Chapter 2 - Strings/creating_strings.py b/Chapter 2 - Strings/2_1_creating_strings.py similarity index 79% rename from Chapter 2 - Strings/creating_strings.py rename to Chapter 2 - Strings/2_1_creating_strings.py index b433fcc..263df29 100644 --- a/Chapter 2 - Strings/creating_strings.py +++ b/Chapter 2 - Strings/2_1_creating_strings.py @@ -39,4 +39,19 @@ print(my_number) print(my_string) # A: you can pass different types to print, without worrying -print(123, "aaaa", 34.0) \ No newline at end of file +print(123, "aaaa", 34.0) + +# run & learn + +''' +This is a +multi-line string. It covers more than +one line +type of my_number: +id of my_number: 4304459696 +id after re-assignment of my_number: 4304463248 +type of my_number2: +234 +234 +123 aaaa 34.0 +''' \ No newline at end of file diff --git a/Chapter 2 - Strings/2_2_string_concatenation.py b/Chapter 2 - Strings/2_2_string_concatenation.py new file mode 100644 index 0000000..5eeebb7 --- /dev/null +++ b/Chapter 2 - Strings/2_2_string_concatenation.py @@ -0,0 +1,19 @@ +# the following demonstrates how to join two strings +string_one = "My dog ate " +string_two = "my homework!" +string_three = string_one + string_two + + +# we can go further on +string_three = string_one + " " + string_two +print("string_three:", string_three) + +string_three = string_one + ' / ' + string_two +print("string_three:", string_three) + +#run & learn + +''' +string_three: My dog ate my homework! +string_three: My dog ate / my homework! +''' \ No newline at end of file diff --git a/Chapter 2 - Strings/string_concatenation.py b/Chapter 2 - Strings/string_concatenation.py deleted file mode 100644 index b080618..0000000 --- a/Chapter 2 - Strings/string_concatenation.py +++ /dev/null @@ -1,4 +0,0 @@ -# the following demonstrates how to join two strings -string_one = "My dog ate " -string_two = "my homework!" -string_three = string_one + string_two \ No newline at end of file From 9bf270c065a3025b655a497e15fd7c87d5574b9f Mon Sep 17 00:00:00 2001 From: sebastian gherghesanu Date: Tue, 8 Jan 2019 11:37:29 +0200 Subject: [PATCH 04/18] chapter2 : run & learn --- Chapter 2 - Strings/2_3_string_methods.py | 27 +++++++ Chapter 2 - Strings/2_4_string_slicing.py | 56 +++++++++++++ .../2_5_string_substitution.py | 80 +++++++++++++++++++ Chapter 2 - Strings/string_methods.py | 10 --- Chapter 2 - Strings/string_slicing.py | 13 --- Chapter 2 - Strings/string_substitution.py | 54 ------------- 6 files changed, 163 insertions(+), 77 deletions(-) create mode 100644 Chapter 2 - Strings/2_3_string_methods.py create mode 100644 Chapter 2 - Strings/2_4_string_slicing.py create mode 100644 Chapter 2 - Strings/2_5_string_substitution.py delete mode 100644 Chapter 2 - Strings/string_methods.py delete mode 100644 Chapter 2 - Strings/string_slicing.py delete mode 100644 Chapter 2 - Strings/string_substitution.py diff --git a/Chapter 2 - Strings/2_3_string_methods.py b/Chapter 2 - Strings/2_3_string_methods.py new file mode 100644 index 0000000..f229273 --- /dev/null +++ b/Chapter 2 - Strings/2_3_string_methods.py @@ -0,0 +1,27 @@ +# string methods +my_string = "This is a string!" +my_string.upper() # + +print(my_string.upper()) +"This is a string!".upper() + +# get a list of string methods +dir(my_string) +print(dir(my_string)) + +# get help +help(my_string.capitalize) + +# run & learn +''' +THIS IS A STRING! +['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] +Help on built-in function capitalize: + +capitalize(...) method of builtins.str instance + S.capitalize() -> str + + Return a capitalized version of S, i.e. make the first character + have upper case and the rest lower case. + +''' \ No newline at end of file diff --git a/Chapter 2 - Strings/2_4_string_slicing.py b/Chapter 2 - Strings/2_4_string_slicing.py new file mode 100644 index 0000000..c6a3ba7 --- /dev/null +++ b/Chapter 2 - Strings/2_4_string_slicing.py @@ -0,0 +1,56 @@ +# string slicing +my_string = "I like Python!" + + +# just the first character but not included the second char +# 0 --> string length len(my_string) - 1 +print("string length:", len(my_string)) + +print(my_string[0:1]) + +#same as +my_string[:1] +print(my_string[:1]) + +my_string[0:12] + +my_string[0:13] +print(my_string[0:13]) + +my_string[0:14] +print(my_string[0:14]) # full string + +print(my_string[0: len(my_string)]) + +my_string[0:-5] +print(my_string[0:-5]) # starts with 0 but end 5 characters before ending + +#same as +print(my_string[0: len(my_string) - 5]) +print(my_string[0: 14 - 5]) + +# full +my_string[:] +print(my_string[:]) + +#starting with the 3rd char(0, 1, 2) until the end +my_string[2:] +print(my_string[2:]) + +# string indexing +print(my_string[0]) # prints the first character of the string + +''' +string length: 14 +I +I +I like Python +I like Python! +I like Python! +I like Py +I like Py +I like Py +I like Python! +like Python! +I +''' \ No newline at end of file diff --git a/Chapter 2 - Strings/2_5_string_substitution.py b/Chapter 2 - Strings/2_5_string_substitution.py new file mode 100644 index 0000000..7aaf6ab --- /dev/null +++ b/Chapter 2 - Strings/2_5_string_substitution.py @@ -0,0 +1,80 @@ +# string substitution +# or substitution + +# the old way +# $ is the substitution sign (to be inserted soon) +my_string = "I like %s" % "Python" +print( my_string) #I like Python + +var = "cookies" +newString = "I like %s" % var +newString +print(newString) #I like cookies + +another_string = "I like %s and %s" % ("Python", var) +print(another_string) #I like Python and cookies + +# you have to be very specific with what to insert +# this will cause a TypeError +# another_string = "I like %s and %s" % "Python" + +# this will work +another_string = "I like %s and %s" % ("Python", "Python") +print(another_string) #I like Python and Python + +# string formatting +my_string = "%i + %i = %i" % (1,2,3) +print(my_string) + +float_string = "%f" % (1.23) +float_string + +float_string2 = "%.2f" % (1.23) +float_string2 + +float_string3 = "%.2f" % (1.237) +float_string3 + +# passing bad data raises a TypeError +#int_float_err = "%i + %f" % ("1", "2.00") + +# did you spot the error, then fix +int_float = "%i + %f" % (1, 2.00) +print(int_float) + +# this is bad too +#int_float_err = "%i + %f" % (1, "2.00") + + +# --------------------------------------------- +# new style of string substitution / formatting +# pay attention to the syntax: the type is after the paranthesis %(value_to_be_inserted)type_of_value +print("%(lang)s is fun!" % {"lang":"Python"}) # too verbose? +# the advantage is that you can reuse the same value to be imserted +print("%(value)s %(value)s %(value)s !" % {"value":"SPAM"}) + +# this one won't work! +# print("%(x)i + %(y)i = %(z)i" % {"x":1, "y":2}) + +# this is a fix of the previous example +print("%(x)i + %(y)i = %(z)i" % {"x":1, "y":2, "z":3}) + +# messing with the order of substitution +# another variant, without telling the type +py = "Python is as simple as {0}, {1}, {2}".format("a", "b", "c") +print(py) +py = "Python is as simple as {1}, {0}, {2}".format("a", "b", "c") +print(py) + +# careless without type +py = "Python is as simple as {0}, {1}".format(2, 0.3) +print(py) + +# doing the substitution from a map (dictionary) +# creating the dict and then doing the substitution by the name of the dictionary +dick = {"x": 0, "y": 10, "z": 300} +print("Graph a point at where x={x} and y={y}".format(**dick)) + +# if the key is missing we have an error : KeyError: 't' +dick = {"x": 0, "y": 10, "z": 300} +# print("Graph a point at where x={x} and t={t}".format(**dick)) diff --git a/Chapter 2 - Strings/string_methods.py b/Chapter 2 - Strings/string_methods.py deleted file mode 100644 index 4eced9f..0000000 --- a/Chapter 2 - Strings/string_methods.py +++ /dev/null @@ -1,10 +0,0 @@ -# string methods -my_string = "This is a string!" -my_string.upper() # or print(my_string.upper()) -"This is a string!".upper() - -# get a list of string methods -dir(my_string) - -# get help -help(my_string.capitalize) diff --git a/Chapter 2 - Strings/string_slicing.py b/Chapter 2 - Strings/string_slicing.py deleted file mode 100644 index 9ef51df..0000000 --- a/Chapter 2 - Strings/string_slicing.py +++ /dev/null @@ -1,13 +0,0 @@ -# string slicing -my_string = "I like Python!" -my_string[0:1] -my_string[:1] -my_string[0:12] -my_string[0:13] -my_string[0:14] -my_string[0:-5] -my_string[:] -my_string[2:] - -# string indexing -print(my_string[0]) # prints the first character of the string \ No newline at end of file diff --git a/Chapter 2 - Strings/string_substitution.py b/Chapter 2 - Strings/string_substitution.py deleted file mode 100644 index 5c47187..0000000 --- a/Chapter 2 - Strings/string_substitution.py +++ /dev/null @@ -1,54 +0,0 @@ -# string substitution - -# the old way -my_string = "I like %s" % "Python" -my_string - -var = "cookies" -newString = "I like %s" % var -newString - - -another_string = "I like %s and %s" % ("Python", var) -another_string - -# this will cause a TypeError -another_string = "I like %s and %s" % "Python" - -# string formatting -my_string = "%i + %i = %i" % (1,2,3) -my_string - -float_string = "%f" % (1.23) -float_string - -float_string2 = "%.2f" % (1.23) -float_string2 - -float_string3 = "%.2f" % (1.237) -float_string3 - -# passing bad data raises a TypeError -int_float_err = "%i + %f" % ("1", "2.00") - -# this is bad too -int_float_err = "%i + %f" % (1, "2.00") - -# --------------------------- -# new style of string substitution / formatting -print("%(lang)s is fun!" % {"lang":"Python"}) -print("%(value)s %(value)s %(value)s !" % {"value":"SPAM"}) - -# this one won't work! -print("%(x)i + %(y)i = %(z)i" % {"x":1, "y":2}) - -# this is a fix of the previous example -print("%(x)i + %(y)i = %(z)i" % {"x":1, "y":2, "z":3}) - -# messing with the order of substitution -"Python is as simple as {0}, {1}, {2}".format("a", "b", "c") -"Python is as simple as {1}, {0}, {2}".format("a", "b", "c") - -# creating the dict and then doing the substitution -xy = {"x":0, "y":10} -print("Graph a point at where x={x} and y={y}".format(**xy)) \ No newline at end of file From 378f58c789fc708b55f8b5d0d0b420916fb0298b Mon Sep 17 00:00:00 2001 From: sebastian gherghesanu Date: Tue, 8 Jan 2019 12:38:04 +0200 Subject: [PATCH 05/18] chapter3 : run & lear --- ...{list_examples.py => 3_1_list_examples.py} | 17 ++++--- .../3_2_tuple_examples.py | 44 +++++++++++++++++++ .../3_3_dict_examples.py | 42 ++++++++++++++++++ .../dict_examples.py | 18 -------- .../tuple_examples.py | 7 --- 5 files changed, 97 insertions(+), 31 deletions(-) rename Chapter 3 - Lists Dicts Tuples/{list_examples.py => 3_1_list_examples.py} (54%) create mode 100644 Chapter 3 - Lists Dicts Tuples/3_2_tuple_examples.py create mode 100644 Chapter 3 - Lists Dicts Tuples/3_3_dict_examples.py delete mode 100644 Chapter 3 - Lists Dicts Tuples/dict_examples.py delete mode 100644 Chapter 3 - Lists Dicts Tuples/tuple_examples.py diff --git a/Chapter 3 - Lists Dicts Tuples/list_examples.py b/Chapter 3 - Lists Dicts Tuples/3_1_list_examples.py similarity index 54% rename from Chapter 3 - Lists Dicts Tuples/list_examples.py rename to Chapter 3 - Lists Dicts Tuples/3_1_list_examples.py index c226f41..200470b 100644 --- a/Chapter 3 - Lists Dicts Tuples/list_examples.py +++ b/Chapter 3 - Lists Dicts Tuples/3_1_list_examples.py @@ -1,6 +1,6 @@ # two ways to create an empty list my_list = [] -my_list = list() +my_list = list() # call to the a method, so you need round parentheses # examples of lists my_list = [1, 2, 3] @@ -13,20 +13,25 @@ # combine / extend a list combo_list = [] one_list = [4, 5] -combo_list.extend(one_list) +combo_list.extend(one_list) # add what is the one_list to combo_list +print(combo_list) # [4, 5] -# or just concatenate the lists together +# or just concatenate the lists together (as you ar doing with strings) my_list = [1, 2, 3] +print(type(my_list)) my_list2 = ["a", "b", "c"] +print(type(my_list2)) combo_list = my_list + my_list2 +print(combo_list) # [1, 2, 3, 'a', 'b', 'c'] +print(type(combo_list)) -# sort a list +# sort a list (in place) alpha_list = [34, 23, 67, 100, 88, 2] alpha_list.sort() -alpha_list +print(alpha_list) # sorted alpha_list [2, 23, 34, 67, 88, 100] # finding a logic error alpha_list = [34, 23, 67, 100, 88, 2] sorted_list = alpha_list.sort() # the sort method returns a None object as lists sort in-place -print(sorted_list) \ No newline at end of file +print(sorted_list) # None \ No newline at end of file diff --git a/Chapter 3 - Lists Dicts Tuples/3_2_tuple_examples.py b/Chapter 3 - Lists Dicts Tuples/3_2_tuple_examples.py new file mode 100644 index 0000000..31b44ce --- /dev/null +++ b/Chapter 3 - Lists Dicts Tuples/3_2_tuple_examples.py @@ -0,0 +1,44 @@ +# a few tuple examples +# to be a tuple(has to have at least 2 values) + +my_tuple = (1, 2, 3, 4, 5) +my_tuple[0:3] # tuple slicing as in strings + +another_tuple = tuple() # creating an empty tuple +print(another_tuple) # empty tuple + +my_tuple2 = (1, "223", 23.0, "abs") +print(my_tuple2[:]) + +another_tuple += my_tuple2[:] # adding whole tuple +print(another_tuple) + +# nested tuples +some_tuple = (another_tuple, "abc") +print(some_tuple) + +# add to a tuple another tuple +some_tuple += (0, 2, "abc") +print(some_tuple) + +# list -> tuple (pass to the tuple constructor) +# turn a list into a tuple via casting +abc = tuple([1, 2, 3]) + + +# now we can solve the problem adding just one value + +bcd = tuple([1]) +print(bcd) + +print(type(bcd)) + +''' +() +(1, '223', 23.0, 'abs') +(1, '223', 23.0, 'abs') +((1, '223', 23.0, 'abs'), 'abc') +((1, '223', 23.0, 'abs'), 'abc', 0, 2, 'abc') +(1,) + +''' \ No newline at end of file diff --git a/Chapter 3 - Lists Dicts Tuples/3_3_dict_examples.py b/Chapter 3 - Lists Dicts Tuples/3_3_dict_examples.py new file mode 100644 index 0000000..f7ee921 --- /dev/null +++ b/Chapter 3 - Lists Dicts Tuples/3_3_dict_examples.py @@ -0,0 +1,42 @@ +# there are two ways to create a Python dictionary (dict) +my_dict = {} +another_dict = dict() #by constructor + +# here's an example with the dict containing data +my_other_dict = {"one": 1, "two": 2, "three": 3} + +# add a new key +my_other_dict["four"] = 4 +print(my_other_dict) + +my_other_dict.pop("four") +print(my_other_dict) + +# access values in a dict +my_other_dict["one"] +my_dict = {"name": "Mike", "address": "123 Happy Way"} + +one_dict = {"one": 1} +two_dict = {"two": 2} +one_dict.update( two_dict) +print(one_dict) + + +# check if a dict has a particular key +"name" in my_dict # returns True +print("name" in my_dict) +"state" in my_dict # returns False + +# get a view of the keys in a dict +my_dict.keys() +print(my_dict.keys()) +print(my_dict.values()) + +''' +{'three': 3, 'four': 4, 'one': 1, 'two': 2} +{'three': 3, 'one': 1, 'two': 2} +{'one': 1, 'two': 2} +True +dict_keys(['name', 'address']) +dict_values(['Mike', '123 Happy Way']) +''' \ No newline at end of file diff --git a/Chapter 3 - Lists Dicts Tuples/dict_examples.py b/Chapter 3 - Lists Dicts Tuples/dict_examples.py deleted file mode 100644 index a3c7ff4..0000000 --- a/Chapter 3 - Lists Dicts Tuples/dict_examples.py +++ /dev/null @@ -1,18 +0,0 @@ -# there are two ways to create a Python dictionary (dict) -my_dict = {} -another_dict = dict() - -# here's an example with the dict containing data -my_other_dict = {"one":1, "two":2, "three":3} - -# access values in a dict -my_other_dict["one"] -my_dict = {"name":"Mike", "address":"123 Happy Way"} -my_dict["name"] - -# check if a dict has a particular key -"name" in my_dict # returns True -"state" in my_dict # returns False - -# get a view of the keys in a dict -my_dict.keys() \ No newline at end of file diff --git a/Chapter 3 - Lists Dicts Tuples/tuple_examples.py b/Chapter 3 - Lists Dicts Tuples/tuple_examples.py deleted file mode 100644 index 7ba2279..0000000 --- a/Chapter 3 - Lists Dicts Tuples/tuple_examples.py +++ /dev/null @@ -1,7 +0,0 @@ -# a few tuple examples -my_tuple = (1, 2, 3, 4, 5) -my_tuple[0:3] # tuple slicing -another_tuple = tuple() # creating an empty tuple - -# turn a list into a tuple via casting -abc = tuple([1, 2, 3]) \ No newline at end of file From 56a3c384653c52a1b3727895e02aa40af17e17c4 Mon Sep 17 00:00:00 2001 From: sebastian gherghesanu Date: Tue, 8 Jan 2019 13:04:44 +0200 Subject: [PATCH 06/18] chapter4: run & lear --- Chapter 4 - Conditionals/conditionals.py | 115 ++++++++++++++++++++++- 1 file changed, 114 insertions(+), 1 deletion(-) diff --git a/Chapter 4 - Conditionals/conditionals.py b/Chapter 4 - Conditionals/conditionals.py index b39d867..62ca4d8 100644 --- a/Chapter 4 - Conditionals/conditionals.py +++ b/Chapter 4 - Conditionals/conditionals.py @@ -5,5 +5,118 @@ # another simple if statement var1 = 1 var2 = 3 +if var1 < var2: + print("This is also True") + +# some else if var1 > var2: - print("This is also True") \ No newline at end of file + print("This should not be printed") +else: + print("Ok, that's the good branch") + + +# -1 -----0 -------1 +if var1 < -1: + print("not reachable") +elif var1 < 0: + print("not reachable also") +elif var1 < 1: + print("almost there") +else: + print("at last") + + +if var1 < -1: + print("not reachable") +elif var1 < 0: + print("not reachable also") +elif var1 <= 1: + print("right there") +else: + print("not reachable ") + +# let's make it dynamic + +user_says = input("give a price:") + +user_says_int = int(user_says) + +#simplified +if 0 < user_says_int <= 10: + print("you got the right price, boss") +elif 10 < user_says_int <= 20: + print("that's a lot") +elif user_says_int >= 20: + print("are you nuts?") +else: + print("what?") + +# and, or, not +if (user_says_int > 0 and + user_says_int <= 10): + print("good price") +elif user_says_int > 10 and user_says_int < 20: + print("that's a lot") +elif user_says_int >= 20: + print("are you nuts?") +else: + print("what?") + +if not False: + print("ola") + +x = 4 +if x != 2: + print("boom") +else: + print("kboom") + +# in list checking +my_list = [1, 2, 3, 4] +x = 10 +if x in my_list : + print("gotcha") +else: + print("keep looking") + +# checking for Nothing +# different types (they are evaluated differently !!!!) +empty_list = [] +empty_map = {} +empty_string = "" +nothing = None +# for ex: +print(empty_list == None) # False + + +if empty_list == []: + print("empty list") +else: + print("something") + +# same as +if empty_list: + print(empty_list) +else: + print("something") + + +if not empty_list: + print("something") +else: + print("empty") + +if not nothing: + print("some value exists") +else: + print("absolutely nothing") + + + +''' +# execute this code only if this program is executed as standlone file +if __name__ == "__main__": + #whatever +''' + + From f09d5337b07f3e72fb07b385028f9f81af9cea41 Mon Sep 17 00:00:00 2001 From: sebastian gherghesanu Date: Tue, 8 Jan 2019 13:05:06 +0200 Subject: [PATCH 07/18] chapter4: run & lear --- Chapter 4 - Conditionals/conditionals.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Chapter 4 - Conditionals/conditionals.py b/Chapter 4 - Conditionals/conditionals.py index 62ca4d8..02a473c 100644 --- a/Chapter 4 - Conditionals/conditionals.py +++ b/Chapter 4 - Conditionals/conditionals.py @@ -114,7 +114,7 @@ ''' -# execute this code only if this program is executed as standlone file +# execute this code only if this program is executed as standalone file if __name__ == "__main__": #whatever ''' From 47066ebb02018a0bea20b03eaed9b27042177841 Mon Sep 17 00:00:00 2001 From: sebastian gherghesanu Date: Tue, 8 Jan 2019 15:22:02 +0200 Subject: [PATCH 08/18] chapter5: run & lear --- Chapter 5 - Loops/5_1_for_loops.py | 77 +++++++++++++++++++ .../{while_loops.py => 5_2_while_loops.py} | 57 ++++++++------ Chapter 5 - Loops/for_loops.py | 34 -------- 3 files changed, 109 insertions(+), 59 deletions(-) create mode 100644 Chapter 5 - Loops/5_1_for_loops.py rename Chapter 5 - Loops/{while_loops.py => 5_2_while_loops.py} (64%) delete mode 100644 Chapter 5 - Loops/for_loops.py diff --git a/Chapter 5 - Loops/5_1_for_loops.py b/Chapter 5 - Loops/5_1_for_loops.py new file mode 100644 index 0000000..1250ddb --- /dev/null +++ b/Chapter 5 - Loops/5_1_for_loops.py @@ -0,0 +1,77 @@ +# built-in + + +list = range(1, 10, 2) +print(type(list)) # range + +# a basic for loop +for number in range(5): + print(number) + +# you can also write the above like this +for number in [0, 1, 2, 3, 4]: + print(number) + +# this is how to loop over the keys in a dict +a_dict = {"one": 1, "two": 2, "three": 3} +for key in a_dict: + print(key) + +# sort the keys before looping over them +a_dict = {5: "five", 4: "four", 1: "one", 2: "two", 3: "three"} +keys = a_dict.keys() # set and it will order the keys +print("the keys", keys) + +# no need to sort the keys in this case +sorted(keys) # only if the key are from the same type at least +print("the keys", keys) + +''' +the keys dict_keys([1, 2, 3, 4, 5]) +the keys dict_keys([1, 2, 3, 4, 5]) +''' + +for key in keys: + print(key) + + +b_dict = {"c": 345, "a": 123, "b": 234} + +keys = b_dict.keys() +print("keys", keys) # keys dict_keys(['c', 'a', 'b']) +sorted(keys) # will not sort the keys +print("keys", keys) +''' +keys dict_keys(['c', 'a', 'b']) +keys dict_keys(['c', 'a', 'b']) +''' + +# Let's use a conditional to print out only even numbers +for number in range(10): + if number % 2 == 0: + print(number) + +# using the else statement with for +my_list = [1, 2, 3, 4, 5] +for i in my_list: + if i == 3: + print("Item found!") + break + print(i) +else: + print("Item not found!") + + + +my_list = [1, 2, 3, 4, 5] + +# if the for loop completed successfully +# then else of the for gets executed +# otherwise no: the break will break out of the for-else (will skip the else also) +for i in my_list: + if i == 6: + print("Item found!") + break + print(i) +else: + print("Item not found!") \ No newline at end of file diff --git a/Chapter 5 - Loops/while_loops.py b/Chapter 5 - Loops/5_2_while_loops.py similarity index 64% rename from Chapter 5 - Loops/while_loops.py rename to Chapter 5 - Loops/5_2_while_loops.py index e2d21d5..931a2e8 100644 --- a/Chapter 5 - Loops/while_loops.py +++ b/Chapter 5 - Loops/5_2_while_loops.py @@ -1,25 +1,32 @@ -# a simple while loop -i = 0 -while i < 10: - print(i) - i = i + 1 - -# this is how to break out of a loop -while i < 10: - print(i) - if i == 5: - break - i += 1 - -# an example of break and continue -i = 0 -while i < 10: - if i == 3: - i += 1 - continue - - print(i) - - if i == 5: - break - i += 1 \ No newline at end of file +# a simple while loop +i = 0 +while i < 10: + print(i) + i = i + 1 + +# this is how to break out of a loop +while i < 10: + print(i) + if i == 5: + break # flow control tool + i += 1 + +# an example of break and continue +i = 0 +while i < 10: + if i == 3: + i += 1 + continue # the other flow control tool : skip the iteration(continue with the next iteration) + + print(i) + + if i == 5: + break + i += 1 +''' +0 +1 +2 +4 +5 +''' diff --git a/Chapter 5 - Loops/for_loops.py b/Chapter 5 - Loops/for_loops.py deleted file mode 100644 index 71fc156..0000000 --- a/Chapter 5 - Loops/for_loops.py +++ /dev/null @@ -1,34 +0,0 @@ -# a basic for loop -for number in range(5): - print(number) - -# you can also write the above like this -for number in [0, 1, 2, 3, 4]: - print(number) - -# this is how to loop over the keys in a dict -a_dict = {"one":1, "two":2, "three":3} -for key in a_dict: - print(key) - -# sort the keys before looping over them -a_dict = {1:"one", 2:"two", 3:"three"} -keys = a_dict.keys() -sorted(keys) -for key in keys: - print(key) - -# Let's use a conditional to print out only even numbers -for number in range(10): - if number % 2 == 0: - print(number) - -# using the else statement -my_list = [1, 2, 3, 4, 5] -for i in my_list: - if i == 3: - print("Item found!") - break - print(i) -else: - print("Item not found!") \ No newline at end of file From 5f0cf644314737845be8f8da94f97177bad98574 Mon Sep 17 00:00:00 2001 From: sebastian gherghesanu Date: Tue, 8 Jan 2019 15:36:55 +0200 Subject: [PATCH 09/18] chapter6: run & lear --- Chapter 6 - Comprehensions/comprehensions.py | 26 ++++++++++++++++---- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/Chapter 6 - Comprehensions/comprehensions.py b/Chapter 6 - Comprehensions/comprehensions.py index e05a5c3..c0b973b 100644 --- a/Chapter 6 - Comprehensions/comprehensions.py +++ b/Chapter 6 - Comprehensions/comprehensions.py @@ -1,24 +1,40 @@ # a simple list comprehension +# just an one line for loop that produces a Python list data structure x = [i for i in range(5)] +print(x) # turn a list of strings into a list of ints x = ['1', '2', '3', '4', '5'] y = [int(i) for i in x] +myStringList = [" abc", " dcf", "efr"] + # strip off all the leading or ending white space myStrings = [s.strip() for s in myStringList] +print(myStrings) # how to turn a list of lists into one list (flattening) vec = [[1,2,3], [4,5,6], [7,8,9]] -flat_vec = [num for elem in vec for num in elem] +flat_vec = [num for elem in vec for num in elem] # just like 2 for , just follow up the num +flatty = [num for num in vec] +print(flatty) # printing the vec +print(flatty == vec) # True +print(flat_vec) # a simple dict comprehension -print( {i: str(i) for i in range(5)} ) +print( {i: str(i) for i in range(5)} ) # just follow the construction {i: str(i) .... } +# and then ask yourself where is i coming from: for i in ... # swapping keys and values with a dict comprehension -my_dict = {1:"dog", 2:"cat", 3:"hamster"} -print( {value:key for key, value in my_dict.items()} ) +# work only if the dictionary values are immutable such as strings +my_dict = {1: "dog", 2: "cat", 3: "hamster"} +print( {value: key for key, value in my_dict.items()} ) # key is inferred +# just follow the construction {value: key} for key, value in ... should be the pairs aka my_dict.items() +# where are the value, key are coming from # turn a list into a set using a set comprehension +# something like eliminate the non-distincts from a list my_list = [1, 2, 2, 3, 4, 5, 5, 7, 8] -my_set = {x for x in my_list} \ No newline at end of file +my_set = {x for x in my_list} # set +print(my_set) +print(type(my_set)) \ No newline at end of file From c52f879e0b4d5971be25b588d25def465b86d0c1 Mon Sep 17 00:00:00 2001 From: sebastian gherghesanu Date: Tue, 8 Jan 2019 15:54:04 +0200 Subject: [PATCH 10/18] chapter5: run & learn --- Chapter 7 - Exceptions/exceptions.py | 48 +++++++++++++++++----------- 1 file changed, 29 insertions(+), 19 deletions(-) diff --git a/Chapter 7 - Exceptions/exceptions.py b/Chapter 7 - Exceptions/exceptions.py index ba8e8c3..3842ff9 100644 --- a/Chapter 7 - Exceptions/exceptions.py +++ b/Chapter 7 - Exceptions/exceptions.py @@ -1,31 +1,39 @@ +# construct try/except + + # raise a ZeroDivisionError exception try: 1 / 0 except ZeroDivisionError: print("You cannot divide by zero!") - -# this is known as a "bare except" + +# this is known as a "bare except": catch all exceptions +# not recommended (you don't know what are catching) try: 1 / 0 except: print("You cannot divide by zero!") - + # let's raise a KeyError -my_dict = {"a":1, "b":2, "c":3} +my_dict = {"a": 1, "b": 2, "c": 3} try: value = my_dict["d"] except KeyError: print("That key does not exist!") - + # now let's raise an IndexError my_list = [1, 2, 3, 4, 5] try: my_list[6] except IndexError: print("That index is not in the list!") - -# the following shows how to catch multiple exceptions -my_dict = {"a":1, "b":2, "c":3} + +# how to catch +# multiple exceptions +# the exceptions are always from the most specific to the less +# following the basket case + +my_dict = {"a": 1, "b": 2, "c": 3} try: value = my_dict["d"] except IndexError: @@ -34,35 +42,37 @@ print("This key is not in the dictionary!") except: print("Some other error occurred!") - + # here's a shorter method of catching multiple exceptions try: value = my_dict["d"] -except (IndexError, KeyError): +except (IndexError, KeyError): # nicer print("An IndexError or KeyError occurred!") - + # here is an example of the "finally" statement # note: the statement following finally always runs -my_dict = {"a":1, "b":2, "c":3} +my_dict = {"a": 1, "b": 2, "c": 3} try: value = my_dict["d"] except KeyError: print("A KeyError occurred!") finally: print("The finally statement has executed!") - + # here we learn how to use the "else" statement -# note: else only runs when no errors occur -my_dict = {"a":1, "b":2, "c":3} +# note: else only runs when no errors occur as it is in for-else construct +# if ran ok then we have an else (SO, NO EXCEPTION then it executes else:) +# this is finer than finally, which is executed anyway all the tine +my_dict = {"a": 1, "b": 2, "c": 3} try: value = my_dict["a"] except KeyError: print("A KeyError occurred!") else: print("No error occurred!") - -# this last example demonstrates both else and finally -my_dict = {"a":1, "b":2, "c":3} + +# this last example demonstrates both else and finally (else before finally) +my_dict = {"a": 1, "b": 2, "c": 3} try: value = my_dict["a"] except KeyError: @@ -70,4 +80,4 @@ else: print("No error occurred!") finally: - print("The finally statement ran!") \ No newline at end of file + print("The finally statement ran!") From 6c03f9e216362cc1e9a8ec213ebcf0d6a5edfe8c Mon Sep 17 00:00:00 2001 From: sebastian gherghesanu Date: Tue, 8 Jan 2019 18:57:55 +0200 Subject: [PATCH 11/18] chapter8: run & learn --- Chapter 8 - Working with Files/8_1_file_io.py | 46 +++++++++++++++++++ .../{write_file.py => 8_2_write_file.py} | 2 +- .../8_3_open_with.py | 15 ++++++ ...ching_errors.py => 8_4_catching_errors.py} | 5 +- ...d_close.py => 8_5_open_read _and_close.py} | 7 ++- Chapter 8 - Working with Files/file_io.py | 8 ---- Chapter 8 - Working with Files/open_with.py | 4 -- .../read_in_chunks.py | 14 ++++-- .../read_line_by_line.py | 15 +++++- 9 files changed, 95 insertions(+), 21 deletions(-) create mode 100644 Chapter 8 - Working with Files/8_1_file_io.py rename Chapter 8 - Working with Files/{write_file.py => 8_2_write_file.py} (54%) create mode 100644 Chapter 8 - Working with Files/8_3_open_with.py rename Chapter 8 - Working with Files/{catching_errors.py => 8_4_catching_errors.py} (64%) rename Chapter 8 - Working with Files/{open_and_close.py => 8_5_open_read _and_close.py} (63%) delete mode 100644 Chapter 8 - Working with Files/file_io.py delete mode 100644 Chapter 8 - Working with Files/open_with.py diff --git a/Chapter 8 - Working with Files/8_1_file_io.py b/Chapter 8 - Working with Files/8_1_file_io.py new file mode 100644 index 0000000..7d63aad --- /dev/null +++ b/Chapter 8 - Working with Files/8_1_file_io.py @@ -0,0 +1,46 @@ +# open a file that is in the same folder as this script +# default mode: read-only +handle = open("test.txt") +print(handle) +handle.close() + +# open a file by specifying its path +# you have to specify the path using raw string, r"path" +try: + handle = open(r"some path", "r") # explicit read only mode (raw_string, "r") +except IOError: + print("cannot open that") + + +# open the file in read-only binary mode +handle = open("test.txt", "rb") +print(handle) + + +# let's read it + +data = handle.read() +print(data) # b'This is a test file\nline 2\nline 3\nthis line intentionally left blank' +handle.close() + + +handle_text = open("test.txt", "r") +data = handle_text.readline() # read the first line +handle_text.close() +print(data) + +handle_text = open("test.txt", "r") +data_all = handle_text.readlines() # all the lines in a list +handle_text.close() +print(data_all) # ['This is a test file\n', 'line 2\n', 'line 3\n', 'this line intentionally left blank'] + + +''' +<_io.TextIOWrapper name='test.txt' mode='r' encoding='US-ASCII'> +cannot open that +<_io.BufferedReader name='test.txt'> +b'This is a test file\nline 2\nline 3\nthis line intentionally left blank' +This is a test file + +['This is a test file\n', 'line 2\n', 'line 3\n', 'this line intentionally left blank'] +''' \ No newline at end of file diff --git a/Chapter 8 - Working with Files/write_file.py b/Chapter 8 - Working with Files/8_2_write_file.py similarity index 54% rename from Chapter 8 - Working with Files/write_file.py rename to Chapter 8 - Working with Files/8_2_write_file.py index f410841..acddca7 100644 --- a/Chapter 8 - Working with Files/write_file.py +++ b/Chapter 8 - Working with Files/8_2_write_file.py @@ -1,3 +1,3 @@ handle = open("output.txt", "w") -handle.write("This is a test!") +handle.write("This is a f. test! yey") handle.close() \ No newline at end of file diff --git a/Chapter 8 - Working with Files/8_3_open_with.py b/Chapter 8 - Working with Files/8_3_open_with.py new file mode 100644 index 0000000..a99df25 --- /dev/null +++ b/Chapter 8 - Working with Files/8_3_open_with.py @@ -0,0 +1,15 @@ +# open and read the file using the with operator +# simplifying the reading and writing + +# with creates a CONTEXT MANAGER : +# automatically closes the file for you when you are done processing +with open("test.txt") as file_handler: + for line in file_handler: + print(len(line)) + print(line) +# no need to close +# you can do all the I/O ops as long as you are in the with block +# after the ops are done and you are out of the with block then the file handler closes. + + +# weird syntax diff --git a/Chapter 8 - Working with Files/catching_errors.py b/Chapter 8 - Working with Files/8_4_catching_errors.py similarity index 64% rename from Chapter 8 - Working with Files/catching_errors.py rename to Chapter 8 - Working with Files/8_4_catching_errors.py index b59d424..c2990da 100644 --- a/Chapter 8 - Working with Files/catching_errors.py +++ b/Chapter 8 - Working with Files/8_4_catching_errors.py @@ -6,12 +6,13 @@ except IOError: print("An IOError has occurred!") finally: - file_handler.close() + file_handler.close() # exactly : we need to take care of closing the handler anyway # catching errors when using the with operator +# no need to close the handler anyway, so we don't need the finally for that try: with open("test.txt") as file_handler: for line in file_handler: print(line) except IOError: - print("An IOError has occurred!" \ No newline at end of file + print("An IOError has occurred!") \ No newline at end of file diff --git a/Chapter 8 - Working with Files/open_and_close.py b/Chapter 8 - Working with Files/8_5_open_read _and_close.py similarity index 63% rename from Chapter 8 - Working with Files/open_and_close.py rename to Chapter 8 - Working with Files/8_5_open_read _and_close.py index 947b113..295f622 100644 --- a/Chapter 8 - Working with Files/open_and_close.py +++ b/Chapter 8 - Working with Files/8_5_open_read _and_close.py @@ -1,8 +1,11 @@ # open a file in read-only mode handle = open("test.txt", "r") -# read the data +# read the data with the handler data = handle.read() # print it out print(data) +print(type(data)) # str # close the file -handle.close() \ No newline at end of file +handle.close() + + diff --git a/Chapter 8 - Working with Files/file_io.py b/Chapter 8 - Working with Files/file_io.py deleted file mode 100644 index 4a0ac24..0000000 --- a/Chapter 8 - Working with Files/file_io.py +++ /dev/null @@ -1,8 +0,0 @@ -# open a file that is in the same folder as this script -handle = open("test.txt") - -# open a file by specifying its path -handle = open(r"C:\Users\mike\py101book\data\test.txt", "r") - -# open the file in read-only binary mode -handle = open("test.pdf", "rb") \ No newline at end of file diff --git a/Chapter 8 - Working with Files/open_with.py b/Chapter 8 - Working with Files/open_with.py deleted file mode 100644 index 2ea04a7..0000000 --- a/Chapter 8 - Working with Files/open_with.py +++ /dev/null @@ -1,4 +0,0 @@ -# open and read the file using the with operator -with open("test.txt") as file_handler: - for line in file_handler: - print(line) \ No newline at end of file diff --git a/Chapter 8 - Working with Files/read_in_chunks.py b/Chapter 8 - Working with Files/read_in_chunks.py index ee61380..d4e67f3 100644 --- a/Chapter 8 - Working with Files/read_in_chunks.py +++ b/Chapter 8 - Working with Files/read_in_chunks.py @@ -1,6 +1,14 @@ +# primitive way of reading in chunks handle = open("test.txt", "r") while True: - data = handle.read(1024) + data = handle.read(1024) # that's 1 Kb print(data) - if not data: - break \ No newline at end of file + if not data: # stop reading when there is no data, otherwise + break + +'''' +This is a test file +line 2 +line 3 +this line intentionally left blank +''' \ No newline at end of file diff --git a/Chapter 8 - Working with Files/read_line_by_line.py b/Chapter 8 - Working with Files/read_line_by_line.py index 9e3a79b..314f72a 100644 --- a/Chapter 8 - Working with Files/read_line_by_line.py +++ b/Chapter 8 - Working with Files/read_line_by_line.py @@ -1,4 +1,17 @@ handle = open("test.txt", "r") +# iterate over the handle, which is cool for line in handle: print(line) -handle.close() \ No newline at end of file +handle.close() + +''' +This is a test file + +line 2 + +line 3 + +this line intentionally left blank + +Process finished with exit code 0 +''' \ No newline at end of file From f490b4447f2535c545840d61e1ae1011ecc77a00 Mon Sep 17 00:00:00 2001 From: sebastian gherghesanu Date: Tue, 8 Jan 2019 19:10:09 +0200 Subject: [PATCH 12/18] chapter9: run & learn --- Chapter 9 - Imports/9_1_this.py | 27 +++++++++++++++++++++++++++ Chapter 9 - Imports/9_2_math.py | 17 +++++++++++++++++ Chapter 9 - Imports/readme.txt | 4 +++- 3 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 Chapter 9 - Imports/9_1_this.py create mode 100644 Chapter 9 - Imports/9_2_math.py diff --git a/Chapter 9 - Imports/9_1_this.py b/Chapter 9 - Imports/9_1_this.py new file mode 100644 index 0000000..4ba6d02 --- /dev/null +++ b/Chapter 9 - Imports/9_1_this.py @@ -0,0 +1,27 @@ +import this + +# run & learn + +''' +The Zen of Python, by Tim Peters + +Beautiful is better than ugly. +Explicit is better than implicit. +Simple is better than complex. +Complex is better than complicated. +Flat is better than nested. +Sparse is better than dense. +Readability counts. +Special cases aren't special enough to break the rules. +Although practicality beats purity. +Errors should never pass silently. +Unless explicitly silenced. +In the face of ambiguity, refuse the temptation to guess. +There should be one-- and preferably only one --obvious way to do it. +Although that way may not be obvious at first unless you're Dutch. +Now is better than never. +Although never is often better than *right* now. +If the implementation is hard to explain, it's a bad idea. +If the implementation is easy to explain, it may be a good idea. +Namespaces are one honking great idea -- let's do more of those! +''' \ No newline at end of file diff --git a/Chapter 9 - Imports/9_2_math.py b/Chapter 9 - Imports/9_2_math.py new file mode 100644 index 0000000..0286c9e --- /dev/null +++ b/Chapter 9 - Imports/9_2_math.py @@ -0,0 +1,17 @@ +#modules +import math + +print(math.sqrt(4)) +# we need to write also the library + + +# no need +from math import sqrt +print(sqrt(9)) + + +# BAD : shadowing: we change the function sqrt into a variable +sqrt = 9 +print(sqrt) + +# import what you need only and not pollute the namespace with all kind of names you don't know diff --git a/Chapter 9 - Imports/readme.txt b/Chapter 9 - Imports/readme.txt index 10768ea..3e86a6a 100644 --- a/Chapter 9 - Imports/readme.txt +++ b/Chapter 9 - Imports/readme.txt @@ -1 +1,3 @@ -This chapter was skipped because it just demonstrates different ways of importing modules. The examples in chapter 9 should be practiced in IDLE or a Python editor of your choice. \ No newline at end of file +This chapter was skipped because it just demonstrates different ways of importing modules. + The examples in chapter 9 should be practiced in IDLE or a Python editor of your choice. + From 6590c6806a37651d7c18921da68e3e09b8e2f0dd Mon Sep 17 00:00:00 2001 From: sebutz Date: Tue, 8 Jan 2019 21:12:32 +0200 Subject: [PATCH 13/18] chapter 10: run and --- .../10_1_simple_function.py | 8 +++++ Chapter 10 - Functions/10_2_stub.py | 6 ++++ Chapter 10 - Functions/10_3_add.py | 29 +++++++++++++++++++ .../{kw_func.py => 10_4_kw_func.py} | 3 +- .../10_5_args_and_kwargs.py | 15 ++++++++++ .../{kw_func2.py => 10_6_pkw_func2.py} | 7 +++-- .../{scope.py => 10_7_scope.py} | 8 ++--- Chapter 10 - Functions/add.py | 14 --------- Chapter 10 - Functions/args_and_kwargs.py | 5 ---- Chapter 10 - Functions/scope2.py | 10 +++---- Chapter 10 - Functions/simple_function.py | 3 -- Chapter 10 - Functions/stub.py | 2 -- 12 files changed, 73 insertions(+), 37 deletions(-) create mode 100644 Chapter 10 - Functions/10_1_simple_function.py create mode 100644 Chapter 10 - Functions/10_2_stub.py create mode 100644 Chapter 10 - Functions/10_3_add.py rename Chapter 10 - Functions/{kw_func.py => 10_4_kw_func.py} (84%) create mode 100644 Chapter 10 - Functions/10_5_args_and_kwargs.py rename Chapter 10 - Functions/{kw_func2.py => 10_6_pkw_func2.py} (62%) rename Chapter 10 - Functions/{scope.py => 10_7_scope.py} (61%) delete mode 100644 Chapter 10 - Functions/add.py delete mode 100644 Chapter 10 - Functions/args_and_kwargs.py delete mode 100644 Chapter 10 - Functions/simple_function.py delete mode 100644 Chapter 10 - Functions/stub.py diff --git a/Chapter 10 - Functions/10_1_simple_function.py b/Chapter 10 - Functions/10_1_simple_function.py new file mode 100644 index 0000000..b5318e4 --- /dev/null +++ b/Chapter 10 - Functions/10_1_simple_function.py @@ -0,0 +1,8 @@ +# create a simple function +# structure you create +def a_function(): + print("You just created a function!") + + +# call the function +a_function() diff --git a/Chapter 10 - Functions/10_2_stub.py b/Chapter 10 - Functions/10_2_stub.py new file mode 100644 index 0000000..f39a392 --- /dev/null +++ b/Chapter 10 - Functions/10_2_stub.py @@ -0,0 +1,6 @@ +# a stub +# what's with the pass? + +def empty_function(): + pass # null operation: nothing happens + diff --git a/Chapter 10 - Functions/10_3_add.py b/Chapter 10 - Functions/10_3_add.py new file mode 100644 index 0000000..2100560 --- /dev/null +++ b/Chapter 10 - Functions/10_3_add.py @@ -0,0 +1,29 @@ +# adding arguments +def add(a, b): + return a + b + +# call the function with arguments +add(1, 2) + +# call the function with the wrong number of arguments +try: + add(1) # causes a TypeError +except TypeError: + print("wrong nr. of argument ") + + +# call the function with keyword arguments +# named arguments +add(a=2, b=3) + + +# assign the result to a variable +total = add(b=4, a=5) +print(total) + +# deefault arguments +def add2(a = 2, b = 3): + return a + b + +print(add2()) +print(add2(10)) diff --git a/Chapter 10 - Functions/kw_func.py b/Chapter 10 - Functions/10_4_kw_func.py similarity index 84% rename from Chapter 10 - Functions/kw_func.py rename to Chapter 10 - Functions/10_4_kw_func.py index ca09806..1995640 100644 --- a/Chapter 10 - Functions/kw_func.py +++ b/Chapter 10 - Functions/10_4_kw_func.py @@ -1,4 +1,5 @@ # create a function with defaults +# default arguments def keyword_function(a=1, b=2): return a+b @@ -6,4 +7,4 @@ def keyword_function(a=1, b=2): keyword_function(b=4, a=5) # call the function without arguments (i.e. use the defaults) -keyword_function() \ No newline at end of file +keyword_function() diff --git a/Chapter 10 - Functions/10_5_args_and_kwargs.py b/Chapter 10 - Functions/10_5_args_and_kwargs.py new file mode 100644 index 0000000..d8d115f --- /dev/null +++ b/Chapter 10 - Functions/10_5_args_and_kwargs.py @@ -0,0 +1,15 @@ +# infinite number of arguments +# infinite number of keyword arguments +def many(*args, **kwargs): + print(args) # list + print(kwargs) # dictionary + +res = many(1, 2, 3, name="Mike", job="programmer") +print("result:", res) + +''' +(1, 2, 3) +{'name': 'Mike', 'job': 'programmer'} +result: None + +''' diff --git a/Chapter 10 - Functions/kw_func2.py b/Chapter 10 - Functions/10_6_pkw_func2.py similarity index 62% rename from Chapter 10 - Functions/kw_func2.py rename to Chapter 10 - Functions/10_6_pkw_func2.py index ad271b0..a5b177f 100644 --- a/Chapter 10 - Functions/kw_func2.py +++ b/Chapter 10 - Functions/10_6_pkw_func2.py @@ -2,7 +2,8 @@ def mixed_function(a, b=2, c=3): return a+b+c # call the function with one argument and 2 keyword arguments -mixed_function(1, b=4, c=5) - +res1 = mixed_function(1, b=4, c=5) +print(res1) # call the argument with just the required argument -mixed_function(1) \ No newline at end of file +res2 = mixed_function(1) # b =2, c = 3 +print(res2) diff --git a/Chapter 10 - Functions/scope.py b/Chapter 10 - Functions/10_7_scope.py similarity index 61% rename from Chapter 10 - Functions/scope.py rename to Chapter 10 - Functions/10_7_scope.py index 546d8ed..c320749 100644 --- a/Chapter 10 - Functions/scope.py +++ b/Chapter 10 - Functions/10_7_scope.py @@ -4,11 +4,11 @@ def function_a(): a = 1 b = 2 - return a+b + return a + b def function_b(): c = 3 - return a+c - + # return a + c # NameError , a is not defined + return c print( function_a() ) -print( function_b() ) \ No newline at end of file +print( function_b() ) diff --git a/Chapter 10 - Functions/add.py b/Chapter 10 - Functions/add.py deleted file mode 100644 index c273f7b..0000000 --- a/Chapter 10 - Functions/add.py +++ /dev/null @@ -1,14 +0,0 @@ -def add(a, b): - return a + b - -# call the function with arguments -add(1, 2) - -# call the function with the wrong number of arguments -add(1) # causes a TypeError - -# call the function with keyword arguments -add(a=2, b=3) - -# assign the result to a variable -total = add(b=4, a=5) \ No newline at end of file diff --git a/Chapter 10 - Functions/args_and_kwargs.py b/Chapter 10 - Functions/args_and_kwargs.py deleted file mode 100644 index c90a85e..0000000 --- a/Chapter 10 - Functions/args_and_kwargs.py +++ /dev/null @@ -1,5 +0,0 @@ -def many(*args, **kwargs): - print(args) - print(kwargs) - -many(1, 2, 3, name="Mike", job="programmer") \ No newline at end of file diff --git a/Chapter 10 - Functions/scope2.py b/Chapter 10 - Functions/scope2.py index 91abbe8..0d1de0d 100644 --- a/Chapter 10 - Functions/scope2.py +++ b/Chapter 10 - Functions/scope2.py @@ -1,15 +1,15 @@ # this script demonstrates how to use a global -# to fic the scope issue in scope.py +# to fic the scope issue in 10_7_scope.py def function_a(): - global a + global a # here a = 1 b = 2 - return a+b + return a + b def function_b(): c = 3 - return a+c + return a + c print(function_a()) -print(function_b()) \ No newline at end of file +print(function_b()) diff --git a/Chapter 10 - Functions/simple_function.py b/Chapter 10 - Functions/simple_function.py deleted file mode 100644 index d5914b1..0000000 --- a/Chapter 10 - Functions/simple_function.py +++ /dev/null @@ -1,3 +0,0 @@ -# create a simple function -def a_function(): - print("You just created a function!") \ No newline at end of file diff --git a/Chapter 10 - Functions/stub.py b/Chapter 10 - Functions/stub.py deleted file mode 100644 index 61a6746..0000000 --- a/Chapter 10 - Functions/stub.py +++ /dev/null @@ -1,2 +0,0 @@ -def empty_function(): - pass \ No newline at end of file From e2457d3bf5b8224611a9e00ba09782b0d67a61fd Mon Sep 17 00:00:00 2001 From: sebutz Date: Tue, 8 Jan 2019 21:36:31 +0200 Subject: [PATCH 14/18] chapter 10: run and learn --- Chapter 10 - Functions/{scope2.py => 10_7_3_fixing_scope2.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Chapter 10 - Functions/{scope2.py => 10_7_3_fixing_scope2.py} (100%) diff --git a/Chapter 10 - Functions/scope2.py b/Chapter 10 - Functions/10_7_3_fixing_scope2.py similarity index 100% rename from Chapter 10 - Functions/scope2.py rename to Chapter 10 - Functions/10_7_3_fixing_scope2.py From 5589a0057c8fb26abe149c37494c5caf18a0b9ca Mon Sep 17 00:00:00 2001 From: "freemitive@gmx.com" Date: Wed, 9 Jan 2019 10:43:51 +0200 Subject: [PATCH 15/18] chapter10: run & learn --- ..._class_2.x.py => 11_1_simple_class_2.x.py} | 3 +- ..._class_3.x.py => 11_2_simple_class_3.x.py} | 0 .../{vehicle.py => 11_3_vehicle.py} | 2 +- .../{vehicle2.py => 11_4_vehicle2.py} | 0 Chapter 11 - Classes/11_5_car_subclass.py | 46 +++++++++++++++++++ Chapter 11 - Classes/car_subclass.py | 19 -------- 6 files changed, 49 insertions(+), 21 deletions(-) rename Chapter 11 - Classes/{simple_class_2.x.py => 11_1_simple_class_2.x.py} (86%) rename Chapter 11 - Classes/{simple_class_3.x.py => 11_2_simple_class_3.x.py} (100%) rename Chapter 11 - Classes/{vehicle.py => 11_3_vehicle.py} (91%) rename Chapter 11 - Classes/{vehicle2.py => 11_4_vehicle2.py} (100%) create mode 100644 Chapter 11 - Classes/11_5_car_subclass.py delete mode 100644 Chapter 11 - Classes/car_subclass.py diff --git a/Chapter 11 - Classes/simple_class_2.x.py b/Chapter 11 - Classes/11_1_simple_class_2.x.py similarity index 86% rename from Chapter 11 - Classes/simple_class_2.x.py rename to Chapter 11 - Classes/11_1_simple_class_2.x.py index fe4eef4..795b750 100644 --- a/Chapter 11 - Classes/simple_class_2.x.py +++ b/Chapter 11 - Classes/11_1_simple_class_2.x.py @@ -1,7 +1,8 @@ # Python 2.x syntax class Vehicle(object): """docstring""" - + + # constructor def __init__(self): """Constructor""" pass \ No newline at end of file diff --git a/Chapter 11 - Classes/simple_class_3.x.py b/Chapter 11 - Classes/11_2_simple_class_3.x.py similarity index 100% rename from Chapter 11 - Classes/simple_class_3.x.py rename to Chapter 11 - Classes/11_2_simple_class_3.x.py diff --git a/Chapter 11 - Classes/vehicle.py b/Chapter 11 - Classes/11_3_vehicle.py similarity index 91% rename from Chapter 11 - Classes/vehicle.py rename to Chapter 11 - Classes/11_3_vehicle.py index e06da5b..4a5abc9 100644 --- a/Chapter 11 - Classes/vehicle.py +++ b/Chapter 11 - Classes/11_3_vehicle.py @@ -22,7 +22,7 @@ def drive(self): """ return "I'm driving!" - +# what code to run if this file is run as standalone if __name__ == "__main__": car = Vehicle("blue", 5, 4) print(car.color) diff --git a/Chapter 11 - Classes/vehicle2.py b/Chapter 11 - Classes/11_4_vehicle2.py similarity index 100% rename from Chapter 11 - Classes/vehicle2.py rename to Chapter 11 - Classes/11_4_vehicle2.py diff --git a/Chapter 11 - Classes/11_5_car_subclass.py b/Chapter 11 - Classes/11_5_car_subclass.py new file mode 100644 index 0000000..4056e51 --- /dev/null +++ b/Chapter 11 - Classes/11_5_car_subclass.py @@ -0,0 +1,46 @@ +# we have to define first the referenced class(the parent class) +class Vehicle(object): + """docstring""" + + def __init__(self, color, doors, tires, vtype): + """Constructor""" + self.color = color + self.doors = doors + self.tires = tires + self.vtype = vtype + + def brake(self): + """ + Stop the car + """ + return "%s braking" % self.vtype + + def drive(self): + """ + Drive the car + """ + return "I'm driving a %s %s!" % (self.color, self.vtype) + + + + +class Car(Vehicle): + """ + The Car class + """ + + + def brake(self): + """ + Override brake method + """ + return "The car class is breaking slowly!" + + + +if __name__ == "__main__": + car = Car("yellow", 2, 4, "car") + print(car.brake()) + 'The car class is breaking slowly!' + print(car.drive()) + "I'm driving a yellow car!" \ No newline at end of file diff --git a/Chapter 11 - Classes/car_subclass.py b/Chapter 11 - Classes/car_subclass.py deleted file mode 100644 index 24ed722..0000000 --- a/Chapter 11 - Classes/car_subclass.py +++ /dev/null @@ -1,19 +0,0 @@ -class Car(Vehicle): - """ - The Car class - """ - - - def brake(self): - """ - Override brake method - """ - return "The car class is breaking slowly!" - - -if __name__ == "__main__": - car = Car("yellow", 2, 4, "car") - car.brake() - 'The car class is breaking slowly!' - car.drive() - "I'm driving a yellow car!" \ No newline at end of file From 0fa2c6eb03140649000a7245984402c81f0ac798 Mon Sep 17 00:00:00 2001 From: "freemitive@gmx.com" Date: Wed, 9 Jan 2019 10:52:36 +0200 Subject: [PATCH 16/18] chapter11: run & learn --- .../12_1_introspection.py | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Chapter 12 - Introspection/12_1_introspection.py diff --git a/Chapter 12 - Introspection/12_1_introspection.py b/Chapter 12 - Introspection/12_1_introspection.py new file mode 100644 index 0000000..eedcf47 --- /dev/null +++ b/Chapter 12 - Introspection/12_1_introspection.py @@ -0,0 +1,32 @@ + +x = "test" +print(type(x)) + +y = 7 +print(type(y)) + +z = None +print(type(z)) + + +''' + + + +''' + +# dir : what arguments can be passed to the object +# what can you do with that object +print(dir("test")) + +# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] + + +#works for a module also +import sys + +print(dir(sys)) + +# ['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe', '_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'set_coroutine_wrapper', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions'] + +print(help(sys.api_version)) \ No newline at end of file From da972ba51da06a73484a7a4f044159b22770c19a Mon Sep 17 00:00:00 2001 From: "freemitive@gmx.com" Date: Wed, 9 Jan 2019 11:41:10 +0200 Subject: [PATCH 17/18] chapter13: run & learn --- .../{csv_reader.py => 13_1_csv_reader.py} | 5 +-- Chapter 13 - csv/13_2_csv_DictReader.py | 35 +++++++++++++++++++ .../{csv_writer.py => 13_3_csv_writer.py} | 15 +++++--- ...v_dictwriter.py => 13_4_csv_dictwriter.py} | 22 ++++++++---- Chapter 13 - csv/csv_reader2.py | 14 -------- 5 files changed, 65 insertions(+), 26 deletions(-) rename Chapter 13 - csv/{csv_reader.py => 13_1_csv_reader.py} (53%) create mode 100644 Chapter 13 - csv/13_2_csv_DictReader.py rename Chapter 13 - csv/{csv_writer.py => 13_3_csv_writer.py} (54%) rename Chapter 13 - csv/{csv_dictwriter.py => 13_4_csv_dictwriter.py} (59%) delete mode 100644 Chapter 13 - csv/csv_reader2.py diff --git a/Chapter 13 - csv/csv_reader.py b/Chapter 13 - csv/13_1_csv_reader.py similarity index 53% rename from Chapter 13 - csv/csv_reader.py rename to Chapter 13 - csv/13_1_csv_reader.py index 1fa9813..3fc90f0 100644 --- a/Chapter 13 - csv/csv_reader.py +++ b/Chapter 13 - csv/13_1_csv_reader.py @@ -4,9 +4,10 @@ def csv_reader(file_obj): """ Read a csv file """ - reader = csv.reader(file_obj) + reader = csv.reader(file_obj) # get a reader object from the file object + # the reader object allows iteration for row in reader: - print(" ".join(row)) + print(" ".join(row)) # each row is a list of words (commas are not taken into consideration) if __name__ == "__main__": diff --git a/Chapter 13 - csv/13_2_csv_DictReader.py b/Chapter 13 - csv/13_2_csv_DictReader.py new file mode 100644 index 0000000..ca46868 --- /dev/null +++ b/Chapter 13 - csv/13_2_csv_DictReader.py @@ -0,0 +1,35 @@ +import csv + +''' +first_name,last_name,address,city,state,zip_code +Tyrese,Hirthe,1404 Turner Ville,Strackeport,NY,19106-8813 +Jules,Dicki,2410 Estella Cape Suite 061,Lake Nickolasville,ME,00621-7435 +Dedric,Medhurst,6912 Dayna Shoal,Stiedemannberg,SC,43259-2273 +''' + +# the first line has the columns name aka the keys +def csv_dict_reader(file_obj): + """ + Read a CSV file using csv.DictReader + """ + reader = csv.DictReader(file_obj, delimiter=',') # you can give the delimiter + for line in reader: + print("the line is:", line) + print(line["first_name"]), + print(line["last_name"]) + +if __name__ == "__main__": + with open("data.csv") as f_obj: + csv_dict_reader(f_obj) + +''' +the line is: {'state': 'NY', 'zip_code': '19106-8813', 'city': 'Strackeport', 'last_name': 'Hirthe', 'address': '1404 Turner Ville', 'first_name': 'Tyrese'} +Tyrese +Hirthe +the line is: {'state': 'ME', 'zip_code': '00621-7435', 'city': 'Lake Nickolasville', 'last_name': 'Dicki', 'address': '2410 Estella Cape Suite 061', 'first_name': 'Jules'} +Jules +Dicki +the line is: {'state': 'SC', 'zip_code': '43259-2273', 'city': 'Stiedemannberg', 'last_name': 'Medhurst', 'address': '6912 Dayna Shoal', 'first_name': 'Dedric'} +Dedric +Medhurst +''' \ No newline at end of file diff --git a/Chapter 13 - csv/csv_writer.py b/Chapter 13 - csv/13_3_csv_writer.py similarity index 54% rename from Chapter 13 - csv/csv_writer.py rename to Chapter 13 - csv/13_3_csv_writer.py index af0baa5..acb0a00 100644 --- a/Chapter 13 - csv/csv_writer.py +++ b/Chapter 13 - csv/13_3_csv_writer.py @@ -4,10 +4,10 @@ def csv_writer(data, path): """ Write data to a CSV file path """ - with open(path, "w", newline='') as csv_file: - writer = csv.writer(csv_file, delimiter=',') + with open(path, "w", newline='') as csv_file: # open for writing + writer = csv.writer(csv_file, delimiter=',') # delimiter for line in data: - writer.writerow(line) + writer.writerow(line) # write row after row if __name__ == "__main__": data = ["first_name,last_name,city".split(","), @@ -16,4 +16,11 @@ def csv_writer(data, path): "Dedric,Medhurst,Stiedemannberg".split(",") ] path = "output.csv" - csv_writer(data, path) \ No newline at end of file + csv_writer(data, path) + +''' +first_name,last_name,city +Tyrese,Hirthe,Strackeport +Jules,Dicki,Lake Nickolasville +Dedric,Medhurst,Stiedemannberg +''' \ No newline at end of file diff --git a/Chapter 13 - csv/csv_dictwriter.py b/Chapter 13 - csv/13_4_csv_dictwriter.py similarity index 59% rename from Chapter 13 - csv/csv_dictwriter.py rename to Chapter 13 - csv/13_4_csv_dictwriter.py index a5547fe..c158c28 100644 --- a/Chapter 13 - csv/csv_dictwriter.py +++ b/Chapter 13 - csv/13_4_csv_dictwriter.py @@ -17,10 +17,20 @@ def csv_dict_writer(path, fieldnames, data): "Dedric,Medhurst,Stiedemannberg".split(",") ] my_list = [] - fieldnames = data[0] - for values in data[1:]: - inner_dict = dict(zip(fieldnames, values)) - my_list.append(inner_dict) - + fieldnames = data[0] # first the column names, aka keys + for values in data[1:]: # from 1 to the end + inner_dict = dict(zip(fieldnames, values)) # make a dict + my_list.append(inner_dict) # data is a list of maps + + print("final list",my_list) path = "dict_output.csv" - csv_dict_writer(path, fieldnames, my_list) \ No newline at end of file + csv_dict_writer(path, fieldnames, my_list) + + +''' +first_name,last_name,city +Tyrese,Hirthe,Strackeport +Jules,Dicki,Lake Nickolasville +Dedric,Medhurst,Stiedemannberg + +''' \ No newline at end of file diff --git a/Chapter 13 - csv/csv_reader2.py b/Chapter 13 - csv/csv_reader2.py deleted file mode 100644 index 9883a1c..0000000 --- a/Chapter 13 - csv/csv_reader2.py +++ /dev/null @@ -1,14 +0,0 @@ -import csv - -def csv_dict_reader(file_obj): - """ - Read a CSV file using csv.DictReader - """ - reader = csv.DictReader(file_obj, delimiter=',') - for line in reader: - print(line["first_name"]), - print(line["last_name"]) - -if __name__ == "__main__": - with open("data.csv") as f_obj: - csv_dict_reader(f_obj) \ No newline at end of file From 039c27dcd8be5af34898c1d0ab686796349b44a9 Mon Sep 17 00:00:00 2001 From: "freemitive@gmx.com" Date: Wed, 9 Jan 2019 11:41:46 +0200 Subject: [PATCH 18/18] chapter6: run & learn --- Chapter 6 - Comprehensions/comprehensions.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Chapter 6 - Comprehensions/comprehensions.py b/Chapter 6 - Comprehensions/comprehensions.py index c0b973b..44bf2d0 100644 --- a/Chapter 6 - Comprehensions/comprehensions.py +++ b/Chapter 6 - Comprehensions/comprehensions.py @@ -37,4 +37,6 @@ my_list = [1, 2, 2, 3, 4, 5, 5, 7, 8] my_set = {x for x in my_list} # set print(my_set) -print(type(my_set)) \ No newline at end of file +print(type(my_set)) + +