# CS 1358 Introduction to Programming in Python SC2 ###### tags: `pythonSC` # 1. Definitions and Short Answers - functions 1. Given the following if-statement ```python= x = int(input('enter one number: ')) y = int(input('another number: ')) if y == 0: print('sorry, cannot divide by 0!') else: print(f'{x} / {y} = {x/y}') ``` What is the purpose of checking if y == 0? >can't divide by 0 What is the purpose of calling the int() function on the first two lines? Will the code still work if you replace lines 1-2 with ```python x = input('enter one number: ') y = input('another number: ') ``` instead? Why or why not? > no, the input() return str no integer 2. The following if-statements are not correct in Python syntax. What is wrong with them and how can they be fixed? Do not change the functionality. ```python if y == 0: # do nothing pass else: print(f'{x} / {y} = {x/y}') ``` ```python if y != 0: print(f'{x} / {y} = {x/y}') else: # do nothing pass ``` ```python if x == 0: print('zero, without checking y') elif y == 0: print('sorry, cannot divide by 0!') else: print(f'{x} / {y} = {x/y}') ``` ```python if y == 0: print('sorry, cannot divide by zero') else: print(f'{x}/{y}={x/y}') ``` 3. Given the dictionary ```python eng = {'one': 1, 'two': 2, 'three': 3, 'four': 4} ``` what is the value of the following expressions, and which ones cause errors? ```python 4 in eng #False 'three' in eng #True ('two', 2) in eng #False {'one': 1} in eng #TypeError: unhashable type: 'dict' eng['three'] #3 eng[0] #KeyError: 0 eng[1] #KeyError: 0 eng['two':2] #TypeError: unhashable type: 'slice' ``` 4. Consider the code: ```python= english={'one':1,'pan':'鍋子','cabbage':'高麗菜','pie':'派餅'} spanish = {'uno':1, 'pan':'麵包','col':'高麗菜', 'pie':'腳'} french = {'une':1, 'toi':'你', 'col':'衣領', 'pie':'鵲'} word = input('enter word to look up: ') if word in english: print(f'in English: {english[word]}') elif word in spanish: print(f'in Spanish: {spanish[word]}') elif word in french: print(f'in French: {french[word]}') else: print(f'{word} not found in dictionary') ``` When running the program, what happens when you type the following text when prompted? ```shell $uno in Spanish: 1 $pan in English: 鍋子 $toi in French: 你 $pie in English: 派餅 $col in Spanish: 高麗菜 $cabbage in English: 高麗菜 $1 1 not found in dictionary $ten ten not found in dictionary ``` 5. In Question #4, if you swap lines 7-8 with lines 9-10, will the code output exactly the same results for all inputs or different for some inputs? Which? > no it will check french first. 6. If the code in Question#4 is modified so all elif clauses get replaced by if, as shown in the following code: ```python=5 if word in english: print(f'in English: {english[word]}') if word in spanish: print(f'in Spanish: {spanish[word]}') if word in french: print(f'in French: {french[word]}') else: print(f'{word} not found in dictionary') ``` Suppose the user enters a word that is in english but not in french, does the print statement on the last line still get executed? Why or why not? > it will do the last statement, because it only check the is it in french 7. Given the following code ```python passing = False if int(input('enter grade: ')) >= 60: passing = True ``` what is the equivalent statement that uses both if and else? ```python if int(input('enter grade: ')) >= 60: passing = True else: passing = False ``` what is the equivalent (assignment) statement that does not use if at all? ```python passing = (int(input('enter grade: ')) >= 60) ``` 8. Consider the following version of the code ```python= word = input('enter word to look up: ') outList = [] if word in english: outList.append(f'in English: {english[word]}') if word in spanish: outList.append(f'in Spanish: {spanish[word]}') if word in french: outList.append(f'in French: {french[word]}') if not outList: print(f'{word} not found in dictionary') else: print('\n'.join(outList)) ``` If line 9 is changed to `if outList:`, then how should the rest of the code be updated so it behaves exactly the same? ```python=9 if outList: print('\n'.join(outList)) else: print(f'{word} not found in dictionary') ``` What does line 12 do? > add the newline in each result and print out the result Is line 2 really necessary? > Yes What if line 2 is removed and line 4 is replaced by ```python outList = [f'in English: {english[word]}'] ``` will the code still work the same way as before? if not, how can it be fixed by adding more code? > no, 9. Convert the if-else statement in the previous question (lines 9-12) into a single print() with a conditional expression as its argument. ```python=9 print('\n'.join(outList) if outList\ else f'{word} not found in dictionary') ``` 10. Convert the if-elif-elif-else statement with four suites in Question#4 (lines 5-12) into a single print() statement whose argument is a conditional expression. ```python=5 print(f'in English: {english[word]}'if word in english\ else f'in Spanish: {spanish[word]}' if word in spanish\ else f'in French: {french[word]}' if word in french\ else f'{word} not found in dictionary') ``` 11. Is there a form of conditional expression that uses the elif keyword? If so, provide an example. ```python else: if condiction: ``` 12. Given the following nested if-statement ```python= if x < 0: if y > 3: print('correct') ``` rewrite it as a single if statement by combining the two conditions. ```python= if x > 0 and y > 3: print('correct') ``` 13. Given the following function that returns a boolean value: ```python= def test(y): if y % 10: return False else: return True ``` rewrite it as a single return statement by eliminating the if-else construct completely. ```python= def test(y): return False if y % 10 else True ``` 14. Given the following function: ```python= def fn(z): if y % 10: return True if y > 400: return False return True ``` rewrite it as a single return statement by eliminating all if-constructs completely. ```python= def fn(z): return y % 10 or y <= 400 ``` 15. Write a Python function to concatenate a list of strings using a while loop. ```python= def concat_str(L): # L is a list of strings # initialize local variables: # - an index into L to select one item at a time index = 0 # - a result variable initialized to empty string result = '' while index < len(L): # fill in your condition # concatenate result with the next string in L result += L[index] # increment the index variable index += 1 # return the result string return result ``` 16. Write a Python function to concatenate a list of strings using a for loop. ```python= def concat_str(L): # L is a list of strings # initialize local variables: # - the result variable initialized to empty string result = '' for i in L : # get one string at a time from L # concatenate result with string from for loop result += i # return the result string return result ``` 17. Given the source code ```python= def index(L, val): i = 0 while i < len(L): if L[i] == val: break i += 1 return i if i < len(L) else -1 ``` Rewrite the code so that it does not use a break to exit the loop but still uses the same code as line 7 to return the i value. Hint: you need a separate "flag" variable that can take a True or False value; it should be initialized before the loop and is tested as part of the while-condition. The flag should be set to cause a break out of the loop. Be sure the i value is correct after exiting the loop. ```python= def index(L, val): i = 0 flag = True while i < len(L) and flag: if L[i] == val: flag = False i += 1 return i if not flag else -1 ``` 18. Convert the code from Problem #17 into a while-else construct (where the else clause is associated with the while construct rather than with an if clause) ```python= def index(L, val): i = 0 while i < len(L): if L[i] == val: break i += 1 else: return -1 return i ``` 19. Convert the code from Problem #17 into a while True: on line 3 and convert the while condition into an if condition inside the loop. ```python= def index(L, val): i = 0 while True: if i >= len(L): break if L[i] == val: break i += 1 return i if i < len(L) else -1 ``` 20. Referring to the same code as in Problem #17, what happens if you replace break on line 5 with continue? For example, ```shell >>> L = "abaca" >>> index(L, 'a') ``` Does the function return a value or go into an infinite loop? Why? > return a value, because the while loop end ubtil i == len(L) ```shell >>> L = "abcde" >>> index(L, 'z') ``` Does the function return a value or go into an infinite loop and why? >same as last question 21. Try to predict the behavior of the code before you try running it to verify your answer.In the code ```python= def index(L, val): i = 0 while i < len(L): if L[i] == val: break i = i + 1 else: return -1 return i ``` What causes the else suite (lines 7-8) to be executed? If line 5 is executed, will line 8 be executed? > if i >= len(L), liene(7-8) will be executed. > if line 5 is executed, line 8 will not be executed 22. Given the code ```python= ESdict = { 'one': 'uno', 'dos': 'two', 'three': 'tres'} word = input('enter an English word:') while word != '': if word in ESdict: print(f'{word} in Spanish is {ESdict[word]}') else: print(f'{word} not in dictionary') word = input('enter an English word:') ``` However, there is redundancy because line 2 and line 8 are exactly the same (except for indentation). How can this code be rewritten to eliminate this redundancy? ```python= ESdict = { 'one': 'uno', 'dos': 'two', 'three': 'tres'} while True: word = input('enter an English word:') if word == '': break if word in ESdict: print(f'{word} in Spanish is {ESdict[word]}') else: print(f'{word} not in dictionary') ``` 23. Given the following code ```python= def StackInterpreter(): L = [] while True: line = input('command? ') words = line.split() if len(words) == 0: pass elif words[0] == 'show': print(L) elif words[0] == 'push': L.extend(words[1:]) elif words[0] == 'pop': print(L.pop()) elif words[0] == 'quit': break else: print('unknown command') ``` If the elif keywords on lines 8, 10, 12, 14 are replaced by if, will the code still behave the same way as far as the user is concerned? Why? > No, the elif keyword line 14 can't be change 24. Using the same code from the previous problem, line 7 can be replaced by a single-keyword statement and the code still behaves the same way to the user. What is the keyword? Explain. > continue, it skips the rest of this iteration 25. Using the same code from the previous problem, line 15 can be replaced by a single-keyword statement and the code still behave the same way. What is it? > return, return will end the function call. 26. Given the code ```python= def StackInterpreter(): L = [] while True: line = input('command? ') words = line.split() if len(words) == 0: continue if words[0] == 'show': print(L) continue if words[0] == 'push': L.extend(words[1:]) continue if words[0] == 'pop': print(L.pop()) continue if words[0] == 'quit': break print('unknown command') ``` Why doesn't line 19 need to be inside an else-clause but can be an unconditional statement at the same level as all preceding if-statements? > because other if statement end with continue and will skip the rest iteration. 27. Given the Python code ```python= def product(L): p = 1 for i in range(len(L)): p = p * L[i] return p ``` Rewrite it as a while-loop ```python= def product(L): p = 1 i = 0 while i < len(L): p = p * L[i] return p ``` Rewrite it as a Pythonic for-loop ```python= def product(L): p = 1 for i in rangeL: p = p * i return p ``` 28. What is the value of the expression ```python list(enumerate("abcde")) list(enumerate(range(5, 10))) list(enumerate(['Sun', 'Mon', 'Tue', 'Wed'])) list(enumerate(['Jan', 'Feb', 'Mar'], start=1)) ``` ```python [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')] [(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)] [(0, 'Sun'), (1, 'Mon'), (2, 'Tue'), (3, 'Wed')] [(1, 'Jan'), (2, 'Feb'), (3, 'Mar')] ``` 29. Rewrite the following code using a Pythonic for-loop: ```python= def find(L, val): i = 0 for i, v in enmerate(L): if v == val: return i return -1 ```