├── unit2_Ex2.1.2.py ├── unit2_ex_2.3.2.py ├── unit3_ex3.1.1.py ├── unit7_ex7.1.1.py ├── unit5_ex5.3.2.py ├── unit9_ex9.2.1.py ├── unit7_ex7.1.2.py ├── unit3_ex3.3.3.py ├── unit6_ex6.1.1.py ├── unit7_ex7.2.3.py ├── unit5_ex5.3.1.py ├── unit2_ex2.3.1.py ├── unit6_ex6.2.2.py ├── unit3_ex3.3.1.py ├── unit5_ex5.3.3.py ├── unit9_ex8.1.1.py ├── unit2-Ex2.1.1.py ├── unit3_ex3.4.1.py ├── unit6_ex6.2.1.py ├── unit7_ex7.1.3.py ├── unit1-Ex1.3.1.py ├── unit3_ex3.4.2.py ├── unit5_ex5.3.4.py ├── unit6_ex6.1.2.py ├── unit2_ex2.4.1.py ├── unit8_ex8.3.1.py ├── unit6_ex6.3.2.py ├── unit4_ex4.2.2.py ├── unit8_ex8.2.1.py ├── unit5_ex5.1.1.py ├── unit3_ex3.3.2.py ├── unit3_ex3.2.1.py ├── unit4_ex4.2.4.py ├── unit4_ex4.4.1.py ├── unit5_ex5.2.1.py ├── unit9_ex9.1.1.py ├── unit1_ex1.3.2.py ├── unit6_ex6.2.4.py ├── unit2_ex2.2.1.py ├── unit4_ex4.2.3.py ├── unit7_ex7.2.7.py ├── unit3_ex3.4.3.py ├── unit7_ex7.2.2.py ├── unit6_ex6.2.3.py ├── unit6_ex6.3.1.py ├── unit7_ex7.2.5.py ├── unit7_ex7.2.4.py ├── unit8_ex8.3.3.py ├── unit7_ex7.2.1.py ├── unit9_ex9.2.2.py ├── unit7_ex7.1.4.py ├── unit3_ex3.4.4.py ├── unit5_ex5.3.5.py ├── unit5_ex5.3.7.py ├── unit8_ex8.2.3.py ├── unit8_ex8.2.2.py ├── unit4_ex4.2.1.py ├── unit2_ex_2.3.3.py ├── unit5_Ex5.3.6.py ├── unit8_ex8.3.4.py ├── hangmanproject_unit3.py ├── hangmanproject_unit4.py ├── unit9_ex9.2.3.py ├── hangmanproject_unit2.py ├── hangmanproject_unit1.py ├── hangmanproject_unit5.py ├── hangmanproject_unit8.py ├── hangmanproject_unit9.py ├── unit8_ex8.3.2.py ├── unit9_ex9.1.2.py ├── README.md ├── unit9_ex9.3.1.py ├── unit9_ex9.3.2.py ├── hangmanproject_unit6.py ├── hangmanproject_unit7.py ├── unit7_ex7.2.6.py ├── hangmanproject_unit6.1.py └── hangman_final_project.py /unit2_Ex2.1.2.py: -------------------------------------------------------------------------------- 1 | # Look at the following code snippet. What will be printed at the end of the run? 2 | a = 10 3 | b = a 4 | a = 4 5 | print(a, b) 6 | # Answer: 4 10 7 | -------------------------------------------------------------------------------- /unit2_ex_2.3.2.py: -------------------------------------------------------------------------------- 1 | # what will be the output? 2 | a, b = "q" not in "snow", type(-200) == type(200) 3 | 4 | # 1: 5 | print(a == b) 6 | # Answer: True 7 | 8 | # 2: 9 | print(a != b) 10 | # Answer: False 11 | 12 | -------------------------------------------------------------------------------- /unit3_ex3.1.1.py: -------------------------------------------------------------------------------- 1 | # exercise 3.1.1 from unit 3 2 | # What will be the result of the following expression? 3 | output = "He" + "l" * 2 + "o" + " Python " + str(7.2 / 2) + "." + str(3) 4 | print(output) 5 | # Answer: 'Hello Python 3.6.3' 6 | -------------------------------------------------------------------------------- /unit7_ex7.1.1.py: -------------------------------------------------------------------------------- 1 | # exercise 7.1.1 from unit 7 2 | # Here is a piece of code that includes a while loop. What output is obtained when running the loop? 3 | 4 | i = 1 5 | while i < 3: 6 | print('wow') 7 | i += 1 8 | 9 | # Answer: wow and next line wow 10 | -------------------------------------------------------------------------------- /unit5_ex5.3.2.py: -------------------------------------------------------------------------------- 1 | # exercise 5.3.2 from unit 5 2 | 3 | # Here are several definitions of functions, mark all the functions that have a valid definition: 4 | 5 | # Answer 6 | 7 | def square_equation(a=1, b=0, c=0): 8 | 9 | def square_equation(a, b=0, c=0): 10 | 11 | -------------------------------------------------------------------------------- /unit9_ex9.2.1.py: -------------------------------------------------------------------------------- 1 | # exercise 9.2.1 from unit 9 2 | ''' 3 | we have empty file called empty.txt 4 | and we need to tell what will be print 5 | 6 | ''' 7 | 8 | with open("empty.txt", "w") as input_file: 9 | input_file.write("So, call me mabye?") 10 | print(input_file.read()) 11 | 12 | # Answer: error io.UnsupportedOperation 13 | -------------------------------------------------------------------------------- /unit7_ex7.1.2.py: -------------------------------------------------------------------------------- 1 | # exercise 7.1.2 from unit 7 2 | ''' 3 | Here is a piece of code that includes a while loop. What output is obtained when running the loop? 4 | 5 | Guidelines 6 | It is recommended to use a tracking table. 7 | ''' 8 | 9 | x = 3 10 | i = 0 11 | while (i < 3): 12 | x += 1 13 | i += 1 14 | print(x) 15 | 16 | # Answer: 6 17 | -------------------------------------------------------------------------------- /unit3_ex3.3.3.py: -------------------------------------------------------------------------------- 1 | # exercise 3.3.3 from unit 3 2 | ''' 3 | You have to decipher a hidden string. All you got was a code string and a small note with a clue. 4 | 5 | The cipher string: 6 | ''' 7 | encrypted_message = "!XgXnXiXcXiXlXsX XnXoXhXtXyXpX XgXnXiXnXrXaXeXlX XmXaX XI" 8 | 9 | print(encrypted_message[56:0:-2]) 10 | 11 | # Answer: I am learning python slicing 12 | -------------------------------------------------------------------------------- /unit6_ex6.1.1.py: -------------------------------------------------------------------------------- 1 | # exercise 6.1.1 from unit 6 2 | 3 | ''' 4 | Choose an appropriate output for each of the code sections. 5 | ''' 6 | 7 | # 1 8 | 9 | first_list = [[13, 16], [13, 7], [5, 12], [17, 6]] 10 | print(first_list[2][1] % first_list[1][1]) 11 | 12 | # Answer: 5 13 | 14 | # 2 15 | 16 | second_list = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] 17 | print(second_list[1][0][1]) 18 | 19 | # Answer: 6 20 | -------------------------------------------------------------------------------- /unit7_ex7.2.3.py: -------------------------------------------------------------------------------- 1 | # exercise 7.2.3 from unit 7 2 | ''' 3 | Here is a piece of code, but it is missing the arguments that are passed to the range function: 4 | 5 | for num in range(___, ___, ___): 6 | print(number) 7 | Mark all the options where the values (start, stop, step) will give the following output: 8 | 9 | 0 10 | -3 11 | -6 12 | -9 13 | ''' 14 | 15 | # Answer: 16 | # C: (0, -10, -3) 17 | # D: (0, -12, -3) 18 | -------------------------------------------------------------------------------- /unit5_ex5.3.1.py: -------------------------------------------------------------------------------- 1 | # exercise 5.3.1 from unit 5 2 | # in fron of you there is the method remainder 3 | 4 | def remainder(base, divide_by=2, show_greeting=True): 5 | if show_greeting: 6 | print("Welcome to my function") 7 | print(base % divide_by) 8 | 9 | # tell which of the calss will print the following output: 10 | # Welcome to my function 11 | # 1 12 | # Answer: 13 | remainder(9, 8, True) 14 | 15 | remainder(9) 16 | -------------------------------------------------------------------------------- /unit2_ex2.3.1.py: -------------------------------------------------------------------------------- 1 | # In the program about the legend "The Ugly Duckling" we defined the following variables: 2 | fairy_tale = "The Ugly Duckling" 3 | swan_height = 90.7 4 | eggs_num = 4 5 | # What will be the output when you run the following lines of code? 6 | 7 | # 1: 8 | int(swan_height) 9 | # Answer: 90 10 | 11 | # 2: 12 | # int(fairy_tale) 13 | # Answer: error message 14 | 15 | # 3: 16 | surprise = bool(eggs_num) 17 | str(surprise) 18 | # Answer: 'True' 19 | 20 | -------------------------------------------------------------------------------- /unit6_ex6.2.2.py: -------------------------------------------------------------------------------- 1 | # exersice 6.2.2 from unit 6 2 | 3 | ''' 4 | given the list 5 | programming_languages = ['Python', 'Perl', 'R', 'Ruby'] 6 | 7 | which of the lines of code his output will be 'R' 8 | ''' 9 | 10 | # Answer: 11 | print(programming_lanquages[2][0]) 12 | print(programming_languages[3][0]) 13 | print(programming_languages[-2][0]) 14 | print(programming_languages[-1][-4]) 15 | print(programming_languages[2]) 16 | print(programming_languages[-2]) 17 | 18 | -------------------------------------------------------------------------------- /unit3_ex3.3.1.py: -------------------------------------------------------------------------------- 1 | # exercise 3.3.1 from unit 3 2 | 3 | # Given the following string: 4 | numbers = "123456789" 5 | 6 | ''' 7 | What will be the output of the following commands (make sure the output is exact)? 8 | 9 | Guidelines 10 | Complete the output in the text boxes on the right. 11 | Ensure accurate output (including quotation marks). 12 | ''' 13 | 14 | # 1: 15 | print(numbers[0:10:1]) 16 | # Answer: '123456789' 17 | 18 | # 2: 19 | print(numbers[3:6:3]) 20 | # Answer: '4' 21 | 22 | # 3: 23 | print(numbers[-1:-1:0]) 24 | # Answer: error 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /unit5_ex5.3.3.py: -------------------------------------------------------------------------------- 1 | # exercise 5.3.3 from unit 5 2 | 3 | # Here is a function called show_date 4 | def show_date(day, month, year=17): 5 | print(day, "/", month, "/", year) 6 | 7 | # Choose the output that is obtained for each of the following calls to the function 8 | 9 | # 1 10 | 11 | show_date(day=15, month=12, year=17) 12 | 13 | # output: 15/12/17 14 | 15 | # 2 16 | 17 | show_date(month=15, day=12) 18 | 19 | # output: 12/15/17 20 | 21 | # 3 22 | 23 | show_date(17, 12) 24 | 25 | # output: 17/12/17 26 | 27 | # 4 28 | 29 | show_date(15, year=12) 30 | 31 | # output: TypeError 32 | -------------------------------------------------------------------------------- /unit9_ex8.1.1.py: -------------------------------------------------------------------------------- 1 | # exersice 8.1.1 from unit 8 2 | ''' 3 | Here are four pieces of code. Choose the output obtained by running each of the code segments. 4 | ''' 5 | 6 | # 1: 7 | tuple_one = (1, 2, 3, 4 ) 8 | tuple_one[1:-1] 9 | 10 | # Answer: (2,3) 11 | 12 | # 2: 13 | tuple_two = (2, 5, 8, 3, 6, 9) 14 | for i in range(0, len(tuple_two), 3): 15 | print(tuple_two[i]) 16 | 17 | # Answer: 2 and after 3 18 | 19 | # 3: 20 | tuple_three = (2, 1, 3) 21 | tuple_three.sort() 22 | 23 | # Answer: error 24 | 25 | # 4: 26 | tuple_four = (4, 2, 3) 27 | sorted(tuple_four) 28 | 29 | # Answer: [2, 3, 4] 30 | -------------------------------------------------------------------------------- /unit2-Ex2.1.1.py: -------------------------------------------------------------------------------- 1 | # Choose the type of each expression. 2 | # author - lirom mizrahi 3 | 4 | # 1: 5 | # Expression: 7 6 | type(7) 7 | # Answer: int 8 | 9 | # 2: 10 | # Expression: "37" 11 | type("37") 12 | # Answer: str 13 | 14 | # 3: 15 | # Expression: 37.00 16 | type(37.00) 17 | # Answer: float 18 | 19 | # 4: 20 | # Expression: '34.56' 21 | type('34.56') 22 | # Answer: str 23 | 24 | # 5: 25 | # Expression: 56.789 26 | type(56.789) 27 | # Answer: float 28 | 29 | # 6: 30 | # Expression: "tfs56" 31 | type("tfs56") 32 | # Answer: str 33 | 34 | # 7: 35 | # Expression: 3.7 36 | type(3.7) 37 | # Answer: float 38 | 39 | -------------------------------------------------------------------------------- /unit3_ex3.4.1.py: -------------------------------------------------------------------------------- 1 | # exercise 3.4.1 from unit 3 2 | ''' 3 | The confused astronaut defined a string called word, but it was deleted 4 | for him. He wrote several lines of code trying to recover it, can you 5 | find out what the original string is given the following output? 6 | 7 | >>> 'e' not in word 8 | False 9 | >>> word.isspace() 10 | False 11 | >>> word.count('p') 12 | 2 13 | >>> word.find('sh') 14 | 5 15 | >>> word.endswith('e') 16 | False 17 | >>> len(word) 18 | 9 19 | >>> word[-2::-4] 20 | ic 21 | >>> word.startswith('spa') 22 | True 23 | 24 | ''' 25 | 26 | # Answer: spaceship 27 | -------------------------------------------------------------------------------- /unit6_ex6.2.1.py: -------------------------------------------------------------------------------- 1 | # exercise 6.2.1 from unit 6 2 | # there is 4 list 3 | 4 | list1 = [1, 2, 3, 4] 5 | list2 = [5,6,7] 6 | list3 = list1 + list2 7 | list4 = [list1 + list2] 8 | 9 | # choose the Right output for each line of code 10 | 11 | # 1 12 | 13 | print(len(list3)) 14 | 15 | # Answer: 7 16 | 17 | # 2 18 | 19 | print((len(list4) 20 | 21 | # Answer: 1 22 | 23 | # 3 24 | 25 | print(list1[2]+list3[4]) 26 | 27 | # Answer: 8 28 | 29 | # 4 30 | 31 | print(list4[0][3]) 32 | 33 | # Answer: 4 34 | 35 | # 5 36 | 37 | print(len(list2 * list1[1])) 38 | 39 | # Answer: 6 40 | 41 | -------------------------------------------------------------------------------- /unit7_ex7.1.3.py: -------------------------------------------------------------------------------- 1 | # exercise 7.1.3 from unit 7 2 | ''' 3 | Here are two pieces of code that include a while loop. Match each loop with the output obtained when it runs. 4 | 5 | Choose the output obtained by running each of the loops. 6 | 7 | Guidelines 8 | 9 | It is recommended to use tracking tables. 10 | ''' 11 | 12 | # 1 13 | 14 | i = 11 15 | while i > 0: 16 | i -=1 17 | if i == 5: 18 | break 19 | print(i) 20 | 21 | # Answer: 10 next line 9 than 8 7 6 22 | 23 | # 2 24 | 25 | i = 11 26 | while i > 0: 27 | i -=1 28 | if i == 5: 29 | continue 30 | print(i) 31 | 32 | # Answer: 10 next line 9 than 8 7 6 4 3 2 1 0 33 | -------------------------------------------------------------------------------- /unit1-Ex1.3.1.py: -------------------------------------------------------------------------------- 1 | ''' Complete what the output will be obtained from running each line of code. 2 | If the line of code is incorrect, type "error"''' 3 | 4 | # 1: 5 | # print(hello world) 6 | # Answer: error 7 | 8 | # 2: 9 | print(2 * 3) 10 | # Answer: 6 11 | 12 | # 3: 13 | print(("3 * 3") 14 | # Answer: 3 * 3 15 | 16 | # 4: 17 | print(2, 2) 18 | # Answer: 2 2 19 | 20 | # 5: 21 | print("hello", "world") 22 | # Answer: hello world 23 | 24 | # 6: 25 | print("my age is", 7*3) 26 | # Answer: my age is 21 27 | 28 | # 7: 29 | print(15 // 2) 30 | # Answer: my age is 7 31 | 32 | # 8: 33 | print(50 + 2 * 4) 34 | # Answer: my age is 58 35 | 36 | -------------------------------------------------------------------------------- /unit3_ex3.4.2.py: -------------------------------------------------------------------------------- 1 | # exercise 3.4.2 from unit main 2 | ''' 3 | Write a program that accepts a string of his choice from the user. 4 | The program will print to the screen a string in which all occurrences 5 | of the first character have been replaced by the character 'e', except for the first 6 | character itself. 7 | 8 | example: 9 | Please enter a string: ddar astronaut. pldase, stop drasing md! 10 | dear astronaut. please, stop erasing me! 11 | 12 | ''' 13 | 14 | str = input("Enter a string: ") 15 | char_to_replace = str[0] 16 | if(len(str) > 1): 17 | output = str[0] + str[1:].replace(char_to_replace, 'e') 18 | else: 19 | output = str[0] 20 | 21 | print(output) 22 | 23 | -------------------------------------------------------------------------------- /unit5_ex5.3.4.py: -------------------------------------------------------------------------------- 1 | # exercise 5.3.4 from unit 5 2 | ''' 3 | The function accepts as a string parameter. The function returns true if the last character that appears in the string also appears before. Otherwise the function returns false. 4 | 5 | Guidelines 6 | Uppercase or lowercase letters are not important. 7 | ''' 8 | 9 | def last_early(my_str): 10 | my_str = my_str.lower() 11 | 12 | last_char = my_str[-1] 13 | 14 | return last_char in my_str[:-1] 15 | 16 | print(last_early("happy birthday")) # True 17 | 18 | print(last_early("best of luck")) # False 19 | 20 | print(last_early("Wow")) # True 21 | 22 | print(last_early("X")) # False 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /unit6_ex6.1.2.py: -------------------------------------------------------------------------------- 1 | # exercise 6.1.2 from unit 6 2 | ''' 3 | Write a function called shift_left. The function accepts a list of length 3 and returns a new list shifted one step to the left. 4 | 5 | function definition 6 | def shift_left(my_list): 7 | Examples of running the shift_left function 8 | >>> shift_left([0, 1, 2]) 9 | [1, 2, 0] 10 | >>> shift_left(['monkey', 2.0, 1]) 11 | [2.0, 1, 'monkey'] 12 | ''' 13 | 14 | def shift_left(my_list): 15 | return my_list[1:] + [my_list[0]] 16 | 17 | def main(): 18 | print(shift_left([0, 1, 2])) # [1, 2, 0] 19 | print(shift_left(['monkey', 2.0, 1])) # [2.0, 1, 'monkey'] 20 | 21 | if __name__ == "__main__": 22 | main() 23 | -------------------------------------------------------------------------------- /unit2_ex2.4.1.py: -------------------------------------------------------------------------------- 1 | # ex 2.4.1 2 | ''' 3 | A programmer, a client of some bank, writes a program that manages his account. As part of the program, he wants to define two variables, for the following information: 4 | 5 | His account number 6 | The amount of money in his account 7 | For each item of information, choose a variable name that best suits it. 8 | 9 | Guidelines 10 | Pay attention to maintaining the conventions in the Python language. 11 | ''' 12 | 13 | # 1: 14 | # chose name for the account number of the programmer 15 | # Answer: ACCOUNT_NUMBER 16 | 17 | # 2: 18 | # chose name for the amount of money in the account number of the programmer 19 | # Answer: amount_of_money 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /unit8_ex8.3.1.py: -------------------------------------------------------------------------------- 1 | # exercise 8.3.1 from unit 8 2 | ''' 3 | given the dict: 4 | my_dict = {(1, 2): 1, (2, 3): 2} 5 | 6 | Here are four pieces of code. Choose the output obtained by running each of the code segments. 7 | 8 | ''' 9 | # 1: 10 | 11 | my_dict = {(1, 2): 1, (2, 3): 2} 12 | 13 | for key in my_dict.keys(): 14 | print(key) 15 | 16 | # Answer: (1,2) and (2,3) 17 | 18 | # 2: 19 | 20 | for value in my_dict.values(): 21 | print(value) 22 | 23 | # Answer: 1 and 2 24 | 25 | # 3: 26 | 27 | print(len(my_dict)) 28 | 29 | # Answer: 2 30 | 31 | # 4: 32 | 33 | print(my_dict[1]) 34 | 35 | # Answer: KeyError 36 | 37 | # 5: 38 | 39 | print(my_dict[1, 2]) 40 | 41 | # Answer: 1 42 | 43 | -------------------------------------------------------------------------------- /unit6_ex6.3.2.py: -------------------------------------------------------------------------------- 1 | # exercise 6.3.2 from unit 6 2 | ''' 3 | Write a function named longest defined as follows: 4 | 5 | def longest(my_list): 6 | The function accepts a list consisting of strings and returns the longest string. 7 | 8 | An example of using the longest function 9 | >>> list1 = ["111", "234", "2000", "goru", "birthday", "09"] 10 | >>> longest(list1) 11 | birthday 12 | 13 | Guidelines 14 | Do not use loops. 15 | ''' 16 | 17 | def longest(my_list): 18 | return max(my_list, key=len) 19 | 20 | def main(): 21 | list1 = ["111", "234", "2000", "goru", "birthday", "09"] 22 | longest_string = longest(list1) 23 | print(longest_string) 24 | 25 | if __name__ == "__main__": 26 | main() 27 | -------------------------------------------------------------------------------- /unit4_ex4.2.2.py: -------------------------------------------------------------------------------- 1 | # exercise 4.2.2 from unit 4 2 | ''' 3 | Write a program that accepts a string 4 | from the user and prints 'OK' if it is a palindrome, otherwise 'NOT'. 5 | 6 | Guidelines 7 | A palindrome is a string (word, number, or any sequence of characters) that is read from right to left the same as read from left to right. pay attention: 8 | Uppercase or lowercase letters do not matter. 9 | Ignore spaces. 10 | Do not use loops. 11 | ''' 12 | 13 | string = input("Enter a string: ") 14 | 15 | # Remove spaces and make all characters lowercase 16 | string = string.replace(" ", "").lower() 17 | 18 | # Check if string is a palindrome 19 | if string == string[::-1]: 20 | print("OK") 21 | else: 22 | print("NOT") 23 | -------------------------------------------------------------------------------- /unit8_ex8.2.1.py: -------------------------------------------------------------------------------- 1 | # exercise 8.2.1 from unit 8 2 | ''' 3 | Given the plan: 4 | 5 | data = ("self", "py", 1.543) 6 | format_string = "Hello" 7 | 8 | print(format_string % data) 9 | We updated the format_string variable to print: 10 | 11 | Hello self.py learner, you have only 1.5 units left before you master the course! 12 | Guidelines 13 | Use the data variable. 14 | Note that only one digit is printed after the period (ie the number 1.5). 15 | ''' 16 | 17 | def main(): 18 | data = ("self", "py", 1.543) 19 | data = ("self", "py", "1.543") 20 | format_string = "Hello %s learner, you have only %.1f units left before you master the course!" 21 | print(format_string % (data[0], float(data[2]))) 22 | 23 | if __name__ == "__main__": 24 | main() 25 | -------------------------------------------------------------------------------- /unit5_ex5.1.1.py: -------------------------------------------------------------------------------- 1 | # exercise 5.1.1 from unit 5 2 | ''' 3 | Here is a code snippet for defining the mystery function and after the definition, 4 | two code snippets to run: 5 | ''' 6 | # section 1 7 | def mystery(index): 8 | print("z" * len(index)) 9 | # section 2 10 | mystery(3) 11 | # section 3 12 | func = mystery 13 | func("python") 14 | 15 | # Mark all the correct sentences regarding the mystery function and the run sections that follow it. 16 | 17 | # Answer: 18 | # A: the var index is a paramter to the function mystery 19 | # D: the value 3 is argument that been pass to the function func 20 | # E: mystery and func is pointing to the same location on memory 21 | # G: the output from line 12 is zzzzzz 22 | # H: The mystery function is called in code section number 2 23 | -------------------------------------------------------------------------------- /unit3_ex3.3.2.py: -------------------------------------------------------------------------------- 1 | # exercise 3.3.2 from unit 3 2 | 3 | ''' 4 | Astronaut defined a string in a variable called msg (the string is a word from the field of astronomy). Unfortunately for the astronaut, the value of the msg variable was deleted for him. 5 | Your task: try to deduce, through the outputs of the commands in front of you, what the string in the msg variable is: 6 | 7 | Please note, the solution to the exercise does not require running the commands themselves (running will throw an error because the msg string is unknown) 8 | Put the string you discovered into the text box (without quotes). 9 | ''' 10 | 11 | #>>> len(msg) 12 | # 6 13 | # >>> msg[-1::] 14 | # 'y' 15 | # >>> msg[::2] 16 | # 'szg' 17 | # >>> msg[1] == msg[3] == msg[5] 18 | # True 19 | 20 | # Answer: syzygy 21 | 22 | -------------------------------------------------------------------------------- /unit3_ex3.2.1.py: -------------------------------------------------------------------------------- 1 | ''' Help the programmer to convert and print the opening words of the game "Taki" in its virtual version. 2 | You have at your disposal the original format of the opening words: ''' 3 | 4 | ''' "Shuffle, Shuffle, Shuffle", say it together! Change colors and directions, Don't back down and stop the player! Do you want to play Taki? Press y\n''' 5 | 6 | # you need to print this in one print in the following format 7 | 8 | ''' "Shuffle, Shuffle, Shuffle", say it 9 | together! 10 | Change colors and directions, 11 | Don't back down and stop the player! 12 | Do you want to play Taki? 13 | Press y\n''' 14 | 15 | print('"Shuffle, Shuffle, Shuffle", say it \n together! \n Change colors and directions, \n "Don\'t" back down and stop the player! \n\t Do you want to play Taki? \n\t\tPress y\\n"') 16 | -------------------------------------------------------------------------------- /unit4_ex4.2.4.py: -------------------------------------------------------------------------------- 1 | # exercise 4.2.4 from unit 4 2 | 3 | ''' 4 | Write a program that accepts a date from the user in the format dd/mm/yyyy 5 | and prints the day of the week for the entered date. 6 | 7 | examples: 8 | >>> Enter a date: 01/01/2000 9 | Saturday 10 | >>> Enter a date: 27/11/2051 11 | Monday 12 | 13 | Directions: Look for documentation about the calendar library and the weekday function. 14 | 15 | ''' 16 | 17 | import calendar 18 | 19 | date_str = input("Enter a date (dd/mm/yyyy): ") 20 | 21 | # Split date string into day, month, and year 22 | day, month, year = map(int, date_str.split('/')) 23 | 24 | # Get the day of the week using the weekday() method 25 | day_of_week = calendar.weekday(year, month, day) 26 | 27 | # Convert day of the week to a string 28 | day_of_week_str = calendar.day_name[day_of_week] 29 | 30 | print(day_of_week_str) 31 | -------------------------------------------------------------------------------- /unit4_ex4.4.1.py: -------------------------------------------------------------------------------- 1 | # exercise 4.4.1 from unit 4 2 | # Match each piece of code with the output obtained when running it. 3 | 4 | # 1: 5 | temperature = float(input("What is the temperature? ")) 6 | if temperature < 0: 7 | print("Brr... I need to find some penquins. to keep me company") 8 | else: 9 | print("Goodbye penquins!") 10 | # Answer: error of kind IndentationError 11 | 12 | # 2: 13 | temperature = float(input("What is the temperature? ")) 14 | if temperature < 0 15 | print("Brr... I need to find some penquins. to keep me company") 16 | else: 17 | print("Goodbye penquins!") 18 | # Answer: error of kind SyntaxError 19 | 20 | # 3: 21 | temperature = float(input("What is the temperature? ")) 22 | if temperature < 0: 23 | print("Brr... I need to find some penquins. to keep me company") 24 | else: 25 | print("Goodbye penquins!") 26 | # Answer: what is the temperature? 27 | -------------------------------------------------------------------------------- /unit5_ex5.2.1.py: -------------------------------------------------------------------------------- 1 | # exercise 5.2.1 from unit 5 2 | ''' 3 | Here are four code snippets for practicing the topic "local and global variables". Repeat the topic again if necessary and answer: 4 | What will be printed when we run each of the code snippets 5 | Choose the expected output for each piece of code. Try to answer without using an interpreter. 6 | ''' 7 | 8 | # 1: 9 | 10 | a = 1 11 | 12 | def foo1(): 13 | print(a) 14 | 15 | foo1() 16 | print(a) 17 | 18 | # Answer: output 1 and 1 19 | 20 | # 2: 21 | 22 | b = 1 23 | 24 | def foo2(): 25 | b=2 26 | print(b) 27 | 28 | foo2() 29 | print(b) 30 | 31 | # Answer: 2 and after 1 32 | 33 | # 3: 34 | 35 | c = 1 36 | 37 | def foo3(): 38 | c = c + 1 39 | print(c) 40 | 41 | foo3() 42 | print(c) 43 | 44 | # Answer: error 45 | 46 | # 4: 47 | 48 | d = 1 49 | 50 | def foo4(): 51 | global d 52 | d = 2 53 | print(d) 54 | 55 | foo4() 56 | print(d) 57 | 58 | # Answer: 2 and 2 59 | 60 | -------------------------------------------------------------------------------- /unit9_ex9.1.1.py: -------------------------------------------------------------------------------- 1 | # exercise 9.1.1 from unit 9 2 | ''' 3 | Write a function called are_files_equal defined as follows: 4 | 5 | def are_files_equal(file1, file2): 6 | The function accepts as parameters paths of two text files (strings). 7 | 8 | The function returns true (True) if the files are identical in content, otherwise returns false (False). 9 | 10 | An example of running the are_files_equal function with different files 11 | >>> are_files_equal("c:\vacation.txt", "c:\work.txt") 12 | False 13 | ''' 14 | 15 | def are_files_equal(file1, file2): 16 | # open the first file and read its contents 17 | with open(file1, 'r') as f: 18 | contents1 = f.read() 19 | # open the second file and read its contents 20 | with open(file2, 'r') as f: 21 | contents2 = f.read() 22 | # compare the contents of the two files 23 | return contents1 == contents2 24 | 25 | # test the function 26 | print(are_files_equal("c:\\vacation.txt", "c:\\work.txt")) 27 | -------------------------------------------------------------------------------- /unit1_ex1.3.2.py: -------------------------------------------------------------------------------- 1 | import this 2 | 3 | # exercise 1.3.2 from unit 1 4 | ''' 5 | Beautiful is better than ugly. 6 | Explicit is better than implicit. 7 | Simple is better than complex. 8 | Complex is better than complicated. 9 | Flat is better than nested. 10 | Sparse is better than dense. 11 | Readability counts. 12 | Special cases aren't special enough to break the rules. 13 | Although practicality beats purity. 14 | Errors should never pass silently. 15 | Unless explicitly silenced. 16 | In the face of ambiguity, refuse the temptation to guess. 17 | There should be one-- and preferably only one --obvious way to do it. 18 | Although that way may not be obvious at first unless you're Dutch. 19 | Now is better than never. 20 | Although never is often better than *right* now. 21 | If the implementation is hard to explain, it's a bad idea. 22 | If the implementation is easy to explain, it may be a good idea. 23 | Namespaces are one honking great idea -- let's do more of those!''' 24 | -------------------------------------------------------------------------------- /unit6_ex6.2.4.py: -------------------------------------------------------------------------------- 1 | # exercise 6.2.4 from unit 6 2 | 3 | ''' 4 | Write a function called extend_list_x defined as follows: 5 | def extend_list_x(list_x, list_y): 6 | The function receives two lists list_y, list_x. The function expands list_x (changes it) so that it also contains list_y at the beginning, and returns list_x. 7 | 8 | An example of running the extend_list_x function 9 | >>> x = [4, 5, 6] 10 | >>> y = [1, 2, 3] 11 | >>> extend_list_x(x, y) 12 | [1, 2, 3, 4, 5, 6] 13 | Guidelines 14 | Do not use the '+' operator. 15 | Do not use the extend method. 16 | 17 | Attention, this is a challenge exercise... ready? Take your time, try to think outside 18 | the box and look for the trick to solve it. 19 | ''' 20 | 21 | def extend_list_x(list_x, list_y): 22 | list_x[:0] = list_y 23 | return list_x 24 | 25 | def main(): 26 | x = [4, 5, 6] 27 | y = [1, 2, 3] 28 | extended_list = extend_list_x(x, y) 29 | print(extended_list) 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /unit2_ex2.2.1.py: -------------------------------------------------------------------------------- 1 | # What will be the value of the variable true_or_false in the following cases? 2 | 3 | # Choose True or False for each line of code. 4 | 5 | # 1: 6 | true_or_false = "ron" != "ron" 7 | print(true_or_false) 8 | # Answer: False 9 | 10 | # 2: 11 | true_or_false = "a" in "alpha" 12 | print(true_or_false) 13 | # Answer: True 14 | 15 | # 3: 16 | true_or_false = "A" in "alpha" 17 | print(true_or_false) 18 | # Answer: False 19 | 20 | # 4: 21 | true_or_false = "alpha" < "beta" 22 | print(true_or_false) 23 | # Answer: True 24 | 25 | # 5: 26 | true_or_false = 1 < 2 < 1 27 | print(true_or_false) 28 | # Answer: False 29 | 30 | # 6: 31 | true_or_false = 18 <= 22 < 30 32 | print(true_or_false) 33 | # Answer: True 34 | 35 | # 7: 36 | true_or_false = not(10) 37 | print(true_or_false) 38 | # Answer: False 39 | 40 | # 8: 41 | true_or_false = (7 > 10) and (1 > 1) 42 | print(true_or_false) 43 | # Answer: False 44 | 45 | # 9: 46 | true_or_false = (20 % 10 == 2) or (1 == 1) 47 | print(true_or_false) 48 | # Answer: True 49 | 50 | -------------------------------------------------------------------------------- /unit4_ex4.2.3.py: -------------------------------------------------------------------------------- 1 | # exercise 4.2.3 from unit 4 2 | ''' 3 | Write a program that converts a temperature in degrees Celsius to a 4 | temperature in degrees Fahrenheit. 5 | The program receives a temperature from the user: either 6 | in degrees Celsius, with the suffix C, or in degrees Fahrenheit, with the suffix F. 7 | If the temperature is in degrees Celsius, convert it to degree 8 | s Fahrenheit, and if the temperature is in degrees Fahrenheit, convert it to degrees Celsius. 9 | 10 | Guidelines 11 | The temperature can be either an integer or a non-integer (int or float). 12 | The suffix can be a lowercase letter or an uppercase letter (c, C, f, F). 13 | ''' 14 | 15 | temp = input("Enter a temperature: ") 16 | 17 | # Check if temperature is in Celsius or Fahrenheit 18 | if temp[-1] == 'C': 19 | # Convert Celsius to Fahrenheit 20 | temp = float(temp[:-1]) * 9.0 / 5.0 + 32.0 21 | print(f"{temp}F") 22 | else: 23 | # Convert Fahrenheit to Celsius 24 | temp = (float(temp[:-1]) - 32.0) * 5.0 / 9.0 25 | print(f"{temp}C") 26 | -------------------------------------------------------------------------------- /unit7_ex7.2.7.py: -------------------------------------------------------------------------------- 1 | # exersice 7.2.7 from unit 7 2 | ''' 3 | Write a function called arrow defined as follows: 4 | 5 | def arrow(my_char, max_length): 6 | The function accepts two parameters: the first is a single character, the second is a maximum size. 7 | The function returns a string representing an "arrow" structure (see example), built from the input, where the center of the arrow (the longest line) is the length of the size passed as a parameter. 8 | 9 | An example of running the arrow function 10 | print(arrow('*', 5)) 11 | * 12 | * * 13 | * * * 14 | * * * * 15 | * * * * * 16 | * * * * 17 | * * * 18 | * * 19 | * 20 | ''' 21 | 22 | def arrow(my_char, max_length): 23 | arrow_str = '' 24 | for i in range(max_length): 25 | arrow_str += (my_char + ' ') * i + my_char + '\n' 26 | for i in range(max_length - 2, -1, -1): 27 | arrow_str += (my_char + ' ') * i + my_char + '\n' 28 | return arrow_str 29 | 30 | def main(): 31 | print(arrow('*', 5)) 32 | 33 | if __name__ == "__main__": 34 | main() 35 | -------------------------------------------------------------------------------- /unit3_ex3.4.3.py: -------------------------------------------------------------------------------- 1 | # exercise 3.4.3 from unit 3 2 | ''' 3 | Write a program that accepts a string of his choice from the user. 4 | The program prints the string where the letters in the first half of the string are lowercase, and the letters in the second half of the string are uppercase. 5 | If the length of the string is odd, the first half will be one less than the second half. 6 | 7 | An example of running the program 8 | Please enter a string: astronaut 9 | astrONAUT 10 | 11 | Guidelines 12 | Do not use loops or if condition statement. 13 | Use slicing on strings. 14 | Assume that the length of the string is greater than 2. 15 | ''' 16 | 17 | str = input("Please enter a string: ") 18 | 19 | # calculate the length of the first half 20 | first_half_len = len(str) // 2 21 | 22 | # make the first half lowercase 23 | first_half = str[:first_half_len].lower() 24 | 25 | # make second half of the string in uppercase 26 | second_half = str[first_half_length:].upper() 27 | 28 | output = first_half + second_half 29 | 30 | print(output) 31 | -------------------------------------------------------------------------------- /unit7_ex7.2.2.py: -------------------------------------------------------------------------------- 1 | # exercise 7.2.2 from unit 7 2 | ''' 3 | Write a function called numbers_letters_count defined as follows: 4 | 5 | def numbers_letters_count(my_str): 6 | The function accepts as a string parameter. 7 | The function returns a list in which the first member represents the number of digits in the string, and the second member represents the number of letters in the string, including spaces, periods, punctuation marks, and anything other than digits. 8 | 9 | An example of running the numbers_letters_count function: 10 | >>> print(numbers_letters_count("Python 3.6.3")) 11 | [3, 9] 12 | ''' 13 | 14 | def numbers_letters_count(my_str): 15 | digits = 0 16 | letters = 0 17 | for ch in my_str: 18 | if ch.isdigit(): 19 | digits += 1 20 | else: 21 | letters += 1 22 | return [digits, letters] 23 | 24 | def main(): 25 | print(numbers_letters_count("Python 3.6.3")) 26 | print(numbers_letters_count("Hello liron")) 27 | 28 | if __name__ == "__main__": 29 | main() 30 | -------------------------------------------------------------------------------- /unit6_ex6.2.3.py: -------------------------------------------------------------------------------- 1 | # exersice 6.2.3 from unit 6 2 | ''' 3 | Write a function called format_list defined as follows: 4 | 5 | def format_list(my_list): 6 | The function receives a list of strings of even length. The function returns a string containing the members of the list in the even positions, separated by a comma and a space, and also the last member with the inscription and before it. 7 | 8 | An example of running the format_list function 9 | >>> my_list = ["hydrogen", "helium", "lithium", "beryllium", "boron", "magnesium"] 10 | >>> format_list(my_list) 11 | hydrogen, lithium, boron, and magnesium 12 | 13 | Guidelines 14 | Do not use loops. 15 | ''' 16 | def format_list(my_list): 17 | formatted_list = ', '.join(my_list[::2]) 18 | return f"{formatted_list} and {my_list[-1]}" 19 | 20 | 21 | def main(): 22 | my_list = ["hydrogen", "helium", "lithium", "beryllium", "boron", "magnesium"] 23 | formatted_list = format_list(my_list) 24 | print(formatted_list) 25 | 26 | if __name__ == "__main__": 27 | main() 28 | 29 | -------------------------------------------------------------------------------- /unit6_ex6.3.1.py: -------------------------------------------------------------------------------- 1 | # exercise 6.3.1 from unit 6 2 | ''' 3 | Write a function called are_lists_equal defined as follows: 4 | 5 | def are_lists_equal(list1, list2): 6 | The function accepts two lists containing members of the int and float types only. The function returns true if the two lists contain exactly the same elements (even if in different order), otherwise, the function returns false. 7 | 8 | An example of using the are_lists_equal function 9 | >>> list1 = [0.6, 1, 2, 3] 10 | >>> list2 = [3, 2, 0.6, 1] 11 | >>> list3 = [9, 0, 5, 10.5] 12 | >>> are_lists_equal(list1, list2) 13 | True 14 | >>> are_lists_equal(list1, list3) 15 | False 16 | 17 | Guidelines 18 | Do not use loops. 19 | ''' 20 | 21 | def are_lists_equal(list1, list2): 22 | return set(list1) == set(list2) 23 | 24 | def main(): 25 | list1 = [0.6, 1, 2, 3] 26 | list2 = [3, 2, 0.6, 1] 27 | list3 = [9, 0, 5, 10.5] 28 | print(are_lists_equal(list1, list2)) 29 | print(are_lists_equal(list1, list3)) 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /unit7_ex7.2.5.py: -------------------------------------------------------------------------------- 1 | # exercise 7.2.5 from unit 7 2 | ''' 3 | Write a function called sequence_del defined as follows: 4 | 5 | def sequence_del(my_str): 6 | The function accepts a string and deletes the letters appearing in sequence. That is, the function returns a string in which only one character appears from each sequence of identical characters in the input string. 7 | 8 | Running examples of the sequence_del function 9 | >>> sequence_del("ppyyyyythhhhhooonnnnn") 10 | python 11 | >>> sequence_del("SSSSsssshhhh") 12 | 'ssh' 13 | >>> sequence_del("Heeyyy yyouuuu!!!") 14 | 'Hey you!' 15 | ''' 16 | 17 | def sequence_del(my_str): 18 | result = "" 19 | prev_char = "" 20 | for char in my_str: 21 | if char != prev_char: 22 | result += char 23 | prev_char = char 24 | return result 25 | 26 | def main(): 27 | print(sequence_del("ppyyyyythhhhhooonnnnn")) 28 | print(sequence_del("SSSSsssshhhh")) 29 | print(sequence_del("Heeyyy yyouuuu!!!")) 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /unit7_ex7.2.4.py: -------------------------------------------------------------------------------- 1 | # exercise 7.2.4 from unit 7 2 | ''' 3 | Write a function called seven_boom which simulates the game "Seven Boom". The function is defined as: 4 | 5 | def seven_boom(end_number): 6 | The function accepts an integer, end_number. 7 | The function returns a list in the range of numbers 0 to end_number inclusive, with certain numbers replaced by the string 'BOOM', if they meet one of the following conditions: 8 | 9 | The number is a multiple of the number 7. 10 | The number contains the digit 7. 11 | Example of running the seven_boom function: 12 | >>> print(seven_boom(17)) 13 | ['BOOM', 1, 2, 3, 4, 5, 6, 'BOOM', 8, 9, 10, 11, 12, 13, 'BOOM', 15, 16, 'BOOM'] 14 | ''' 15 | 16 | def seven_boom(end_number): 17 | result = [] 18 | for i in range(1, end_number+1): 19 | if i % 7 == 0 or '7' in str(i): 20 | result.append('BOOM') 21 | else: 22 | result.append(i) 23 | return result 24 | 25 | def main(): 26 | print(seven_boom(21)) 27 | 28 | if __name__ == '__main__': 29 | main() 30 | -------------------------------------------------------------------------------- /unit8_ex8.3.3.py: -------------------------------------------------------------------------------- 1 | # exercise 8.3.3 from unit 8 2 | ''' 3 | Write a function called count_chars defined like this: 4 | 5 | def count_chars(my_str): 6 | The function accepts a string as a parameter. 7 | The function returns a dictionary, so that each element in it is a pair consisting of a key: a character from the passed string (not including spaces), and an array: the number of times the character appears in the string. 8 | 9 | An example of running the count_chars function: 10 | >>> magic_str = "abra cadabra" 11 | >>> count_chars(magic_str) 12 | {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1} 13 | ''' 14 | 15 | def main(): 16 | def count_chars_helper(my_str): 17 | char_counts = {} 18 | for char in my_str: 19 | if char == ' ': 20 | continue 21 | if char not in char_counts: 22 | char_counts[char] = 1 23 | else: 24 | char_counts[char] += 1 25 | return char_counts 26 | 27 | magic_str = "abra cadabra" 28 | print(count_chars_helper(magic_str)) 29 | 30 | main() 31 | 32 | -------------------------------------------------------------------------------- /unit7_ex7.2.1.py: -------------------------------------------------------------------------------- 1 | # exercise 7.2.1 from unit 7 2 | ''' 3 | Write a function called is_greater defined as follows: 4 | 5 | def is_greater(my_list, n): 6 | The function accepts two parameters: a list and a number n. 7 | The function returns a new list containing all the elements that are greater than the number n. 8 | 9 | An example of running the is_greater function: 10 | >>> result = is_greater([1, 30, 25, 60, 27, 28], 28) 11 | >>> print(result) 12 | [30, 60] 13 | ''' 14 | 15 | def is_greater(my_list, n): 16 | result = [] 17 | for element in my_list: 18 | if element > n: 19 | result.append(element) 20 | return result 21 | 22 | def main(): 23 | result = is_greater([1, 30, 25, 60, 27, 28], 28) 24 | print(result) # print [30, 60] 25 | result = is_greater([1, 2, 3, 4, 5, 6], 3) 26 | print(result) # print [4, 5, 6] 27 | result = is_greater([10, 20, 30, 40], 15) 28 | print(result) # print [20, 30, 40] 29 | result = is_greater([1, 2, 3, 4, 5, 6], 6) 30 | print(result) # print [] 31 | 32 | if __name__ == "__main__": 33 | main() 34 | -------------------------------------------------------------------------------- /unit9_ex9.2.2.py: -------------------------------------------------------------------------------- 1 | # exersice 9.2.2 from unit 9 2 | ''' 3 | Write a function called copy_file_content defined as follows: 4 | 5 | def copy_file_content(source, destination): 6 | The function accepts as parameters two strings representing file paths. 7 | The function copies the contents of the source file to the destination file. 8 | 9 | An example of an input file and the execution of the copy_file_content function: 10 | A file called copy.txt: 11 | 12 | Copy this text to another file. 13 | A file called paste.txt: 14 | 15 | -- some random text -- 16 | Running the function copy_file_content with the files copy.txt and paste.txt: 17 | 18 | >>> copy_file_content("copy.txt", "paste.txt") 19 | The paste.txt file after the above run of the copy_file_content function: 20 | 21 | Copy this text to another file. 22 | ''' 23 | 24 | def copy_file_content(source, destination): 25 | with open(source, 'r') as src_file: 26 | with open(destination, 'w') as dest_file: 27 | dest_file.write(src_file.read()) 28 | 29 | def main(): 30 | copy_file_content("copy.txt", "paste.txt") 31 | 32 | if __name__ == "__main__": 33 | main() 34 | 35 | -------------------------------------------------------------------------------- /unit7_ex7.1.4.py: -------------------------------------------------------------------------------- 1 | # exercise 7.1.4 from unit 7 2 | ''' 3 | Write a function called squared_numbers defined as follows: 4 | 5 | def squared_numbers(start, stop): 6 | The function accepts two integers, start and stop (assume that: start <= stop). The function returns a list containing all the squares of the numbers between start and stop (inclusive). 7 | 8 | Guidelines 9 | 10 | Use a while loop only. 11 | 12 | Running examples of the squared_numbers function 13 | >>> squared_numbers(4, 8) 14 | [16, 25, 36, 49, 64] 15 | >>> squared_numbers(-3, 3) 16 | [9, 4, 1, 0, 1, 4, 9] 17 | 18 | ''' 19 | 20 | def squared_numbers(start, stop): 21 | result = [] 22 | i = start 23 | while i <= stop: 24 | result.append(i ** 2) 25 | i += 1 26 | return result 27 | 28 | def main(): 29 | print(squared_numbers(4, 8)) # print [16, 25, 36, 49, 64] 30 | print(squared_numbers(-3, 3)) # print [9, 4, 1, 0, 1, 4, 9] 31 | print(squared_numbers(-2, 2)) # print [4, 1, 0, 1, 4] 32 | print(squared_numbers(0, 5)) # print [0, 1, 4, 9, 16] 33 | print(squared_numbers(2, 2)) # print [4] 34 | 35 | if __name__ == "__main__": 36 | main() 37 | -------------------------------------------------------------------------------- /unit3_ex3.4.4.py: -------------------------------------------------------------------------------- 1 | # exercise 3.4.4 from unit 2 | ''' 3 | A programmer wrote a plan to recreate the launch of the "Apollo 11" spacecraft. 4 | 5 | The programmer forgot to write the code according to the spacing conventions 6 | used in Python. You need to fix the code snippet. 7 | 8 | Guidelines 9 | Copy each line of code into the answer box below. 10 | Add the necessary spaces to the given line of code. 11 | Do not change/delete any characters (the only action allowed is adding spaces). 12 | 13 | ''' 14 | 15 | LAUNCH_DATE="16/07/1969" 16 | RETURN_DATE="24/07/1969" 17 | astronaut="Neil"+"Armstrong" 18 | days=how_many_days(LAUNCH_DATE‚RETURN_DATE) 19 | astronaut.take_to_space(days) 20 | 21 | # 1: 22 | # LAUNCH_DATE="16/07/1969" 23 | # Answer: LAUNCH_DATE = "16/07/1969" 24 | 25 | # 2: 26 | # RETURN_DATE="24/07/1969" 27 | # Answer: RETURN_DATE = "24/07/1969" 28 | 29 | # 3: 30 | # astronaut="Neil"+"Armstrong" 31 | # Answer: astronaut = "Neil" + "Armstrong" 32 | 33 | # 4: 34 | # days=how_many_days(LAUNCH_DATE‚RETURN_DATE) 35 | # Answer: days = how_many_days(LAUNCH_DATE‚ RETURN_DATE) 36 | 37 | # 5: 38 | # astronaut.take_to_space(days) 39 | # Answer: astronaut.take_to_space(days) 40 | 41 | -------------------------------------------------------------------------------- /unit5_ex5.3.5.py: -------------------------------------------------------------------------------- 1 | # exercise 5.3.5 from unit 5 2 | 3 | ''' 4 | Write a function called distance defined as follows: 5 | 6 | def distance(num1, num2, num3): 7 | The function accepts three integers: num1, num2, num3. 8 | 9 | The function returns true if both conditions are met: 10 | 11 | One of the numbers num2 or num3 is "close" to num1. "Near" = absolute distance 1. 12 | One of the numbers num2 or num3 is "far" from the other two numbers. "Far" = absolute distance 2 or more. 13 | Running examples of the distance function 14 | >>> distance(1, 2, 10) 15 | True 16 | >>> distance(4, 5, 3) 17 | False 18 | Guidelines 19 | You can use the built-in function (abs(num) which calculates the absolute value of a number. 20 | 21 | ''' 22 | def distance(num1, num2, num3): 23 | # Check if one of the numbers is "close" to num1 24 | cond1 = abs(num1 - num2) == 1 or abs(num1 - num3) == 1 25 | # Check if one of the numbers is "far" from the other two 26 | cond2 = abs(num2 - num3) >= 2 and abs(num2 - num1) >= 2 or abs(num3 - num1) >= 2 27 | # Return True if both conditions are met, False otherwise 28 | return cond1 and cond2 29 | 30 | print(distance(1, 2, 10)) # True 31 | 32 | print(distance(4, 5, 3)) # False 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /unit5_ex5.3.7.py: -------------------------------------------------------------------------------- 1 | # exercise 5.3.7 from unit 5 2 | ''' 3 | We would like to connect chocolate cubes to a row that is x cm long. We have small 4 | chocolate cubes 1 cm long and large chocolate cubes 5 cm long. 5 | 6 | For the purpose of the task, write a function called chocolate_maker defined as follows: 7 | 8 | def chocolate_maker(small, big, x): 9 | The function receives the number of small cubes (small), the number of large cubes (big) 10 | and the desired line length (x). The function returns true if it is possible to create 11 | a line of length x using the number of chocolate cubes it received, all or some. 12 | 13 | Guidelines 14 | Do not use loops. 15 | 16 | Running examples of the chocolate_maker function 17 | >>> chocolate_maker(3, 1, 8) 18 | True 19 | >>> chocolate_maker(3, 1, 9) 20 | False 21 | >>> chocolate_maker(3, 2, 10) 22 | True 23 | ''' 24 | 25 | def chocolate_maker(small, big, x): 26 | one_total = small * 1 27 | five_total = big * 5 28 | if one_total + five_total == x or five_total == x or one_total == x: 29 | return True 30 | elif x - one_total > 0: 31 | if (x - one_total) % 5 == 0: 32 | return x <= five_total 33 | else: 34 | return False 35 | else: 36 | return True 37 | -------------------------------------------------------------------------------- /unit8_ex8.2.3.py: -------------------------------------------------------------------------------- 1 | # exercise 8.2.3 from unit 8 2 | ''' 3 | Write a function called mult_tuple defined as follows: 4 | 5 | def mult_tuple(tuple1, tuple2): 6 | The function accepts as parameters two members of the tuple type. 7 | The function returns a tuple containing all the pairs that can be created from the members of the tuples passed as arguments. 8 | 9 | Running examples of the mult_tuple function 10 | >>> first_tuple = (1, 2) 11 | >>> second_tuple = (4, 5) 12 | >>> mult_tuple(first_tuple, second_tuple) 13 | ((1, 4), (4, 1), (1, 5), (5, 1), (2, 4), (4, 2), (2, 5), (5, 2)) 14 | >>> first_tuple = (1, 2, 3) 15 | >>> second_tuple = (4, 5, 6) 16 | >>> mult_tuple(first_tuple, second_tuple) 17 | ((1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), ( 3, 6), (4, 1), (5, 1), (6, 1), (4, 2), (5, 2), (6, 2), (4, 3), (5, 3), (6, 3)) 18 | ''' 19 | 20 | def mult_tuple(tuple1, tuple2): 21 | def combinations(t1, t2): 22 | # create a list of tuples with all combinations of elements from t1 and t2 23 | comb = [(x, y) for x in t1 for y in t2] 24 | # add all combinations of elements from t2 and t1 25 | comb += [(y, x) for x in t1 for y in t2] 26 | return comb 27 | 28 | return combinations(tuple1, tuple2) 29 | 30 | -------------------------------------------------------------------------------- /unit8_ex8.2.2.py: -------------------------------------------------------------------------------- 1 | # exercise 8.2.2 from unit 8 2 | ''' 3 | Exercise 8.2.2 4 | Write a function called sort_prices defined as follows: 5 | 6 | def sort_prices(list_of_tuples): 7 | The function receives a list of tuples that each have an item and a price. 8 | The function returns a list of tuples sorted by the price of the items in them from the largest to the smallest. 9 | 10 | Define the list of tuples that the function receives according to the following form: 11 | 12 | [('item', 'price'), ('item', 'price'), ('item', 'price')] 13 | Note that all members are of string type and price is written as a non-integer number. 14 | 15 | Running examples of the sort_prices function 16 | >>> products = [('milk', '5.5'), ('candy', '2.5'), ('bread', '9.0')] 17 | >>> sort_prices(products) 18 | [('bread', '9.0'), ('milk', '5.5'), ('candy', '2.5')] 19 | ''' 20 | 21 | def sort_prices(list_of_tuples): 22 | def get_price(tuple): 23 | return float(tuple[1]) 24 | 25 | # sort the list of tuples by the price of the item in each tuple 26 | sorted_list = sorted(list_of_tuples, key=get_price, reverse=True) 27 | return sorted_list 28 | 29 | # test the function 30 | products = [('milk', '5.5'), ('candy', '2.5'), ('bread', '9.0')] 31 | print(sort_prices(products)) 32 | -------------------------------------------------------------------------------- /unit4_ex4.2.1.py: -------------------------------------------------------------------------------- 1 | # exercise 4.2.1 from unit 4 2 | ''' 3 | Here are a couple of code snippets. For each couple, complete whether the couple's output 4 | will be the same or different. 5 | (Write the word "same" or "different" in the box, without quotation marks) 6 | 7 | Guidelines 8 | Assume that the variable rain_mm is of type integer (int). 9 | Assume that the variable in both code snippets has the same value. 10 | Recommendation: Test each pair of code sections using different variable values. 11 | Recommendation: use a truth table. 12 | ''' 13 | # first code: 14 | if rain_mm < 6 and rain_mm > 4: 15 | print("illegal") 16 | else: 17 | print("legal") 18 | 19 | # second code: 20 | if not (rain_mm == 5): 21 | print("legal") 22 | else: 23 | print("illegal") 24 | 25 | # Answer: same 26 | 27 | # first code: 28 | if rain_mm > 20 and rain_mm < 40: 29 | print("legal") 30 | else: 31 | print("illegal") 32 | 33 | # second code: 34 | if not (rain_mm < 20 and rain_mm > 40): 35 | print("legal") 36 | else: 37 | print("illegal") 38 | 39 | # Answer: different 40 | 41 | # first code: 42 | if rain_mm > 6 and rain_mm < 4: 43 | print("illegal") 44 | else: 45 | print("legal") 46 | 47 | # second code: 48 | if not (False): 49 | print("legal") 50 | else: 51 | print("illegal") 52 | 53 | # Answer: same 54 | 55 | 56 | -------------------------------------------------------------------------------- /unit2_ex_2.3.3.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The legend "The Three Little Pigs" tells about three pigs who lived under the threat of a wolf. In order to provide themselves with shelter from him, they began to gather together building materials. 3 | Write a program that will display the total number of bricks collected by the pigs, and the number of bricks available to each pig, according to the following instructions. 4 | 5 | Guidelines 6 | The program will receive as input a three-digit number (assume that the input is correct). Each digit in this number represents the number of bricks collected by another pig. 7 | The program will print the following output: 8 | The total number of bricks collected by the piggies (ie the sum of the three digits) 9 | The number of bricks that each pig will get if they divide the total number of bricks is equal among all 10 | The remainder of the distribution of bricks (as distributed in the previous section) 11 | True if the sum is divided between the three pigs without a remainder, and False otherwise. Note, do not use a conditional statement 12 | Do not use loops. 13 | ''' 14 | #ex 2.3.3 15 | 16 | blocks_num = int(input('\n Enter three digits number: ')) 17 | num1 = int(blocks_num / 100) 18 | num2 = int((blocks_num / 10) % 10) 19 | num3 = blocks_num % 10 20 | sum_blocks = num1 + num2 + num3 21 | print('\n', num1, num2, num3) 22 | print('\n', sum_blocks) 23 | print('\n', int(sum_blocks / 3)) 24 | print('\n', sum_blocks % 3 == 0) 25 | -------------------------------------------------------------------------------- /unit5_Ex5.3.6.py: -------------------------------------------------------------------------------- 1 | # exercise 5.3.6 from unit 5 2 | 3 | ''' 4 | Write a function called filter_teens defined as follows: 5 | 6 | def filter_teens(a, b, c): 7 | The function receives three values representing ages: a, b, c and returns their sum. 8 | 9 | Guidelines 10 | If the function is called with no parameters, the default value of each age is 13. 11 | If one of the values represents the age of teenagers between 13 and 19 (including them) 12 | but excluding the ages 15 and 16 - adjust its value using the function described below, 13 | so that it is calculated as 0. 14 | 15 | Write a helper function fix_age defined as follows: 16 | def fix_age(age): 17 | The function receives a number that represents an age and returns it corrected 18 | according to the rules above. Call the fix_age function from within the filter_teens 19 | function so that you don't repeat the age correction code three times. 20 | 21 | Running examples of the filter_teens function 22 | 23 | >>> filter_teens() 24 | 0 25 | >>> filter_teens(1, 2, 3) 26 | 6 27 | >>> filter_teens(2, 13, 1) 28 | 3 29 | >>> filter_teens(2, 1, 15) 30 | 18 31 | ''' 32 | def fix_age(age): 33 | if age >= 13 and age <= 19 and age not in (15, 16): 34 | return 0 35 | return age 36 | 37 | 38 | def filter_teens(a=13, b=13, c=13): 39 | a = fix_age(a) 40 | b = fix_age(b) 41 | c = fix_age(c) 42 | return a + b + c 43 | 44 | print(filter_teens()) # 0 45 | print(filter_teens(1, 2, 3)) # 6 46 | print(filter_teens(2, 1, 15)) # 18 47 | 48 | 49 | -------------------------------------------------------------------------------- /unit8_ex8.3.4.py: -------------------------------------------------------------------------------- 1 | # exercies 8.3.4 from unit 8 2 | ''' 3 | We are nearing the end of the course and at this stage you can combine the topics 4 | learned throughout the course, explore additional options yourself and apply everything 5 | in writing the code. 6 | 7 | In this exercise, write a function called inverse_dict defined as follows: 8 | 9 | def inverse_dict(my_dict): 10 | The function accepts as a parameter a dictionary. 11 | The function returns a new dictionary with a "reverse" mapping: each key in the passed 12 | dictionary is a value in the returned dictionary and each value in the passed dictionary 13 | is a key in the returned dictionary. 14 | 15 | Guidelines 16 | 17 | The inversion between keys and values may create keys that appear more than once. Therefore, 18 | display the values in the returned dictionary as a list, which may contain one or more values 19 | The returned lists should be sorted (it can be assumed that the values in the dictionary 20 | are of the same type). 21 | 22 | ''' 23 | 24 | def main(): 25 | def inverse_dict(my_dict): 26 | inverted_dict = {} 27 | for key, value in my_dict.items(): 28 | if value not in inverted_dict: 29 | inverted_dict[value] = [key] 30 | else: 31 | inverted_dict[value].append(key) 32 | for value in inverted_dict.values(): 33 | value.sort() 34 | return inverted_dict 35 | 36 | my_dict = {'a': 1, 'b': 2, 'c': 1, 'd': 2, 'e': 2} 37 | print(inverse_dict(my_dict)) 38 | 39 | main() 40 | 41 | -------------------------------------------------------------------------------- /hangmanproject_unit3.py: -------------------------------------------------------------------------------- 1 | # hangman project - three unit exercise. 2 | # author - lirom mizrahi 3 | ''' 4 | 3.5.1 5 | In the unfolding task at the end of the previous unit, you began to realize 6 | the basis of the game. You have captured a character guess from the user and 7 | printed it to the screen. 8 | 9 | Since the size of the letters that are guessed in the game is not important 10 | (ie, lowercase or uppercase), you must change the piece of code you wrote 11 | so that the guessed letter is always displayed on the screen as a lowercase letter. 12 | 13 | 3.5.2 14 | In the previous exercise, you implemented a short program that asks 15 | the player to guess a letter, but you have not yet shown him the word pattern 16 | for which he must guess letters, that is, the number of letters that make up the secret word. 17 | 18 | It's time to create the "game board" for the player, that is, the sequence of 19 | underscores that mark the position of the missing letters in the word to be guessed. 20 | 21 | Write a piece of code according to the following sections: 22 | 23 | Accept a one-word string (without spaces) from the user. 24 | Print a new string that will contain multiple underscores spaced next to each other, the length of the received string. 25 | 26 | Guidelines 27 | Solve the section without using loops. 28 | Ensure accurate output. 29 | 30 | ''' 31 | # 3.5.1 32 | guess_letter= input("Guess a letter:" ) 33 | print(guess_letter.lower()) 34 | 35 | # 3.5.2 36 | # compute the length of the word 37 | word = input("Please enter a word: ") 38 | word_len = len(word) 39 | output = "_ " * word_len 40 | 41 | # print an the empty _ based on the length of the word 42 | print(output) 43 | -------------------------------------------------------------------------------- /hangmanproject_unit4.py: -------------------------------------------------------------------------------- 1 | # hangman project - unit four exercise. 2 | # author - lirom mizrahi 3 | ''' 4 | Remember the unfolding task at the end of the previous unit, 5 | where we received a guess from the player? Have you ever wondered what happens if the 6 | player accidentally types a character that is not an English letter? Or more than one died? 7 | When we ask for input from the user, we must assume that the input will not necessarily 8 | be correct and therefore it is our responsibility to perform correctness checks on it. 9 | 10 | In this exercise you must receive a note from the user (the player). 11 | Depending on the received character, print a message to the screen regarding its correctness, 12 | according to the following requirements: 13 | 14 | For an invalid character: 15 | If the player entered a string of letters with more than one letter, 16 | print the string "E1" to the screen. 17 | If the player entered a character that is not an English letter 18 | (for example a sign like: &, *), print the string "E2" to the screen. 19 | If the player entered a letter string that has more than one character and also 20 | contains non-English characters, print the string "E3" to the screen. 21 | 22 | For a valid character: 23 | If the received character is one character and also an English letter 24 | (and not another character), print it to the screen as a lowercase letter. 25 | 26 | ''' 27 | 28 | user_note = input("Enter a note: ") 29 | 30 | if len(user_note) > 1: 31 | if user_note.isalpha(): 32 | print("E1") 33 | else: 34 | print("E3") 35 | elif len(user_note) == 1 and user_note.isalpha() != True: 36 | print("E2") 37 | else: 38 | print(user_note.lower()) 39 | -------------------------------------------------------------------------------- /unit9_ex9.2.3.py: -------------------------------------------------------------------------------- 1 | # exercise 9.2.3 from unit 9 2 | ''' 3 | Write a function called who_is_missing defined as follows: 4 | 5 | def who_is_missing(file_name): 6 | The function accepts as a parameter a path to a text file (string). 7 | The file we return is passed as an argument and contains a list of integers from 1 to some n, which are not sorted, separated by commas, when one of the numbers in the sequence disappears (that is, missing from the sorted list). 8 | 9 | The operation of the who_is_missing function: 10 | A. The function returns the missing number in the sequence (int). 11 | B. The function writes the missing number in sequence to a new file called found.txt. 12 | 13 | An example of an input file and the execution of the who_is_missing function 14 | A file called findMe.txt: 15 | 16 | 8,1,9,7,4,6,3,2 17 | Running the who_is_missing function on the findMe.txt file: 18 | 19 | >>> who_is_missing("c:\findMe.txt") 20 | 5 21 | After the above run of the who_is_missing function, a new file called found.txt is created: 22 | 23 | 5 24 | ''' 25 | 26 | def who_is_missing(file_name): 27 | # Read the file and extract the numbers 28 | with open(file_name, 'r') as f: 29 | numbers = [int(num) for num in f.read().split(',')] 30 | 31 | # Find the missing number 32 | expected_sum = sum(range(1, len(numbers) + 1)) 33 | actual_sum = sum(numbers) 34 | missing_number = expected_sum - actual_sum 35 | 36 | # Write the missing number to a new file 37 | with open('found.txt', 'w') as f: 38 | f.write(str(missing_number)) 39 | 40 | return missing_number 41 | 42 | def main(): 43 | result = who_is_missing("c:\findMe.txt") 44 | print(result) 45 | 46 | if __name__ == "__main__": 47 | main() 48 | -------------------------------------------------------------------------------- /hangmanproject_unit2.py: -------------------------------------------------------------------------------- 1 | # hangman project - second unit exercise. 2 | # author - lirom mizrahi 3 | # In this exercise you will start developing the game by designing an "opening screen" that will 4 | # appear to the player who starts playing. You need to create a designed "open screen" 5 | # for the game. 6 | # limit your gusses by using randint function 7 | # Write a piece of code that prints to the screen the seven states of the hanging man, in order. The prints will be used by us in the advanced development stages of the game. 8 | # Remember how you completed the previous exercise 9 | 10 | # name of the game: 11 | HANGMAN_ASCII_ART = print(""" _ _ 12 | | | | | 13 | | |__| | __ _ _ __ __ _ _ __ ___ __ _ _ __ 14 | | __ |/ _` | '_ \ / _` | '_ ` _ \ / _` | '_ \\ 15 | | | | | (_| | | | | (_| | | | | | | (_| | | | | 16 | |_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_| 17 | __/ | 18 | |____ / """) 19 | 20 | MAX_TRIES = random.randint(5,10) 21 | print(MAX_TRIES) 22 | 23 | guess_a_letter= input("Guess a letter:" ) 24 | print(guess_a_letter.lower()) 25 | 26 | #images for the wrong gusses 27 | 28 | #picture 1: 29 | print("x-------x") 30 | #picture 2: 31 | print("""x-------x 32 | | 33 | | 34 | | 35 | | 36 | |""") 37 | #picture 3: 38 | print("""x-------x 39 | | | 40 | | 0 41 | | 42 | | 43 | |""") 44 | #picture 4: 45 | print("""x-------x 46 | | | 47 | | 0 48 | | | 49 | | 50 | |""") 51 | #picture 5: 52 | print("""x-------x 53 | | | 54 | | 0 55 | | /|\\ 56 | | 57 | |""") 58 | #picture 6: 59 | print("""x-------x 60 | | | 61 | | 0 62 | | /|\\ 63 | | / 64 | |""") 65 | #picture 7: 66 | print("""x-------x 67 | | | 68 | | 0 69 | | /|\\ 70 | | / \\ 71 | |""") 72 | -------------------------------------------------------------------------------- /hangmanproject_unit1.py: -------------------------------------------------------------------------------- 1 | # hangman project - first unit exercise. 2 | # author - lirom mizrahi 3 | # In this exercise you will start developing the game by designing an "opening screen" that will 4 | # appear to the player who starts playing. You need to create a designed "open screen" 5 | # for the game. 6 | # limit your gusses by using randint function 7 | # Write a piece of code that prints to the screen the seven states of the hanging man, in order. The prints will be used by us in the advanced development stages of the game. 8 | # Remember how you completed the previous exercise 9 | 10 | # name of the game: 11 | HANGMAN_ASCII_ART = print(""" _ _ 12 | | | | | 13 | | |__| | __ _ _ __ __ _ _ __ ___ __ _ _ __ 14 | | __ |/ _` | '_ \ / _` | '_ ` _ \ / _` | '_ \\ 15 | | | | | (_| | | | | (_| | | | | | | (_| | | | | 16 | |_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_| 17 | __/ | 18 | |____ / """) 19 | 20 | MAX_TRIES = random.randint(5,10) 21 | print(MAX_TRIES) 22 | 23 | guess_a_letter= input("Guess a letter:" ) 24 | guess_a_letter.lower() 25 | print(guess_a_letter) 26 | 27 | #images for the wrong gusses 28 | 29 | #picture 1: 30 | print("x-------x") 31 | #picture 2: 32 | print("""x-------x 33 | | 34 | | 35 | | 36 | | 37 | |""") 38 | #picture 3: 39 | print("""x-------x 40 | | | 41 | | 0 42 | | 43 | | 44 | |""") 45 | #picture 4: 46 | print("""x-------x 47 | | | 48 | | 0 49 | | | 50 | | 51 | |""") 52 | #picture 5: 53 | print("""x-------x 54 | | | 55 | | 0 56 | | /|\\ 57 | | 58 | |""") 59 | #picture 6: 60 | print("""x-------x 61 | | | 62 | | 0 63 | | /|\\ 64 | | / 65 | |""") 66 | #picture 7: 67 | print("""x-------x 68 | | | 69 | | 0 70 | | /|\\ 71 | | / \\ 72 | |""") 73 | -------------------------------------------------------------------------------- /hangmanproject_unit5.py: -------------------------------------------------------------------------------- 1 | # hangman project - unit five exercise. 2 | # author - lirom mizrahi 3 | ''' 4 | In the task at the end of the previous unit, you thoroughly dealt with cases wher 5 | e the player types input that is not correct. Since the game "Hanged Man" includes 6 | many guesses, the question arises: will we copy all these lines of code over and over 7 | again for each guess? of course not. 8 | 9 | That's why we will bundle part of the logic from the previous task as a function 10 | called is_valid_input. The function is defined as: 11 | 12 | def is_valid_input(letter_guessed): 13 | Implement the is_valid_input function. The function receives as a parameter the string 14 | letter_guessed, which represents the received character, and returns a Boolean value 15 | representing whether the character is correct or not. 16 | 17 | The function returns false (False, an invalid string) in the following cases: 18 | If the letter_guessed string consists of two or more characters 19 | If the string letter_guessed contains a sign that is not an English letter like: &, *) 20 | The function returns true (True, a valid character) if the letter_guessed string 21 | consists of only one letter that is an English letter (and not another character). 22 | ''' 23 | 24 | def is_valid_input(letter_guessed): 25 | if letter_guessed == "E1" or letter_guessed == "E3" or letter_guessed == "E2": 26 | return False 27 | else: 28 | return True 29 | 30 | 31 | def error_check(user_note): 32 | if len(user_note) > 1: 33 | if user_note.isalpha(): 34 | return "E1" 35 | else: 36 | return "E3" 37 | elif len(user_note) == 1 and user_note.isalpha() != True: 38 | return "E2" 39 | else: 40 | return "fine" 41 | 42 | 43 | def main(): 44 | guess_a_letter = input("Guess a letter:") 45 | error = error_check(guess_a_letter) 46 | is_valid = is_valid_input(error) 47 | print(is_valid) 48 | 49 | 50 | if __name__ == "__main__": 51 | main() 52 | -------------------------------------------------------------------------------- /hangmanproject_unit8.py: -------------------------------------------------------------------------------- 1 | # hangman project - unit 8 exercise 2 | # author - lirom mizrahi 3 | ''' 4 | Towards the end of the development of the game "Hanged Man" we had to go back and print each time one of the status images of the hanging man, depending on the number of wrong guesses the player guessed. 5 | 6 | For this purpose, follow the following instructions: 7 | 8 | Define a constant variable called HANGMAN_PHOTOS. The variable is of dictionary type (dict) and must hold the seven states of the hanging man (which you encountered in the unfolding task at the end of Unit 1). 9 | Write a function called print_hangman defined as follows: 10 | def print_hangman(num_of_tries): 11 | The function prints one of the seven states of the hanging man, using: 12 | A variable called num_of_tries that represents the number of failed attempts by the user so far. 13 | The HANGMAN_PHOTOS variable you defined. 14 | An example of running the print_hangman function 15 | >>> num_of_tries = 6 16 | >>> print_hangman(num_of_tries) 17 | x-------x 18 | | | 19 | | 0 20 | | /|\ 21 | | / \ 22 | | 23 | ''' 24 | def print_hangman(num_of_tries): 25 | HANGMAN_PHOTOS = { 26 | 1: """ x-------x""", 27 | 2: """ x-------x 28 | | 29 | | 30 | | 31 | | 32 | |""", 33 | 3: """ x-------x 34 | | | 35 | | 0 36 | | 37 | | 38 | |""", 39 | 4: """ x-------x 40 | | | 41 | | 0 42 | | | 43 | | 44 | |""", 45 | 5: """ x-------x 46 | | | 47 | | 0 48 | | /|\ 49 | | 50 | |""", 51 | 6: """ x-------x 52 | | | 53 | | 0 54 | | /|\ 55 | | / 56 | |""", 57 | 7: ''' x-------x 58 | | | 59 | | 0 60 | | /| 61 | | / 62 | |''' 63 | } 64 | if num_of_tries in HANGMAN_PHOTOS.keys(): 65 | print(HANGMAN_PHOTOS[num_of_tries]) 66 | else: 67 | print('X') 68 | 69 | print(print_hangman(7)) 70 | -------------------------------------------------------------------------------- /hangmanproject_unit9.py: -------------------------------------------------------------------------------- 1 | # hangman project - unit 9 exercise. 2 | # author - lirom mizrahi 3 | ''' 4 | This task will choose for the player a word that will be the secret word for the guess, 5 | from a text file containing a list of words separated by spaces. 6 | 7 | Write a function called choose_word defined as follows: 8 | 9 | def choose_word(file_path, index): 10 | The function accepts as parameters: 11 | 12 | A string (file_path) representing a path to the text file. 13 | An integer (index) representing the position of a certain word in the file. 14 | The function returns a tuple consisting of two members in the following order: 15 | 16 | The number of different words in the file, i.e. not including repeated words. 17 | A word in the position received as an argument to the function (index), which will be used as the secret word for guessing. 18 | Guidelines 19 | Treat the positions the player enters as starting from 1 (rather than zero). 20 | If the position (index) is greater than the number of words in the file, the function 21 | continues to count positions in a circular fashion (that is, returns to the first position 22 | in the original list of words in the file and God forbid). 23 | An example of a text file that contains a list of words, called words.txt 24 | hangman song most broadly is a song hangman work music work broadly is typically 25 | Examples of running the choose_word function with the words.txt file 26 | >>> choose_word(r"c:\words.txt", 3) 27 | (9, 'most') 28 | >>> choose_word(r"c:\words.txt", 15) 29 | (9, 'hangman') 30 | 31 | ''' 32 | 33 | def choose_word(file_path, index): 34 | with open(file_path, 'r') as f: 35 | words = f.read().split() 36 | 37 | num_unique_words = len(set(words)) 38 | 39 | secret_word = words[(int(index) - 1) % len(words)] 40 | 41 | return (num_unique_words, secret_word) 42 | 43 | def main(): 44 | result = choose_word(r"words.txt", 3) 45 | print(result) 46 | result = choose_word(r"words.txt", 15) 47 | print(result) 48 | 49 | if __name__ == "__main__": 50 | main() 51 | -------------------------------------------------------------------------------- /unit8_ex8.3.2.py: -------------------------------------------------------------------------------- 1 | # exercies 8.3.2 from unit 8 2 | ''' 3 | Create a dictionary with a name of your choice and initialize it according to the 4 | following table: 5 | 6 | Mariah first_name 7 | Carey last_name 8 | 27.03.1970 (string) birth_date 9 | Sing, Compose, Act (list) hobbies 10 | 11 | Write a program that performs the following actions, depending on the digit that the user 12 | pressed: 13 | 14 | Print Maria's last name to the screen. 15 | Print to the screen the month in which Maria was born. 16 | Print to the screen the number of hobbies Maria has. 17 | Print to the screen the last hobby in Maria's list of hobbies. 18 | Add the hobby "Cooking" to the end of the list of hobbies. 19 | Turn the date of birth type into a tuple that includes 3 numbers 20 | (day, month and year - from left to right) and print it. 21 | Add a new key called age which includes Maria's age and present it. 22 | Guidelines 23 | Ask the user to enter an input (a number between 1 and 7) and assume that the input 24 | is correct. 25 | ''' 26 | 27 | def main(): 28 | # create a dictionary with Maria's information 29 | mariah = { 30 | 'first_name': 'Mariah', 31 | 'last_name': 'Carey', 32 | 'birth_date': '27.03.1970', 33 | 'hobbies': ['Sing', 'Compose', 'Act'] 34 | } 35 | 36 | user_input = int(input("Enter a number between 1 and 7: ")) 37 | 38 | def perform_action(mariah, user_input): 39 | if user_input == 1: 40 | print(mariah['last_name']) 41 | elif user_input == 2: 42 | month = mariah['birth_date'].split('.')[1] 43 | print(month) 44 | elif user_input == 3: 45 | print(len(mariah['hobbies'])) 46 | elif user_input == 4: 47 | print(mariah['hobbies'][-1]) 48 | elif user_input == 5: 49 | mariah['hobbies'].append('Cooking') 50 | print(mariah['hobbies']) 51 | elif user_input == 6: 52 | birth_date = tuple(mariah['birth_date'].split('.')) 53 | print(birth_date) 54 | elif user_input == 7: 55 | mariah['age'] = 2023 - int(mariah['birth_date'].split('.')[2]) 56 | print(mariah['age']) 57 | 58 | perform_action(mariah, user_input) 59 | 60 | # call the main function 61 | main() 62 | -------------------------------------------------------------------------------- /unit9_ex9.1.2.py: -------------------------------------------------------------------------------- 1 | # exercise 9.1.2 from unit 9 2 | ''' 3 | Write a program that receives from the user: 4 | 5 | Path to text file (string) 6 | Name of one of the operations: rev, sort or last (string) 7 | The file we return is passed as an argument containing lines of lowercase word sequences separated by a single space. 8 | 9 | According to the name of the action received from the user, the program performs: 10 | 11 | sort - the program prints all the words in the transferred file as a sorted list in alphabetical order, without duplicates. 12 | rev - the program prints the characters in each line in the file in reverse order, i.e. from the end to the beginning. 13 | last - the program receives another parameter from the user which is an integer (n), and prints the last n lines in the file (assume that the number is positive and less than or equal to the number of lines in the file). 14 | An example of an input file and lectures of the program 15 | A file called sampleFile.txt: 16 | 17 | i believe i can fly i believe i can touch the sky 18 | I think about it every night and day spread my wings and fly away 19 | Run the program on the file sampleFile.txt: 20 | 21 | >>> Enter a file path: c:\sampleFile.txt 22 | >>> Enter a task: sort 23 | ['about', 'and', 'away', 'believe', 'can', 'day', 'every', 'fly', 'i', 'it', 'my', 'night', ' sky', 'spread', 'the', 'think', 'touch', 'wings'] 24 | >>> Enter a file path: c:\sampleFile.txt 25 | >>> Enter a task: rev 26 | yks eht hcuot nac i eveileb i ylf nac i eveileb i 27 | yawa ylf dna sgniw ym daerps yad dna thgin yreve ti tuoba kniht i 28 | >>> Enter a file path: c:\sampleFile.txt 29 | >>> Enter a task: last 30 | >>> Enter a number: 1 31 | I think about it every night and day spread my wings and fly away 32 | ''' 33 | 34 | def main(): 35 | file_path = input("Enter a file path: ") 36 | task = input("Enter a task: ") 37 | with open(file_path, 'r') as f: 38 | lines = f.readlines() 39 | if task == 'sort': 40 | words = sorted(set(line.split() for line in lines)) 41 | print(words) 42 | elif task == 'rev': 43 | reversed_lines = [line[::-1] for line in lines] 44 | print(reversed_lines) 45 | elif task == 'last': 46 | n = int(input("Enter a number: ")) 47 | print(lines[-n:]) 48 | 49 | main() 50 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
4 |
5 | this repository contains solutions in python to the python course problems of the Cyber Education Center. and the final project of the course hangman
6 |
7 | 
8 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/unit9_ex9.3.1.py:
--------------------------------------------------------------------------------
1 | # exercise 9.3.1 from unit 9
2 | '''
3 | Write a function called my_mp3_playlist defined as follows:
4 |
5 | def my_mp3_playlist(file_path):
6 | The function accepts as a parameter a path to the file (string).
7 | The file represents a playlist of songs and has a fixed format consisting of the name of the song, the name of the performer (singer/band) and the length of the song, separated by a semicolon (;) without spaces.
8 |
9 | An example of an input file called songs.txt:
10 |
11 | Tudo Bom; Static and Ben El Tavori; 5:13;
12 | I Gotta Feeling; The Black Eyed Peas; 4:05;
13 | Instrumental; Unknown; 4:15;
14 | Paradise; Coldplay; 4:23;
15 | Where is the love?; The Black Eyed Peas; 4:13;
16 | The function returns a tuple in which:
17 |
18 | The first member is a string representing the name of the longest song in the file
19 | (it means the longest song, assume all lengths are different).
20 | The second member is a number representing the number of songs the file contains.
21 | The third member is a string representing the name of the operation that appears in
22 | the file the largest number of times (assume there is only one).
23 | An example of running the my_mp3_playlist function on the songs.txt file
24 | >>> print(my_mp3_playlist(r"c:\my_files\songs.txt"))
25 | ("Tudo Bom", 5, "The black Eyed Peas")
26 | '''
27 | def my_mp3_playlist(file_path):
28 | longest_song = ""
29 | longest_song_length = 0
30 | song_count = 0
31 | most_common_artist = ""
32 | artist_counts = {}
33 |
34 | with open(file_path, 'r') as f:
35 | for line in f:
36 | song, artist, length = line.strip().split(';')
37 | length_parts = length.split(':')
38 | length_minutes = int(length_parts[0])
39 | length_seconds = int(length_parts[1])
40 | total_length = length_minutes * 60 + length_seconds
41 |
42 | if total_length > longest_song_length:
43 | longest_song = song
44 | longest_song_length = total_length
45 |
46 | if artist in artist_counts:
47 | artist_counts[artist] += 1
48 | else:
49 | artist_counts[artist] = 1
50 |
51 | song_count += 1
52 |
53 | most_common_artist = max(artist_counts, key=artist_counts.get)
54 |
55 | return (longest_song, song_count, most_common_artist)
56 |
57 | def main():
58 | result = my_mp3_playlist(r"c:\my_files\songs.txt")
59 | print(result)
60 |
61 | if __name__ == "__main__":
62 | main()
63 |
--------------------------------------------------------------------------------
/unit9_ex9.3.2.py:
--------------------------------------------------------------------------------
1 | # exercise 9.3.2 from unit 9
2 | '''
3 | def my_mp4_playlist(file_path, new_song):
4 | The function accepts as parameters:
5 |
6 | Path to the file (string).
7 | Just like in the previous exercise, the file represents a playlist of songs and has a fixed format built from the name of the song, the name of the performer (singer/band) and the length of the song, separated by a semicolon (;) without spaces.
8 |
9 | An example of an input file called songs.txt:
10 | Tudo Bom; Static and Ben El Tavori; 5:13;
11 | I Gotta Feeling; The Black Eyed Peas; 4:05;
12 | Instrumental; Unknown; 4:15;
13 | Paradise; Coldplay; 4:23;
14 | Where is the love?; The Black Eyed Peas; 4:13;
15 | A string representing the name of a new song.
16 | The operation of the function my_mp4_playlist:
17 |
18 | The function writes to the file the string representing the name of a new song (new_song) instead of the name of the song that appears in the third line of the file (if the file contains less than three lines, write empty lines to the file so that the name of the song is written in the third line).
19 | The function prints the contents of the file after the change has been made.
20 | An example of running the my_mp4_playlist function on the songs.txt file
21 | >>> my_mp4_playlist(r"c:\my_files\songs.txt", "Python Love Story")
22 | Tudo Bom; Static and Ben El Tavori; 5:13;
23 | I Gotta Feeling; The Black Eyed Peas; 4:05;
24 | Python Love Story;Unknown;4:15;
25 | Paradise; Coldplay; 4:23;
26 | Where is the love?; The Black Eyed Peas; 4:13;
27 | The contents of the songs.txt file after
28 |
29 | Tudo Bom;Static and Ben El Tavori;5:13;
30 | I Gotta Feeling;The Black Eyed Peas;4:05;
31 | Python Love Story;Unknown;4:15;
32 | Paradise;Coldplay;4:23;
33 | Where is the love?;The Black Eyed Peas;4:13;
34 |
35 | '''
36 | def my_mp4_playlist(file_path, new_song):
37 | with open(file_path, 'r') as f:
38 | lines = f.readlines()
39 |
40 | while len(lines) < 3:
41 | lines.append(";;\n")
42 |
43 | song_parts = new_song.split(';')
44 | song_name = song_parts[0]
45 | artist = "Unknown"
46 | if len(song_parts) > 1:
47 | artist = song_parts[1]
48 |
49 | lines[2] = f"{song_name};{artist};\n"
50 |
51 | with open(file_path, 'w') as f:
52 | f.writelines(lines)
53 |
54 | with open(file_path, 'r') as f:
55 | print(f.read())
56 |
57 | def main():
58 | my_mp4_playlist(r"c:\my_files\songs.txt", "Python Love Story")
59 |
60 | if __name__ == "__main__":
61 | main()
62 |
63 |
64 |
--------------------------------------------------------------------------------
/hangmanproject_unit6.py:
--------------------------------------------------------------------------------
1 | # hangman project - unit six part 1 exercise.
2 | # author - lirom mizrahi
3 | '''
4 | To remind you, in the unfolding task at the end of the previous unit, you wrote a function to check the correctness
5 | of input from the user. In this exercise, you will upgrade the function so that it also refers to the letters that
6 | the player has already guessed in the game in the tests.
7 |
8 | Write the function, this time call it check_valid_input, and define it as follows:
9 |
10 | def check_valid_input(letter_guessed, old_letters_guessed):
11 | Acceptance values of the function:
12 | A string called letter_guessed. The string represents the character received from the player.
13 | A list called old_letters_guessed. The list contains the letters the player has guessed so far.
14 | The return values of the function
15 | The function returns a Boolean value representing the correctness of the string and whether the user has already guessed the character before.
16 |
17 | The function returns false (False, an invalid string) in the following cases:
18 | If the letter_guessed string consists of two or more characters
19 | If the string letter_guessed contains a sign that is not an English letter (like: &, *)
20 | If the letter_guessed string is a character already in the old_letters_guessed list (that is, this character has
21 | been guessed before and therefore it is illegal to guess it again)
22 | The function returns true (True, a valid character) if the string letter_guessed consists of only one letter
23 | that is an English letter (and not another sign) that is not in the list old_letters_guessed
24 |
25 | Examples of running the check_valid_input function
26 |
27 | >>> old_letters = ['a', 'b', 'c']
28 | >>> check_valid_input('C', old_letters)
29 | False
30 | >>> check_valid_input('ep', old_letters)
31 | False
32 | >>> check_valid_input('$', old_letters)
33 | False
34 | >>> check_valid_input('s', old_letters)
35 | True
36 |
37 | '''
38 |
39 |
40 | def error_check(user_note):
41 | if len(user_note) > 1:
42 | if user_note.isalpha():
43 | return "E1"
44 | else:
45 | return "E3"
46 | elif len(user_note) == 1 and user_note.isalpha() != True:
47 | return "E2"
48 | else:
49 | return user_note.lower()
50 |
51 |
52 | def check_valid_input(letter_guessed, old_letters_guessed):
53 | if letter_guessed == "E1" or letter_guessed == "E3" or letter_guessed == "E2":
54 | return False
55 | else:
56 | if letter_guessed not in old_letters_guessed:
57 | old_letters_guessed = old_letters_guessed.append(letter_guessed)
58 | return True
59 | else:
60 | return False
61 |
62 |
63 | def main():
64 | guess_a_letter = input("Guess a letter:")
65 | letter_guessed = error_check(guess_a_letter)
66 | check_valid = check_valid_input(letter_guessed, old_letters_guessed=['a', 'b', 'c'])
67 | print(check_valid)
68 |
69 | if __name__ == "__main__":
70 | main()
71 |
--------------------------------------------------------------------------------
/hangmanproject_unit7.py:
--------------------------------------------------------------------------------
1 | # hangman project - unit seven part 1 and 2 exercise.
2 | # author - lirom mizrahi
3 | '''
4 | 7.3.1
5 | In this exercise you will show the player his progress in guessing the secret word.
6 |
7 | Write a function called show_hidden_word defined as follows:
8 |
9 | def show_hidden_word(secret_word, old_letters_guessed):
10 | The function's acceptance values
11 | A string called secret_word. The string represents the secret word that the player has to guess.
12 | A list called old_letters_guessed. The list contains the letters the player has guessed so far.
13 | The return values of the function
14 | The function returns a string consisting of letters and underscores. The string shows the
15 | letters from the old_letters_guessed list that are in the secret_word string in their
16 | appropriate position, and the other letters in the string (which the player has not yet guessed)
17 | as underlines.
18 |
19 | Example of running the show_hidden_word function:
20 |
21 | >>> secret_word = "mammals"
22 | >>> old_letters_guessed = ['s', 'p', 'j', 'i', 'm', 'k']
23 | >>> print(show_hidden_word(secret_word, old_letters_guessed))
24 | m _ m m _ _ s
25 | Guidelines
26 | To make it clear to the player how many letters are left to guess, space the string
27 | when you print the underscores
28 |
29 | 7.3.2
30 | Time to check if the player has already won, right?
31 | In this exercise you will write a function that checks whether the player was able to guess the secret word and thus won the game!
32 |
33 | Write a function called check_win defined as follows:
34 |
35 | def check_win(secret_word, old_letters_guessed):
36 | The function's acceptance values
37 | A string called secret_word. The string represents the secret word that the player has to guess.
38 | A list called old_letters_guessed. The list contains the letters the player has guessed so far.
39 | The return values of the function
40 | The function returns true if all the letters that make up the secret word are included in the list of letters that the user guessed. Otherwise, the function returns false.
41 |
42 | Examples of running the check_win function
43 | >>> secret_word = "friends"
44 | >>> old_letters_guessed = ['m', 'p', 'j', 'i', 's', 'k']
45 | >>> print(check_win(secret_word, old_letters_guessed))
46 | False
47 | >>> secret_word = "yes"
48 | >>> old_letters_guessed = ['d', 'g', 'e', 'i', 's', 'k', 'y']
49 | >>> print(check_win(secret_word, old_letters_guessed))
50 | True
51 |
52 | '''
53 |
54 | def show_hidden_word(secret_word, old_letters_guessed):
55 | result = ''
56 | for letter in secret_word:
57 | if letter in old_letters_guessed:
58 | result += letter + ' '
59 | else:
60 | result += '_ '
61 | return result.strip()
62 |
63 | def check_win(secret_word, old_letters_guessed):
64 | for letter in secret_word:
65 | if letter not in old_letters_guessed:
66 | return False
67 | return True
68 |
69 | def main():
70 | secret_word = "lironrrrg"
71 | old_letters_guessed = ['s', 'p', 'j', 'i', 'l', 'r']
72 | print(show_hidden_word(secret_word, old_letters_guessed))
73 | secret_word = "friends"
74 | old_letters_guessed = ['m', 'p', 'j', 'i', 's', 'k']
75 | print(check_win(secret_word, old_letters_guessed))
76 | secret_word = "yes"
77 | old_letters_guessed = ['d', 'g', 'e', 'i', 's', 'k', 'y']
78 | print(check_win(secret_word, old_letters_guessed))
79 | if __name__ == "__main__":
80 | main()
81 |
82 |
--------------------------------------------------------------------------------
/unit7_ex7.2.6.py:
--------------------------------------------------------------------------------
1 | # exercise 7.2.6 from unit 7
2 | '''
3 | Write a program that receives from the user a single string representing a list of products
4 | for shopping, separated by commas without spaces.
5 | An example of an input string: "Milk,Cottage,Tomatoes".
6 |
7 | The program asks the user to key in a number (digit) in the range of one to nine
8 | (there is no need to check the correctness of the input).
9 | Depending on the number received, perform one of the following actions, according to
10 | the following breakdown:
11 |
12 | The program asks the user to key in a number (digit) in the range of one to nine
13 | (there is no need to check the correctness of the input).
14 | Depending on the number received, perform one of the following actions, according
15 | to the following breakdown:
16 |
17 | 1.Printing the list of products
18 | 2.Printing the number of products in the list
19 | 3.Printing the answer to the test "Is the product on the list?" (The user will be asked to enter a product name)
20 | 4.Printing the answer to the test "How many times does a certain product appear?" (The user will be asked to enter a product name)
21 | 5.Deleting a product from the list (the user will be asked to tap a product name, only one product will be deleted)
22 | 6.Adding a product to the list (the user will be asked to tap a product name)
23 | 7.Printing all invalid products (a product is invalid if its length is less than 3 or it contains characters other than letters)
24 | 8.Removing all existing duplicates in the list
25 |
26 | Output
27 |
28 | Please note, after the user makes a selection, the user will return to the main menu until he
29 | selects the exit (he will press the number 9).
30 |
31 | Guidelines
32 | Transfer the products that the program accepts to the list.
33 | Use additional functions of your choice.
34 |
35 | '''
36 |
37 | def main():
38 | products = input("Enter a string of products separated by commas: ").split(",")
39 |
40 | while True:
41 | print("Menu:")
42 | print("1. Print the list of products")
43 | print("2. Print the number of products in the list")
44 | print("3. Check if a product is on the list")
45 | print("4. Count the number of occurrences of a product")
46 | print("5. Delete a product from the list")
47 | print("6. Add a product to the list")
48 | print("7. Print invalid products")
49 | print("8. Remove duplicates from the list")
50 | print("9. Exit")
51 |
52 | choice = int(input("Enter your choice 1-9: "))
53 | if choice == 1:
54 | print(products)
55 | elif choice == 2:
56 | print(len(products))
57 | elif choice == 3:
58 | product = input("Enter a product name: ")
59 | if product in products:
60 | print("The product is on the list.")
61 | else:
62 | print("The product is not on the list.")
63 | elif choice == 4:
64 | product = input("Enter a product name: ")
65 | print(products.count(product))
66 | elif choice == 5:
67 | product = input("Enter a product name: ")
68 | products.remove(product)
69 | elif choice == 6:
70 | product = input("Enter a product name: ")
71 | products.append(product)
72 | elif choice == 7:
73 | invalid_products = [p for p in products if len(p) < 3 or not p.isalpha()]
74 | print(invalid_products)
75 | elif choice == 8:
76 | products = list(set(products))
77 | elif choice == 9:
78 | break
79 |
80 | if __name__ == "__main__":
81 | main()
82 |
--------------------------------------------------------------------------------
/hangmanproject_unit6.1.py:
--------------------------------------------------------------------------------
1 | # hangman project - unit six part 2 exercise.
2 | # author - lirom mizrahi
3 | '''
4 | In this exercise, you will act in accordance with the new letter that the player guessed:
5 | either you will add it to the list of guesses, or you will print a message if it is not
6 | possible to add it.
7 |
8 | Write a function called try_update_letter_guessed defined as follows:
9 |
10 | def try_update_letter_guessed(letter_guessed, old_letters_guessed):
11 | The function's acceptance values
12 | A string called letter_guessed. The string represents the character received from the player.
13 | A list called old_letters_guessed. The list contains the letters the player has guessed so far.
14 |
15 | function operation
16 | If the character is correct (ie one English letter) and has not been guessed before, the
17 | function will add the letter_guessed character to the old_letters_guessed list. Then it will
18 | return a true value (True) indicating that the addition was successful.
19 | If the character is not correct (that is, it is not a single English letter) or it is already
20 | in the list of guesses, the function will print the character X (the capital letter X) and below
21 | it the list old_letters_guessed as a string of small letters that are sorted from small to large
22 | and separated from each other by arrows (an arrow consists of the signs: <- , see sample output).
23 | The printing of the organs is to remind the player which characters he has already guessed.
24 | At the end, the function will return a false value (False), which means that it is not possible
25 | to add the character to the list of already guessed characters.
26 |
27 | directive
28 | Use the check_valid_input function that you implemented in the previous exercise.
29 |
30 | Examples of running the function
31 |
32 | >>> old_letters = ['a', 'p', 'c', 'f']
33 | >>> try_update_letter_guessed('A', old_letters)
34 | X
35 | a -> c -> f -> p
36 | False
37 | >>> try_update_letter_guessed('s', old_letters)
38 | True
39 | >>> old_letters
40 | ['a', 'p', 'c', 'f', 's']
41 | >>> try_update_letter_guessed('$', old_letters)
42 | X
43 | a -> c -> f -> p -> s
44 | False
45 | >>> try_update_letter_guessed('d', old_letters)
46 | True
47 | >>> old_letters
48 | ['a', 'p', 'c', 'f', ‘s’, 'd']
49 |
50 | '''
51 |
52 | def error_check(user_note):
53 | if len(user_note) > 1:
54 | if user_note.isalpha():
55 | return "E1"
56 | else:
57 | return "E3"
58 | elif len(user_note) == 1 and user_note.isalpha() != True:
59 | return "E2"
60 | else:
61 | return user_note.lower()
62 |
63 |
64 | def check_valid_input(letter_guessed, old_letters_guessed):
65 | if letter_guessed == "E1" or letter_guessed == "E3" or letter_guessed == "E2":
66 | return False
67 | else:
68 | if letter_guessed not in old_letters_guessed:
69 | old_letters_guessed = old_letters_guessed.append(letter_guessed)
70 | return True
71 | else:
72 | return False
73 |
74 |
75 | def try_update_letter_guessed(letter_guessed, old_letters_guessed):
76 |
77 | letter_guessed = error_check(letter_guessed)
78 | if check_valid_input(letter_guessed, old_letters_guessed) == False:
79 | print('X')
80 | old_letters_guessed = ' -> '.join(sorted(old_letters_guessed))
81 | print(old_letters_guessed)
82 | return False
83 | else:
84 | return True
85 |
86 | def main():
87 |
88 | old_letters = ['a', 'p', 'c', 'f']
89 | check_update = try_update_letter_guessed('A', old_letters)
90 | print(check_update)
91 | check_update = try_update_letter_guessed('s', old_letters)
92 | print(check_update)
93 | print(old_letters)
94 | check_update = try_update_letter_guessed('$', old_letters)
95 | print(check_update)
96 | check_update = try_update_letter_guessed('d', old_letters)
97 | print(check_update)
98 | print(old_letters)
99 |
100 | if __name__ == "__main__":
101 | main()
102 |
--------------------------------------------------------------------------------
/hangman_final_project.py:
--------------------------------------------------------------------------------
1 | import sys
2 | def welcome_Screen():
3 | """
4 | Print the logo and number of attempts.
5 |
6 | :param None
7 | :return: None
8 | :rtype: None
9 | """
10 |
11 | HANGMAN_GAME_LOGO = """
12 | __ __ ___ .__ __. _______ .___ ___. ___ .__ __. _______ ___ .___ ___. _______
13 | | | | | / \ | \ | | / _____|| \/ | / \ | \ | | / _____| / \ | \/ | | ____|
14 | | |__| | / ^ \ | \| | | | __ | \ / | / ^ \ | \| | | | __ / ^ \ | \ / | | |__
15 | | __ | / /_\ \ | . ` | | | |_ | | |\/| | / /_\ \ | . ` | | | |_ | / /_\ \ | |\/| | | __|
16 | | | | | / _____ \ | |\ | | |__| | | | | | / _____ \ | |\ | | |__| | / _____ \ | | | | | |____
17 | |__| |__| /__/ \__\ |__| \__| \______| |__| |__| /__/ \__\ |__| \__| \______| /__/ \__\ |__| |__| |_______|
18 | """
19 | print(HANGMAN_GAME_LOGO)
20 | MAX_TRIES = 6
21 | print(f"you have {MAX_TRIES} guess")
22 |
23 | def choose_word(file_path, index):
24 | """
25 | the function return the secret word for guessing.
26 |
27 | :param file_path: A string representing a path to a text file containing space-separated words
28 | :param index: Position of a particular word in the file
29 | :return: the secret word for guessing
30 | :rtype: str
31 | """
32 | # open the file at read mode and read the words from the file
33 | while True: # check if user file_path correct
34 | try:
35 | with open(file_path, 'r') as file:
36 | words = file.read().split()
37 | # take the secret word
38 | while True: # check if user index is correct
39 | try:
40 | secret_word = words[(int(index) - 1) % len(words)]
41 | return secret_word
42 | except ValueError:
43 | print(f"sorry, {index} is not a corret index. Please try again!")
44 | sys.exit()
45 |
46 | except:
47 | print(f"sorry, {file_path} is not a corret file name. Please try again!")
48 | sys.exit()
49 |
50 | def print_hangman(num_of_tries):
51 | """Prints the value of the key given as paramter.
52 |
53 | :param num_of_tries: a key for the dict(HANGMAN_PHOTOS)
54 | :type num_of_tries: int
55 | :return: None
56 | """
57 |
58 | HANGMAN_PHOTOS = {
59 | 1: """ x-------x""",
60 | 2: """ x-------x
61 | |
62 | |
63 | |
64 | |
65 | |""",
66 | 3: """ x-------x
67 | | |
68 | | 0
69 | |
70 | |
71 | |""",
72 | 4: """ x-------x
73 | | |
74 | | 0
75 | | |
76 | |
77 | |""",
78 | 5: """ x-------x
79 | | |
80 | | 0
81 | | /|\\
82 | |
83 | |""",
84 | 6: """ x-------x
85 | | |
86 | | 0
87 | | /|\\
88 | | /
89 | |""",
90 | 7: """ x-------x
91 | | |
92 | | 0
93 | | /|\\
94 | | / \\
95 | |"""
96 | }
97 | hangman_status = HANGMAN_PHOTOS[num_of_tries]
98 | print(hangman_status)
99 |
100 | def check_valid_input(letter_guessed, old_letters_guessed):
101 | """
102 | A Boolean function that accepts a character and a list of letters
103 | that the user has guessed previously. The function checks
104 | two things: the correctness of the input and whether it is legal
105 | to guess this letter (that is, the player has not guessed this letter before)
106 | and returns true or false accordingly.
107 |
108 | :param letter_guessed: character received from the user.
109 | :type letter_guessed: str
110 | :param old_letters_guessed: list contains the letters the player has guessed.
111 | :type old_letters_guessed: list
112 | :return: return True if it is a legal input, else return False
113 | :rtype: bool
114 | """
115 | # if the character is not valid return false
116 | if letter_guessed.isalpha() != True or len(letter_guessed) > 1:
117 | return False
118 | elif letter_guessed in old_letters_guessed: # if the character is not in the letters the player has guessed we return false
119 | return False
120 | else:
121 | return True
122 |
123 | def try_update_letter_guessed(letter_guessed, old_letters_guessed):
124 | """
125 | The method checks if the character is correct
126 | and if it is correct and does not exist in
127 | the letters that the user guessed then it updates the list with
128 | the new character and returns true otherwise it returns false
129 |
130 | :param letter_guessed: character received from the user.
131 | :type letter_guessed: str
132 | :param old_letters_guessed: list contains the letters the player has guessed.
133 | :type old_letters_guessed: list
134 | :return: return True if it is a legal input, else return False
135 | :rtype: bool
136 | """
137 | # check if the input is valid
138 | if check_valid_input(letter_guessed, old_letters_guessed) == False:
139 | print('X')
140 | old_letters_guessed = ' -> '.join(sorted(old_letters_guessed))
141 | print(old_letters_guessed)
142 | return False
143 | else:
144 | old_letters_guessed.append(letter_guessed)
145 | return True
146 |
147 | def show_hidden_word(secret_word, old_letters_guessed):
148 | """
149 | A function that returns a string consisting of letters and underscores.
150 |
151 | :param secret_word: word the user has to guess
152 | :type secret_word: str
153 | :param old_letters_guessed: list contains the letters the player has guessed.
154 | :type old_letters_guessed: str
155 | :return: reveal the secret word to the player in a lower-line structure
156 | :rtype: str
157 | """
158 | # we making the result string by loop all the letters in the secret word
159 | # and if the letter in the letters the user has guessed we add the letter to the result
160 | # and if not we and _ to the result
161 | result = ''
162 | for letter in secret_word:
163 | if letter in old_letters_guessed:
164 | result += letter + ' '
165 | else:
166 | result += '_ '
167 | return result
168 |
169 | def check_win(secret_word, old_letters_guessed):
170 | """
171 | This is a boolean function that returns true if all the letters that make up the secret word
172 | are included in the list of letters that the user guessed. Otherwise, the function returns false.
173 |
174 | :param secret_word: word the user has to guess
175 | :param old_letters_guessed: list contains the letters the player has guessed.
176 | :type secret_word: str
177 | :type old_letters_guessed: list
178 | :return: true if all the letters that make up the secret word are included int the list of old_letters_guessed otherwise return false
179 | :rtype: bool
180 | """
181 | # looping all the letters in secret word if one of them not int the guessed word we return False otherwise we return True
182 | for letter in secret_word:
183 | if letter not in old_letters_guessed:
184 | return False
185 | return True
186 |
187 | def main():
188 |
189 | # print the welcome screen
190 | welcome_Screen()
191 | wrong_guess = 0
192 | num_of_tries = 1
193 | old_letters_guessed = list() # create an empty list for the beginning
194 | # take from user the file path and index
195 | file_path = input("Enter file path: ")
196 | index = input("Enter index: ")
197 | secret_word = choose_word(file_path, index)
198 | print("Let’s start!")
199 | print_hangman(num_of_tries)
200 | print("_ " * len(secret_word))
201 | # game loop
202 | while wrong_guess in range(6):
203 | # take user input
204 | guessed_letter = input("Guess a letter: ").lower()
205 | # the main logic of the game
206 | if try_update_letter_guessed(guessed_letter, old_letters_guessed):
207 | if guessed_letter not in secret_word:
208 | wrong_guess += 1
209 | num_of_tries += 1
210 | print(":(")
211 | print_hangman(num_of_tries)
212 | print(show_hidden_word(secret_word, old_letters_guessed))
213 | else:
214 | print(show_hidden_word(secret_word, old_letters_guessed))
215 | if check_win(secret_word, old_letters_guessed):
216 | print("WIN")
217 | break
218 | if wrong_guess == 6:
219 | if check_win(secret_word, old_letters_guessed):
220 | print("WIN")
221 | else:
222 | print("LOSE")
223 |
224 | if __name__ == "__main__":
225 | main()
--------------------------------------------------------------------------------