amt

P1

amt
Sep 28th, 2021 (edited)
440
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 51.26 KB | None | 0 0
  1. '''
  2. there cannot be more than one instruction in a line.
  3. '''
  4.  
  5. '''
  6. print() begins its output from a new line each time it starts its execution; you can change this behavior, but you can also use it to your advantage;
  7. '''
  8.  
  9. '''
  10. the instructions in the code are executed in the same order in which they have been placed in the source file; no next instruction is executed until the previous one is completed (there are some exceptions to this rule, but you can ignore them for now)
  11. '''
  12.  
  13. print("The itsy bitsy spider . \
  14. climbed up the waterspout.")
  15. print()
  16. print("Down came the rain\nand washed the spider out.")
  17.  
  18. '''
  19. The itsy bitsy spider . climbed up the waterspout.
  20.  
  21. Down came the rain
  22. and washed the spider out.
  23. '''
  24.  
  25. '''
  26. The backslash (\) has a very special meaning when used inside strings - this is called the escape character.
  27. '''
  28.  
  29. '''
  30. print("\") SyntaxError: EOL while scanning string literal
  31. '''
  32.  
  33. print("\\") # \
  34. print("The itsy" , "bitsy" , "spider") # The itsy bitsy spider
  35.  
  36. '''
  37. a print() function invoked with more than one argument outputs them all on one line;
  38. the print() function puts a space between the outputted arguments on its own initiative.
  39.  
  40. The print() function - the positional way of passing the arguments
  41.  
  42. a keyword argument consists of three elements: a keyword identifying the argument (end here); an equal sign (=); and a value assigned to that argument;
  43. any keyword arguments have to be put after the last positional argument (this is very important)
  44. '''
  45.  
  46. print("My name is", "Python.", end=" ")
  47. print("Monty Python.") # My name is Python. Monty Python.
  48.  
  49. print("My", "name", "is", "Monty", "Python.", sep="-") # My-name-is-Monty-Python.
  50.  
  51. print("My", "name", "is", sep="_", end="|||")
  52. print("Monty", "Python.", sep="*", end="*\n") # My_name_is|||Monty*Python.*
  53.  
  54. '''
  55. A literal is data whose values are determined by the literal itself.
  56.  
  57. you can write this number either like this: 11111111, or like that: 11_111_111
  58.  
  59. If an integer number is preceded by an 0O or 0o prefix (zero-o), it will be treated as an octal value. This means that the number must contain digits taken from the [0..7] range only.
  60.  
  61. 0o123 is an octal number with a (decimal) value equal to 83.
  62.  
  63. The print() function does the conversion automatically.
  64.  
  65. Hexadecimal numbers should be preceded by the prefix 0x or 0X (zero-x).
  66.  
  67. 0x123 is a hexadecimal number with a (decimal) value equal to 291. The print() function can manage these values too.
  68. '''
  69. print(12_3_47 + 3); # 12350
  70.  
  71. print(0o123) # 83
  72. print(0x123) #123
  73.  
  74. print(.4, 4.) # 0.4 4.0
  75. print(3E8) # 300000000.0
  76.  
  77. print(3.6E-84) # 3.6e-84
  78. print(0.0000000000000000000001) # 1e-22
  79.  
  80. '''
  81. Python always chooses the more economical form of the number's presentation, and you should take this into consideration when creating literals.
  82. '''
  83.  
  84. print("I like \"Monty Python\"") # I like "Monty Python"
  85. print('I like "Monty Python"') # I like "Monty Python"
  86.  
  87. '''
  88. string can be empty - it may contain no characters at all.
  89.  
  90. ''
  91. ""
  92. '''
  93.  
  94. print(True > False) # True
  95. print(True < False) # False
  96. print(True == False) # False
  97. print(not True == False) # True
  98.  
  99. print('"I\'m"\n""learning""\n"""Python"""') #"I'm"
  100. ""learning""
  101. """Python"""
  102.  
  103. '''
  104. 1011 is 11 because (2**3) + 0 + (2**1) + (2**0) = 11
  105. '''
  106.  
  107. print(2+2) # 4
  108.  
  109. '''
  110. Remember: Data and operators when connected together form expressions. The simplest expression is a literal itself.
  111. '''
  112.  
  113. print(2 ** 3) # 8
  114. print(2 ** 3.) # 8.0
  115. print(2.3 ** 3) # 12.166999999999998
  116. print(2. ** 3.4) # 10.556063286183154
  117.  
  118. print(2 * 3) # 6
  119. print(2 * 3.) # 6.0
  120. print(2. * 3) # 6.0
  121. print(2. * 3.) # 6.0
  122.  
  123. print(6 / 3) # 2.0
  124. print(6 / 3.) # 2.0
  125. print(6. / 3) # 2.0
  126. print(6. / 3.) # 2.0
  127.  
  128. print(6 // 3) # 2
  129. print(6 // 3.) # 2.0
  130. print(6. // 3) # 2.0
  131. print(6. // 3.) # 2.0
  132.  
  133. print(6 // 4) # 1
  134. print(6. // 4) # 1.0
  135. print(-6 // 4) # -2
  136. print(6. // -4) # -2.0
  137.  
  138. '''
  139. // (double slash) sign is an integer divisional operator,
  140. its result lacks the fractional part - it's absent (for integers),
  141. or is always equal to zero (for floats);
  142. this means that the results are always rounded to the lesser integer;
  143. '''
  144.  
  145. print(14 % 4) # 2
  146. print(12 % 4.5) # 3.0
  147. print(0 / 3) # 0.0
  148. print(0.1 / 0) # ZeroDivisionError: float division by zero
  149.  
  150. print(-4 + 4) # 0
  151. print(-4. + 8) # 4.0
  152.  
  153. print(-4 - 4) # -8 # used as unary and binary operator
  154. print(4. - 8) # -4.0 # used as binary operator
  155. print(-1.1) # -1.1 # used as unary operator
  156.  
  157. print(+2) #. 2
  158.  
  159. print(9 % 6 % 2) # 1 # left side binding
  160. print(2 ** 2 ** 3) # 256 # right side binding
  161.  
  162. '''
  163. Priority    Operator   
  164. 1   +, -    unary
  165. 2   ** 
  166. 3   *, /, //, %
  167. 4   +, -    binary
  168. '''
  169. print(2 * 3 % 5) # 1
  170. print((5 * ((25 % 13) + 100) / (2 * 13)) // 2) # 10.0
  171.  
  172. '''
  173. 1. An expression is a combination of values (or variables, operators, calls to functions - you will learn about them soon) which evaluates to a value, e.g., 1 + 2.
  174.  
  175. 2. Operators are special symbols or keywords which are able to operate on the values and perform (mathematical) operations, e.g., the * operator multiplies two values: x * y.
  176.  
  177. 3. Arithmetic operators in Python: + (addition), - (subtraction), * (multiplication), / (classic division - always returns a float), % (modulus - divides left operand by right operand and returns the remainder of the operation, e.g., 5 % 2 = 1), ** (exponentiation - left operand raised to the power of right operand, e.g., 2 ** 3 = 2 * 2 * 2 = 8), // (floor/integer division - returns a number resulting from division, but rounded down to the nearest whole number, e.g., 3 // 2.0 = 1.0)
  178.  
  179. 4. A unary operator is an operator with only one operand, e.g., -1, or +3.
  180.  
  181. 5. A binary operator is an operator with two operands, e.g., 4 + 5, or 12 % 5.
  182.  
  183. 6. Some operators act before others - the hierarchy of priorities:
  184.  
  185. unary + and - have the highest priority
  186. then: **, then: *, /, and %, and then the lowest priority: binary + and -.
  187. 7. Subexpressions in parentheses are always calculated first, e.g., 15 - 1 * (5 * (1 + 2)) = 0.
  188.  
  189. 8. The exponentiation operator uses right-sided binding, e.g., 2 ** 2 ** 3 = 256.
  190. ,,,
  191. print((2 ** 4), (2 * 4.), (2 * 4)) # 16 8.0 8
  192. print((-2 / 4), (2 / 4), (2 // 4), (-2 // 4)) # -0.5 0.5 0 -1
  193. print((2 % -4), (2 % 4), (2 ** 3 ** 2)) # -2 2 512
  194.  
  195. '''
  196. the name of the variable must be composed of upper-case or lower-case letters, digits, and the character _ (underscore)
  197. the name of the variable must begin with a letter;
  198. the underscore character is a letter;
  199. upper- and lower-case letters are treated as different (a little differently than in the real world - Alice and ALICE are the same first names, but in Python they are two different variable names, and consequently, two different variables);
  200. the name of the variable must not be any of Python's reserved words (the keywords - we'll explain more about this soon).
  201. '''
  202.  
  203. '''
  204. Keywords
  205. ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
  206. '''
  207. print(AbraCaDabra) # NameError: name 'AbraCaDabra' is not defined
  208.  
  209. var = 3
  210. print("Python version: " + var) # TypeError: can only concatenate str (not "int") to str
  211.  
  212. a = 3.0
  213. b = 4.0
  214. c = (a ** 2 + b ** 2) ** 0.5 # √ (x)  = x(½)
  215. print("c =", c) # 5.0
  216.  
  217. '''
  218. 1. A variable is a named location reserved to store values in the memory. A variable is created or initialized automatically when you assign a value to it for the first time. (2.1.4.1)
  219.  
  220. 2. Each variable must have a unique name - an identifier. A legal identifier name must be a non-empty sequence of characters, must begin with the underscore(_), or a letter, and it cannot be a Python keyword. The first character may be followed by underscores, letters, and digits. Identifiers in Python are case-sensitive. (2.1.4.1)
  221.  
  222. 3. Python is a dynamically-typed language, which means you don't need to declare variables in it. (2.1.4.3) To assign values to variables, you can use a simple assignment operator in the form of the equal (=) sign, i.e., var = 1.
  223.  
  224. 4. You can also use compound assignment operators (shortcut operators) to modify values assigned to variables, e.g., var += 1, or var /= 5 * 2. (2.1.4.8)
  225.  
  226. 5. You can assign new values to already existing variables using the assignment operator or one of the compound operators, e.g.: (2.1.4.5)
  227.  
  228. var = 2
  229. print(var)
  230.  
  231. var = 3
  232. print(var)
  233.  
  234. var += 1
  235. print(var)
  236.  
  237.  
  238. 6. You can combine text and variables using the + operator, and use the print() function to output strings and variables, e.g.: (2.1.4.4)
  239.  
  240. var = "007"
  241. print("Agent " + var)
  242. '''
  243.  
  244. a = 6
  245. b = 3
  246. a /= 2 * b
  247. print(a) # 1.0
  248.  
  249. anything = input("Tell me anything...")
  250. print(anything)
  251.  
  252. '''
  253. result of the input() function is a string.
  254. '''
  255.  
  256. anything = float(input("Enter a number: "))
  257. print(anything ** 2.0) # 4 -> 16.0
  258.  
  259. print("James" * 3) # JamesJamesJames
  260. print(3 * "caT") # caTcaTcaT
  261. print(0 * "caT") #
  262. print(-10 * "caT") #
  263.  
  264. print("No " + str(4)) # No 4
  265.  
  266. '''
  267. 1. The print() function sends data to the console, while the input() function gets data from the console.
  268.  
  269. 2. The input() function comes with an optional parameter: the prompt string. It allows you to write a message before the user input, e.g.:
  270.  
  271. name = input("Enter your name: ")
  272. print("Hello, " + name + ". Nice to meet you!")
  273.  
  274.  
  275. 3. When the input() function is called, the program's flow is stopped, the prompt symbol keeps blinking (it prompts the user to take action when the console is switched to input mode) until the user has entered an input and/or pressed the Enter key.
  276.  
  277. NOTE
  278.  
  279. You can test the functionality of the input() function in its full scope locally on your machine. For resource optimization reasons, we have limited the maximum program execution time in Edube to a few seconds. Go to Sandbox, copy-paste the above snippet, run the program, and do nothing - just wait a few seconds to see what happens. Your program should be stopped automatically after a short moment. Now open IDLE, and run the same program there - can you see the difference?
  280.  
  281. Tip: the above-mentioned feature of the input() function can be used to prompt the user to end a program. Look at the code below:
  282.  
  283. name = input("Enter your name: ")
  284. print("Hello, " + name + ". Nice to meet you!")
  285.  
  286. print("\nPress Enter to end the program.")
  287. input()
  288. print("THE END.")
  289.  
  290.  
  291. 3. The result of the input() function is a string. You can add strings to each other using the concatenation (+) operator. Check out this code:
  292.  
  293. num_1 = input("Enter the first number: ") # Enter 12
  294. num_2 = input("Enter the second number: ") # Enter 21
  295.  
  296. print(num_1 + num_2) # the program returns 1221
  297.  
  298.  
  299. 4. You can also multiply (* - replication) strings, e.g.:
  300.  
  301. my_input = input("Enter something: ") # Example input: hello
  302. print(my_input * 3) # Expected output: hellohellohello
  303. '''
  304.  
  305. x = input("Enter a number: ") # The user enters 2
  306. print(type(input("Enter a number: "))) # <class 'str'>
  307.  
  308. '''
  309. == is a binary operator with left-sided binding. It needs two arguments and checks if they are equal.
  310. '''
  311.  
  312. The question will be as follows:
  313.  
  314. black_sheep == 2 * white_sheep
  315.  
  316.  
  317. Due to the low priority of the == operator, the question shall be treated as equivalent to this one:
  318.  
  319. black_sheep == (2 * white_sheep) # True # Due to low priority of == operator, be treated as black_sheep == 2 * white_sheep
  320. print(4 == 2 * 2) # True
  321. print(4 == 2 + 2) # True
  322.  
  323. '''
  324. Priority    Operator   
  325. 1   +, -    unary
  326. 2   ** 
  327. 3   *, /, //, %
  328. 4   +, -    binary
  329. 5   <, <=, >, >=   
  330. 6   ==, !=
  331. '''
  332. print(2 == 2.) # True # Python is able to convert the integer value into its real equivalent
  333.  
  334. '''
  335. note: if there is more than one instruction in the indented part, the indentation should be the same in all lines; even though it may look the same if you use tabs mixed with spaces, it's important to make all indentations exactly the same - Python 3 does not allow mixing spaces and tabs for indentation.
  336. '''
  337.  
  338. if sheep_counter >= 120:
  339.     make_a_bed() # executed conditionally
  340.     take_a_shower() # executed conditionally
  341.     sleep_and_dream() # executed conditionally
  342. feed_the_sheepdogs() # executed always
  343.  
  344. if the_weather_is_good:
  345.     if nice_restaurant_is_found:
  346.         have_lunch()
  347.     else:
  348.         eat_a_sandwich()
  349. else:
  350.     if tickets_are_available:
  351.         go_to_the_theater()
  352.     else:
  353.         go_shopping()
  354.  
  355. if the_weather_is_good:
  356.     go_for_a_walk()
  357. elif tickets_are_available:
  358.     go_to_the_theater()
  359. elif table_is_available:
  360.     go_for_lunch()
  361. else:
  362.     play_chess_at_home()
  363.  
  364. '''
  365. you mustn't use else without a preceding if;
  366. else is always the last branch of the cascade, regardless of whether you've used elif or not;
  367. else is an optional part of the cascade, and may be omitted;
  368. if there is an else branch in the cascade, only one of all the branches is executed;
  369. if there is no else branch, it's possible that none of the available branches is executed.
  370. ''''
  371.  
  372. # Read two numbers
  373. number1 = int(input("Enter the first number: "))
  374. number2 = int(input("Enter the second number: "))
  375.  
  376. # Choose the larger number
  377. if number1 > number2:
  378.    larger_number = number1
  379. else: larger_number = number2
  380.  
  381. # Print the result
  382. print("The larger number is:", larger_number)
  383.  
  384. '''
  385. 1. The comparison (or the so-called relational) operators are used to compare values. The table below illustrates how the comparison operators work, assuming that x = 0, y = 1, and z = 0:
  386.  
  387. Operator    Description Example
  388. ==  returns if operands' values are equal, and False otherwise 
  389. x == y  # False
  390. x == z  # True
  391.  
  392. !=  returns True if operands' values are not equal, and False otherwise
  393. x != y  # True
  394. x != z  # False
  395.  
  396. >   True if the left operand's value is greater than the right operand's value, and False otherwise
  397. x > y  # False
  398. y > z  # True
  399.  
  400. <   True if the left operand's value is less than the right operand's value, and False otherwise   
  401. x < y  # True
  402. y < z  # False
  403.  
  404. True if the left operand's value is greater than or equal to the right operand's value, and False otherwise
  405. x >= y  # False
  406. x >= z  # True
  407. y >= z  # True
  408.  
  409. True if the left operand's value is less than or equal to the right operand's value, and False otherwise   
  410. x <= y  # True
  411. x <= z  # True
  412. y <= z  # False
  413.  
  414. 2. When you want to execute some code only if a certain condition is met, you can use a conditional statement:
  415.  
  416. a single if statement, e.g.:
  417.  
  418. x = 10
  419.  
  420. if x == 10: # condition
  421.     print("x is equal to 10")  # Executed if the condition is True.
  422.  
  423.  
  424. a series of if statements, e.g.:
  425.  
  426. x = 10
  427.  
  428. if x > 5: # condition one
  429.     print("x is greater than 5")  # Executed if condition one is True.
  430.  
  431. if x < 10: # condition two
  432.     print("x is less than 10")  # Executed if condition two is True.
  433.  
  434. if x == 10: # condition three
  435.     print("x is equal to 10")  # Executed if condition three is True.
  436.    
  437.  
  438. Each if statement is tested separately.
  439. '''
  440. x, y, z = 5, 10, 8
  441. x, y, z = z, y, x
  442.  
  443. print(x > z) # True
  444. print((y - 5) == x) # False
  445.  
  446.  
  447.  
  448. x = 10
  449.  
  450. if x == 10:
  451.    print(x == 10)  # True
  452. if x > 5:
  453.    print(x > 5)  # True
  454. if x < 10:
  455.    print(x < 10)
  456. else:
  457.    print("else")  # else
  458.  
  459.  
  460. x = "1"
  461.  
  462. if x == 1:
  463.    print("one")
  464. elif x == "1":
  465.    if int(x) > 1:
  466.        print("two")
  467.    elif int(x) < 1:
  468.        print("three")
  469.    else:
  470.        print("four") # four
  471. if int(x) == 1:
  472.    print("five") # five
  473. else:
  474.    print("six")
  475.  
  476.  
  477. x = 1
  478. y = 1.0
  479. z = "1"
  480.  
  481. if x == y:
  482.    print("one") # one
  483. if y == int(z):
  484.    print("two") # two
  485. elif x == y:
  486.    print("three")
  487. else:
  488.    print("four")
  489.  
  490. '''
  491. when the condition is met, if performs its statements only once; while repeats the execution as long as the condition evaluates to True.
  492.  
  493. Note: all the rules regarding indentation are applicable here, too.
  494.  
  495. if you want to execute more than one statement inside one while, you must (as with if) indent all the instructions in the same way;
  496. an instruction or set of instructions executed inside the while loop is called the loop's body;
  497. if the condition is False (equal to zero) as early as when it is tested for the first time, the body is not executed even once (note the analogy of not having to do anything if there is nothing to do);
  498. the body should be able to change the condition's value, because if the condition is True at the beginning, the body might run continuously to infinity - notice that doing a thing usually decreases the number of things to do).
  499.  
  500. '''
  501.  
  502. while True:
  503.    print("I'm stuck inside a loop.") # infinite loop
  504.  
  505.  
  506. ---
  507. # Store the current largest number here.
  508. largest_number = -999999999
  509.  
  510. # Input the first value.
  511. number = int(input("Enter a number or type -1 to stop: "))
  512.  
  513. # If the number is not equal to -1, continue.
  514. while number != -1:
  515.    # Is number larger than largest_number?
  516.    if number > largest_number:
  517.        # Yes, update largest_number.
  518.        largest_number = number
  519.    # Input the next number.
  520.    number = int(input("Enter a number or type -1 to stop: "))
  521.  
  522. # Print the largest number.
  523. print("The largest number is:", largest_number)
  524.  
  525. ---
  526. # A program that reads a sequence of numbers
  527. # and counts how many numbers are even and how many are odd.
  528. # The program terminates when zero is entered.
  529.  
  530. odd_numbers = 0
  531. even_numbers = 0
  532.  
  533. # Read the first number.
  534. number = int(input("Enter a number or type 0 to stop: "))
  535.  
  536. # 0 terminates execution.
  537. while number != 0:
  538.    # Check if the number is odd.
  539.    if number % 2 == 1:
  540.        # Increase the odd_numbers counter.
  541.        odd_numbers += 1
  542.    else:
  543.        # Increase the even_numbers counter.
  544.        even_numbers += 1
  545.    # Read the next number.
  546.    number = int(input("Enter a number or type 0 to stop: "))
  547.  
  548. # Print results.
  549. print("Odd numbers count:", odd_numbers)
  550. print("Even numbers count:", even_numbers)
  551.  
  552. '''
  553. two forms are equivalent:
  554.  
  555. while number != 0: and while number:.
  556.  
  557. if number % 2 == 1: and if number % 2:.
  558. '''
  559.  
  560. counter = 5 # Using a counter variable to exit a loop
  561. while counter != 0:
  562.    print("Inside the loop.", counter)
  563.    counter -= 1
  564. print("Outside the loop.", counter)
  565.  
  566. ---
  567. i = 0
  568. while i < 10:
  569.    print("Not 10 yet")
  570.    i += 1
  571. ---
  572. for i in range(10):
  573.    print("Not 10 yet")
  574.    pass
  575.  
  576. '''
  577. the for keyword opens the for loop; note - there's no condition after it; you don't have to think about conditions, as they're checked internally, without any intervention;
  578. any variable after the for keyword is the control variable of the loop; it counts the loop's turns, and does it automatically;
  579. the in keyword introduces a syntax element describing the range of possible values being assigned to the control variable;
  580. the range() function (this is a very special function) is responsible for generating all the desired values of the control variable; in our example, the function will create (we can even say that it will feed the loop with) subsequent values from the following set: 0, 1, 2 .. 97, 98, 99; note: in this case, the range() function starts its job from 0 and finishes it one step (one integer number) before the value of its argument;
  581. note the pass keyword inside the loop body - it does nothing at all; it's an empty instruction - we put it here because the for loop's syntax demands at least one instruction inside the body (by the way - if, elif, else and while express the same thing)
  582. '''
  583. for i in range(10):
  584.    print("The value of i is currently", i)
  585.  
  586. '''
  587. the loop has been executed ten times (it's the range() function's argument)
  588. the last control variable's value is 9 (not 10, as it starts from 0, not from 1)
  589. '''
  590.  
  591. for i in range(2, 8):
  592.     print("The value of i is currently", i)
  593.  
  594. '''
  595. range() first argument determines the initial value of the control variable. 2 here.
  596.  
  597. last argument is first value the control variable will not be assigned ,8 here. It goes only till 7.
  598.  
  599. Note: the range() function accepts only integers as its arguments, and generates sequences of integers.
  600. '''
  601. for i in range(2, 8, 3):
  602.     print("The value of i is currently", i)
  603.  
  604. # The value of i is currently 2
  605. # The value of i is currently 5
  606.  
  607. '''
  608. range() function's third argument is an increment - it's a value added to control the variable at every loop turn (as you may suspect, the default value of the increment is 1).
  609. '''
  610.  
  611. for i in range(1, 1):
  612.     print("The value of i is currently", i) # No output, set generated by the range() function is empty
  613.  
  614. for i in range(1, 2, 3):
  615.     print("The value of i is currently", i) # The value of i is currently 1
  616.  
  617. for i in range(2, 1):
  618.     print("The value of i is currently", i) # No output, set generated by the range() has to be sorted in ascending order.
  619. # second argument must be greater than the first
  620.  
  621. power = 1
  622. for expo in range(16):
  623.     print("2 to the power of", expo, "is", power)
  624.     power *= 2
  625.  
  626.  
  627. import time
  628. for second in range(1, 6):
  629.     print(second, "Mississippi")
  630.     time.sleep(1) # suspend execution for one second
  631.  
  632. '''
  633. break - exits the loop immediately, and unconditionally ends the loop's operation; the program begins to execute the nearest instruction after the loop's body;
  634. continue - behaves as if the program has suddenly reached the end of the body; the next turn is started and the condition expression is tested immediately.
  635. '''
  636. for i in range(1, 4):
  637.     if i == 2:
  638.         break
  639.     print("Before break.", i) # Before break. 1
  640.  
  641.  
  642. for i in range(1, 4):
  643.     if i == 2:
  644.         continue
  645.     print("Not with continue", i)
  646. # Not with continue 1
  647. # Not with continue 3
  648.  
  649. i = 1
  650. while i < 2:
  651.     print(i)
  652.     i += 1
  653. else:
  654.     print("else:", i)
  655. # 1
  656. # else: 2
  657.  
  658. '''
  659. loop's else branch is always executed once, regardless of whether the loop has entered its body or not
  660. '''
  661.  
  662. i = 111
  663. for i in range(2, 1):
  664.     print(i)
  665. else:
  666.     print("else:", i) # else: 111
  667.  
  668. '''
  669. 1. There are two types of loops in Python: while and for:
  670.  
  671. the while loop executes a statement or a set of statements as long as a specified boolean condition is true, e.g.:
  672.  
  673. # Example 1
  674. while True:
  675.    print("Stuck in an infinite loop.")
  676.  
  677. # Example 2
  678. counter = 5
  679. while counter > 2:
  680.    print(counter)
  681.    counter -= 1
  682.  
  683.  
  684. the for loop executes a set of statements many times; it's used to iterate over a sequence (e.g., a list, a dictionary, a tuple, or a set - you will learn about them soon) or other objects that are iterable (e.g., strings). You can use the for loop to iterate over a sequence of numbers using the built-in range function. Look at the examples below:
  685.  
  686. # Example 1
  687. word = "Python"
  688. for letter in word:
  689.    print(letter, end="*")
  690.  
  691. # Example 2
  692. for i in range(1, 10):
  693.    if i % 2 == 0:
  694.        print(i)
  695.  
  696.  
  697. 2. You can use the break and continue statements to change the flow of a loop:
  698.  
  699. You use break to exit a loop, e.g.:
  700.  
  701. text = "OpenEDG Python Institute"
  702. for letter in text:
  703.    if letter == "P":
  704.        break
  705.    print(letter, end="")
  706.  
  707.  
  708. You use continue to skip the current iteration, and continue with the next iteration, e.g.:
  709.  
  710. text = "pyxpyxpyx"
  711. for letter in text:
  712.    if letter == "x":
  713.        continue
  714.    print(letter, end="")
  715.  
  716. 3. The while and for loops can also have an else clause in Python. The else clause executes after the loop finishes its execution as long as it has not been terminated by break, e.g.:
  717.  
  718. n = 0
  719.  
  720. while n != 3:
  721.    print(n)
  722.    n += 1
  723. else:
  724.    print(n, "else")
  725.  
  726. print()
  727.  
  728. for i in range(0, 3):
  729.    print(i)
  730. else:
  731.    print(i, "else")
  732.  
  733.  
  734. 4. The range() function generates a sequence of numbers. It accepts integers and returns range objects. The syntax of range() looks as follows: range(start, stop, step), where:
  735.  
  736. start is an optional parameter specifying the starting number of the sequence (0 by default)
  737. stop is an optional parameter specifying the end of the sequence generated (it is not included),
  738. and step is an optional parameter specifying the difference between the numbers in the sequence (1 by default.)
  739. Example code:
  740.  
  741. for i in range(3):
  742.    print(i, end=" ")  # Outputs: 0 1 2
  743.  
  744. for i in range(6, 1, -2):
  745.    print(i, end=" ")  # Outputs: 6, 4, 2
  746. '''
  747.  
  748. '''
  749. and is binary operator with a priority that is lower than the one expressed by the comparison operators
  750. or is binary operator with a lower priority than and
  751. not is unary operator performing a logical negation with priority very high, same as the unary + and -.
  752.  
  753. not (p and q) == (not p) or (not q)
  754. not (p or q) == (not p) and (not q)
  755.  
  756. Bitwise Operators: arguments of these operators must be integers
  757. & (ampersand) - bitwise conjunction;
  758. | (bar) - bitwise disjunction;
  759. ~ (tilde) - bitwise negation;
  760. ^ (caret) - bitwise exclusive or (xor).
  761.  
  762. & requires exactly two 1s to provide 1 as the result;
  763. | requires at least one 1 to provide 1 as the result;
  764. ^ requires exactly one 1 to provide 1 as the result.
  765.  
  766. x = x & y  =>   x &= y
  767. x = x | y  =>   x |= y
  768. x = x ^ y  =>   x ^= y
  769. '''
  770. Binary left shift and binary right shift is applied only to integer
  771.  
  772. shifting a value one bit to the left thus corresponds to multiplying it by two; respectively, shifting one bit to the right is like dividing by two (notice that the rightmost bit is lost).
  773.  
  774. value << bits
  775. value >> bits
  776.  
  777. The left argument of these operators is an integer value whose bits are shifted. The right argument determines the size of the shift.
  778.  
  779. updated priority table, containing all the operators introduced so far:
  780.  
  781. Priority    Operator   
  782. 1   ~, +, - unary
  783. 2   ** 
  784. 3   *, /, //, %
  785. 4   +, -    binary
  786. 5   <<, >> 
  787. 6   <, <=, >, >=   
  788. 7   ==, != 
  789. 8   &  
  790. 9   |  
  791. 10  =, +=, -=, *=, /=, %=, &=, ^=, |=, >>=, <<=
  792.  
  793. 17 >> 117 // 2 (17 floor-divided by 2 to the power of 1)8 (shifting to the right by one bit is the same as integer division by two)
  794. 17 << 217 * 4 (17 multiplied by 2 to the power of 2)68 (shifting to the left by two bits is the same as integer multiplication by four)
  795. '''
  796.  
  797. print(17, 17 << 2, 17 >> 1) # 17 68 8
  798.  
  799. '''
  800. Key takeaways
  801.  
  802. 1. Python supports the following logical operators:
  803.  
  804. andif both operands are true, the condition is true, e.g., (True and True) is True,
  805. orif any of the operands are true, the condition is true, e.g., (True or False) is True,
  806. not → returns false if the result is true, and returns true if the result is false, e.g., not True is False.
  807. 2. You can use bitwise operators to manipulate single bits of data. The following sample data:
  808.  
  809. x = 15, which is 0000 1111 in binary,
  810. y = 16, which is 0001 0000 in binary.
  811. will be used to illustrate the meaning of bitwise operators in Python. Analyze the examples below:
  812.  
  813. & does a bitwise and, e.g., x & y = 0, which is 0000 0000 in binary,
  814. | does a bitwise or, e.g., x | y = 31, which is 0001 1111 in binary,
  815. ˜  does a bitwise not, e.g., ˜ x = 240*, which is 1111 0000 in binary,
  816. ^ does a bitwise xor, e.g., x ^ y = 31, which is 0001 1111 in binary,
  817. >> does a bitwise right shift, e.g., y >> 1 = 8, which is 0000 1000 in binary,
  818. << does a bitwise left shift, e.g., y << 3 = , which is 1000 0000 in binary,
  819.  
  820. * -16 (decimal from signed 2's complement) -- read more about the Two's complement operation.
  821. '''
  822.  
  823. x = 1
  824. y = 0
  825. z = ((x == y) and (x == y)) or not(x == y)
  826. print(not(z)) # False
  827.  
  828.  
  829. x = 4
  830. y = 1
  831. a = x & y
  832. b = x | y
  833. c = ~x  # tricky!
  834. d = x ^ 5
  835. e = x >> 2
  836. f = x << 2
  837. print(a, b, c, d, e, f) # 0 5 -5 1 1 16
  838.  
  839. '''
  840. Lists: Elements may have different types, indexing starting from zero any expression can be index
  841.  
  842. You can't access an element which doesn't exist
  843. '''
  844.  
  845. numbers = [10, 5, 7, 99, 17]
  846. print(len([0, 1])) # 2
  847. del numbers[1]
  848. print(numbers[4]) # IndexError: list index out of range
  849. print(numbers[-1]) # 17
  850. print(numbers[-2]) # 99
  851. print(numbers[-(len(numbers))]) # 10
  852. numbers.append(4) # [10, 7, 99, 17, 4]
  853. numbers.insert(0, 222) # [222, 10, 7, 99, 17, 4]
  854.  
  855. for i in range(5):
  856.    print(i) # 1 2 3 4 5
  857.  
  858. for i in [1, 2, 3, 4, 5]:
  859.    print(i) # 1 2 3 4 5
  860.  
  861. a = 1
  862. b = 2
  863. a, b = b, a
  864.  
  865. m = [10, 1, 8, 3, 5]
  866. m[0], m[4] = m[4], m[0]
  867. m[1], m[3] = m[3], m[1]
  868. print(m)
  869.  
  870. my_list = [10, 1, 8, 3, 5]
  871. for i in range(len(my_list) // 2):
  872.    my_list[i], my_list[length - i - 1] = my_list[length - i - 1], my_list[i] # [5, 3, 8, 1, 10]
  873.  
  874. '''
  875. 1. The list is a type of data in Python used to store multiple objects. It is an ordered and mutable collection of comma-separated items between square brackets, e.g.:
  876.  
  877. my_list = [1, None, True, "I am a string", 256, 0]
  878.  
  879.  
  880. 2. Lists can be indexed and updated, e.g.:
  881.  
  882. my_list = [1, None, True, 'I am a string', 256, 0]
  883. print(my_list[3])  # outputs: I am a string
  884. print(my_list[-1])  # outputs: 0
  885.  
  886. my_list[1] = '?'
  887. print(my_list)  # outputs: [1, '?', True, 'I am a string', 256, 0]
  888.  
  889. my_list.insert(0, "first")
  890. my_list.append("last")
  891. print(my_list)  # outputs: ['first', 1, '?', True, 'I am a string', 256, 0, 'last']
  892.  
  893.  
  894. 3. Lists can be nested, e.g.:
  895.  
  896. my_list = [1, 'a', ["list", 64, [0, 1], False]]
  897.  
  898. You will learn more about nesting in module 3.1.7 - for the time being, we just want you to be aware that something like this is possible, too.
  899.  
  900. 4. List elements and lists can be deleted, e.g.:
  901.  
  902. my_list = [1, 2, 3, 4]
  903. del my_list[2]
  904. print(my_list)  # outputs: [1, 2, 4]
  905.  
  906. del my_list  # deletes the whole list
  907.  
  908.  
  909. Again, you will learn more about this in module 3.1.6 - don't worry. For the time being just try to experiment with the above code and check how changing it affects the output.
  910.  
  911. 5. Lists can be iterated through using the for loop, e.g.:
  912.  
  913. my_list = ["white", "purple", "blue", "yellow", "green"]
  914.  
  915. for color in my_list:
  916.    print(color)
  917.  
  918.  
  919. 6. The len() function may be used to check the list's length, e.g.:
  920.  
  921. my_list = ["white", "purple", "blue", "yellow", "green"]
  922. print(len(my_list))  # outputs 5
  923.  
  924. del my_list[2]
  925. print(len(my_list))  # outputs 4
  926.  
  927.  
  928. 7. A typical function invocation looks as follows: result = function(arg), while a typical method invocation looks like this:result = data.method(arg).
  929. '''
  930. lst = [1, 2, 3, 4, 5]
  931. lst.insert(1, 6)
  932. del lst[0]
  933. lst.append(1)
  934. print(lst) # [6, 2, 3, 4, 5, 1]
  935.  
  936. lst = [1, 2, 3, 4, 5]
  937. lst_2 = []
  938. add = 0
  939. for number in lst:
  940.    add += number
  941.    lst_2.append(add)
  942. print(lst_2) # [1, 3, 6, 10, 15]
  943.  
  944. lst = []
  945. del lst
  946. print(lst) # NameError: name 'lst' is not defined
  947.  
  948. lst = [1, [2, 3], 4]
  949. print(lst[1], len(lst)) # [2, 3] 3
  950.  
  951. '''
  952. Bubble Sort: Iterate in bubbles swapping neighbors
  953. '''
  954.  
  955. arr = [64, 34, 25, 12, 22, 11, 90]
  956. for i in range(len(arr)-1):
  957.        for j in range(0, len(arr)-i-1):
  958.            if arr[j] > arr[j + 1] :
  959.                arr[j], arr[j + 1] = arr[j + 1], arr[j]
  960. print(arr) # [11, 12, 22, 25, 34, 64, 90]
  961.  
  962.  
  963. my_list = [8, 10, 6, 2, 4]
  964. my_list.sort()
  965. print(my_list) # [2, 4, 6, 8, 10]
  966.  
  967. lst = [5, 3, 1, 2, 4]
  968. lst.reverse()
  969. print(lst)  # outputs: [4, 2, 1, 3, 5]
  970.  
  971. lst = ["D", "F", "A", "Z"]
  972. lst.sort()
  973. print(lst) # ['A', 'D', 'F', 'Z']
  974.  
  975. a = 3
  976. b = 1
  977. c = 2
  978. lst = [a, c, b]
  979. lst.sort()
  980. print(lst) # [1, 2, 3]
  981.  
  982. a = "A"
  983. b = "B"
  984. c = "C"
  985. d = " "
  986. lst = [a, b, c, d]
  987. lst.reverse()
  988. print(lst) # [' ', 'C', 'B', 'A']
  989. lst.sort()
  990. print(lst) # [' ', 'A', 'B', 'C']
  991.  
  992. list_1 = [1] # creates a one-element list named list_1;
  993. list_2 = list_1 # assigns it to a new list named list_2;
  994. list_1[0] = 2 # changes the only element of list_1;
  995. print(list_2) # [2] # prints out list_2.
  996.  
  997. '''
  998. name of a list is the name of a memory location where the list is stored.
  999. assignment: list_2 = list_1 copies the name of the array, not its contents. In effect, the two names (list_1 and list_2) identify the same location in the computer memory. Modifying one of them affects the other, and vice versa.
  1000. '''
  1001.  
  1002. '''
  1003. A slice is an element of Python syntax that allows you to make a brand new copy of a list, or parts of a list.
  1004.  
  1005. my_list[start:end]
  1006.  
  1007. start is the index of the first element included in the slice;
  1008. end is the index of the first element not included in the slice.
  1009.  
  1010. new list will have end - start (ex 3 - 1 = 2) elements
  1011. '''
  1012.  
  1013. list_1 = [1]
  1014. list_2 = list_1[:]      # Copying the entire list.
  1015. list_1[0] = 2
  1016. print(list_2)
  1017.  
  1018. my_list = [10, 8, 6, 4, 2]
  1019. new_list = my_list[1:3] # [8, 6]
  1020. new_list = my_list[0:5] # [10, 8, 6, 4, 2]
  1021. new_list = my_list[:] # [10, 8, 6, 4, 2] # my_list[0:len(my_list)]
  1022. new_list = my_list[0:] # [10, 8, 6, 4, 2] # my_list[0:len(my_list)]
  1023. new_list = my_list[:5] # [10, 8, 6, 4, 2] # my_list[0:5]
  1024. new_list = my_list[1:5] # [8, 6, 4, 2]
  1025. new_list = my_list[1:4] # [8, 6, 4]
  1026. print(new_list)
  1027.  
  1028. my_list = [10, 8, 6, 4, 2]
  1029. new_list = my_list[1:-1] # [8, 6, 4]
  1030. new_list = my_list[-1:1] # []
  1031. print(new_list)
  1032.  
  1033. my_list = [10, 8, 6, 4, 2]
  1034. del my_list[1:3]   # [10, 4, 2]
  1035. del my_list[:]   # []
  1036. print(my_list) # [10, 4, 2]
  1037.  
  1038. my_list = [10, 8, 6, 4, 2]
  1039. del my_list # delete the list itself, not its content.
  1040. print(my_list) # NameError: name 'my_list' is not defined
  1041.  
  1042. '''
  1043. elem in my_list
  1044. elem not in my_list
  1045. '''
  1046.  
  1047. my_list = [0, 3, 12, 8, 2]
  1048. print(5 in my_list) # False
  1049. print(5 not in my_list) # True
  1050. print(12 in my_list) # True
  1051.  
  1052. my_list = [3, 11, 5, 1, 9, 17, 7, 15, 13]
  1053. largest = my_list[0]
  1054. for i in range(1, len(my_list)):
  1055.    if my_list[i] > largest:
  1056.        largest = my_list[i]
  1057. print(largest) # 17
  1058.  
  1059. my_list = [17, 3, 11, 5, 1, 9, 7, 15, 13]
  1060. largest = my_list[0]
  1061. for i in my_list[1:]:
  1062.    if i > largest:
  1063.        largest = i
  1064. print(largest) # 17
  1065.  
  1066. my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  1067. to_find = 5
  1068. found = False
  1069. for i in range(len(my_list)):
  1070.    found = my_list[i] == to_find
  1071.    if found:
  1072.        print("Element found at index", i) # Element found at index 4
  1073.        break
  1074.  
  1075. drawn = [5, 11, 9, 42, 3, 49]
  1076. bets = [3, 7, 11, 42, 34, 49]
  1077. hits = 0
  1078. for number in bets:
  1079.    if number in drawn:
  1080.        hits += 1
  1081. print(hits) # 4
  1082.  
  1083. '''
  1084. 1. If you have a list l1, then the following assignment: l2 = l1 does not make a copy of the l1 list, but makes the variables l1 and l2 point to one and the same list in memory. For example:
  1085.  
  1086. vehicles_one = ['car', 'bicycle', 'motor']
  1087. print(vehicles_one) # outputs: ['car', 'bicycle', 'motor']
  1088.  
  1089. vehicles_two = vehicles_one
  1090. del vehicles_one[0] # deletes 'car'
  1091. print(vehicles_two) # outputs: ['bicycle', 'motor']
  1092.  
  1093.  
  1094. 2. If you want to copy a list or part of the list, you can do it by performing slicing:
  1095.  
  1096. colors = ['red', 'green', 'orange']
  1097.  
  1098. copy_whole_colors = colors[:]  # copy the entire list
  1099. copy_part_colors = colors[0:2]  # copy part of the list
  1100.  
  1101.  
  1102. 3. You can use negative indices to perform slices, too. For example:
  1103.  
  1104. sample_list = ["A", "B", "C", "D", "E"]
  1105. new_list = sample_list[2:-1]
  1106. print(new_list)  # outputs: ['C', 'D']
  1107.  
  1108.  
  1109. 4. The start and end parameters are optional when performing a slice: list[start:end], e.g.:
  1110.  
  1111. my_list = [1, 2, 3, 4, 5]
  1112. slice_one = my_list[2: ]
  1113. slice_two = my_list[ :2]
  1114. slice_three = my_list[-2: ]
  1115.  
  1116. print(slice_one)  # outputs: [3, 4, 5]
  1117. print(slice_two)  # outputs: [1, 2]
  1118. print(slice_three)  # outputs: [4, 5]
  1119.  
  1120.  
  1121. 5. You can delete slices using the del instruction:
  1122.  
  1123. my_list = [1, 2, 3, 4, 5]
  1124. del my_list[0:2]
  1125. print(my_list)  # outputs: [3, 4, 5]
  1126.  
  1127. del my_list[:]
  1128. print(my_list)  # deletes the list content, outputs: []
  1129.  
  1130.  
  1131. 6. You can test if some items exist in a list or not using the keywords in and not in, e.g.:
  1132.  
  1133. my_list = ["A", "B", 1, 2]
  1134.  
  1135. print("A" in my_list)  # outputs: True
  1136. print("C" not in my_list)  # outputs: True
  1137. print(2 not in my_list)  # outputs: False
  1138. '''
  1139.  
  1140. list_1 = ["A", "B", "C"]
  1141. list_2 = list_1
  1142. list_3 = list_2
  1143. del list_1[0]
  1144. del list_2[0]
  1145. print(list_3) # ['C']
  1146.  
  1147. list_1 = ["A", "B", "C"]
  1148. list_2 = list_1
  1149. list_3 = list_2
  1150. del list_1[0]
  1151. del list_2
  1152. print(list_3) # ['B', 'C']
  1153.  
  1154. list_1 = ["A", "B", "C"]
  1155. list_2 = list_1
  1156. list_3 = list_2
  1157. del list_1[0]
  1158. del list_2[:]
  1159. print(list_3) # []
  1160.  
  1161. list_1 = ["A", "B", "C"]
  1162. list_2 = list_1[:]
  1163. list_3 = list_2[:]
  1164. del list_1[0]
  1165. del list_2[0]
  1166. print(list_3) # ['A', 'B', 'C']
  1167.  
  1168. my_list = [1, 2, "in", True, "ABC"]
  1169. print(1 ??? my_list)  # outputs True
  1170. print("A" ??? my_list)  # outputs True
  1171. print(3 ??? my_list)  # outputs True
  1172. print(False ??? my_list)  # outputs False
  1173.  
  1174. print([x ** 2 for x in range(10)]) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  1175. print([2 ** i for i in range(8)]) # [1, 2, 4, 8, 16, 32, 64, 128]
  1176. print([x for x in [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] if x % 2 != 0 ]) # [1, 9, 25, 49, 81]
  1177. print([[0.0 for h in range(2)] for d in range(3)]) # [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]]
  1178. print([[['Hi' for r in range(2)] for f in range(2)] for t in range(2)]) # [[['Hi', 'Hi'], ['Hi', 'Hi']], [['Hi', 'Hi'], ['Hi', 'Hi']]]
  1179.  
  1180. '''
  1181. 1. List comprehension allows you to create new lists from existing ones in a concise and elegant way. The syntax of a list comprehension looks as follows:
  1182.  
  1183. [expression for element in list if conditional]
  1184.  
  1185.  
  1186. which is actually an equivalent of the following code:
  1187.  
  1188. for element in list:
  1189.     if conditional:
  1190.         expression
  1191.  
  1192.  
  1193. Here's an example of a list comprehension - the code creates a five-element list filled with with the first five natural numbers raised to the power of 3:
  1194.  
  1195. cubed = [num ** 3 for num in range(5)]
  1196. print(cubed)  # outputs: [0, 1, 8, 27, 64]
  1197.  
  1198.  
  1199. 2. You can use nested lists in Python to create matrices (i.e., two-dimensional lists). For example:
  1200.  
  1201. Table - a two-dimensional array
  1202.  
  1203. # A four-column/four-row table - a two dimensional array (4x4)
  1204.  
  1205. table = [[":(", ":)", ":(", ":)"],
  1206.         [":)", ":(", ":)", ":)"],
  1207.         [":(", ":)", ":)", ":("],
  1208.         [":)", ":)", ":)", ":("]]
  1209.  
  1210. print(table)
  1211. print(table[0][0])  # outputs: ':('
  1212. print(table[0][3])  # outputs: ':)'
  1213.  
  1214. 3. You can nest as many lists in lists as you want, and therefore create n-dimensional lists, e.g., three-, four- or even sixty-four-dimensional arrays. For example:
  1215.  
  1216. Cube - a three-dimensional array
  1217.  
  1218. # Cube - a three-dimensional array (3x3x3)
  1219.  
  1220. cube = [[[':(', 'x', 'x'],
  1221.         [':)', 'x', 'x'],
  1222.         [':(', 'x', 'x']],
  1223.  
  1224.        [[':)', 'x', 'x'],
  1225.         [':(', 'x', 'x'],
  1226.         [':)', 'x', 'x']],
  1227.  
  1228.        [[':(', 'x', 'x'],
  1229.         [':)', 'x', 'x'],
  1230.         [':)', 'x', 'x']]]
  1231.  
  1232. print(cube)
  1233. print(cube[0][0][0])  # outputs: ':('
  1234. print(cube[2][2][0])  # outputs: ':)'
  1235.  
  1236. '''
  1237.  
  1238. for i in range (-1, 1):
  1239.     print('@') # @ @
  1240.  
  1241. z = 10
  1242. y = 0
  1243. x = z > y or z ==y
  1244. print(x) # True
  1245.  
  1246. print("We start here.")
  1247. message()
  1248. print("We end here.")
  1249. def message():
  1250.     print("Enter a value: ") # NameError: name 'message' is not defined
  1251.  
  1252. '''
  1253. Python reads your code from top to bottom.
  1254. '''
  1255. def hi():
  1256.     print("hi")
  1257. hi(5) # TypeError: hi() takes 0 positional arguments but 1 was given
  1258.  
  1259. '''
  1260. specifying one or more parameters in a function's definition is also a requirement, and you have to fulfil it during invocation. You must provide as many arguments as there are defined parameters.
  1261.  
  1262. Failure to do so will cause an error.
  1263. '''
  1264. def message(number):
  1265.     print("Enter a number:", number)
  1266. message() # TypeError: message() missing 1 required positional argument: 'number'
  1267.  
  1268. def message(number):
  1269.     print("Enter a number:", number)
  1270. number = 1234
  1271. message(1) # 1
  1272. print(number) # 1234
  1273.  
  1274. def introduction(first_name, last_name):
  1275.     print("Hello, my name is", first_name, last_name)
  1276. introduction(first_name = "James", last_name = "Bond") # Hello, my name is James Bond
  1277. introduction(last_name = "Skywalker", first_name = "Luke") # Hello, my name is Luke Skywalker
  1278.  
  1279. def introduction(first_name, last_name):
  1280.     print("Hello, my name is", first_name, last_name)
  1281. introduction(surname="Skywalker", first_name="Luke") # TypeError: introduction() got an unexpected keyword argument 'surname'
  1282.  
  1283. # positional arguments go before keyword arguments.
  1284. def adding(a, b, c):
  1285.     print(a, "+", b, "+", c, "=", a + b + c)
  1286. adding(3, c = 1, b = 2) # 6
  1287. adding(3, a = 1, b = 2) # TypeError: adding() got multiple values for argument 'a'
  1288.  
  1289. def rating(rating, type="movie"): # default (predefined) values for arguments
  1290.     print(rating, type)
  1291. rating(2) # 2 movie
  1292.  
  1293. '''
  1294. 1. You can pass information to functions by using parameters. Your functions can have as many parameters as you need.
  1295.  
  1296. An example of a one-parameter function:
  1297.  
  1298. def hi(name):
  1299.    print("Hi,", name)
  1300.  
  1301. hi("Greg")
  1302.  
  1303.  
  1304. An example of a two-parameter function:
  1305.  
  1306. def hi_all(name_1, name_2):
  1307.    print("Hi,", name_2)
  1308.    print("Hi,", name_1)
  1309.  
  1310. hi_all("Sebastian", "Konrad")
  1311.  
  1312.  
  1313. An example of a three-parameter function:
  1314.  
  1315. def address(street, city, postal_code):
  1316.    print("Your address is:", street, "St.,", city, postal_code)
  1317.  
  1318. s = input("Street: ")
  1319. p_c = input("Postal Code: ")
  1320. c = input("City: ")
  1321.  
  1322. address(s, c, p_c)
  1323.  
  1324.  
  1325. 2. You can pass arguments to a function using the following techniques:
  1326.  
  1327. positional argument passing in which the order of arguments passed matters (Ex. 1),
  1328. keyword (named) argument passing in which the order of arguments passed doesn't matter (Ex. 2),
  1329. a mix of positional and keyword argument passing (Ex. 3).
  1330. Ex. 1
  1331. def subtra(a, b):
  1332.    print(a - b)
  1333.  
  1334. subtra(5, 2)    # outputs: 3
  1335. subtra(2, 5)    # outputs: -3
  1336.  
  1337.  
  1338. Ex. 2
  1339. def subtra(a, b):
  1340.    print(a - b)
  1341.  
  1342. subtra(a=5, b=2)    # outputs: 3
  1343. subtra(b=2, a=5)    # outputs: 3
  1344.  
  1345. Ex. 3
  1346. def subtra(a, b):
  1347.    print(a - b)
  1348.  
  1349. subtra(5, b=2)    # outputs: 3
  1350. subtra(5, 2)    # outputs: 3
  1351.  
  1352.  
  1353. It's important to remember that positional arguments mustn't follow keyword arguments. That's why if you try to run the following snippet:
  1354.  
  1355. def subtra(a, b):
  1356.    print(a - b)
  1357.  
  1358. subtra(5, b=2)    # outputs: 3
  1359. subtra(a=5, 2)    # Syntax Error
  1360.  
  1361. Python will not let you do it by signalling a SyntaxError.
  1362.  
  1363. 3. You can use the keyword argument passing technique to pre-define a value for a given argument:
  1364.  
  1365. def name(first_name, last_name="Smith"):
  1366.    print(first_name, last_name)
  1367.  
  1368. name("Andy")    # outputs: Andy Smith
  1369. name("Betty", "Johnson")    # outputs: Betty Johnson (the keyword argument replaced by "Johnson")
  1370. '''
  1371. def add_numbers(a, b=2, c):
  1372.     print(a + b + c)
  1373. add_numbers(a=1, c=3) # SyntaxError: non-default argument follows default argument
  1374.  
  1375. print(None + 2) # TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
  1376.  
  1377. '''
  1378. None is a keyword.
  1379.  
  1380. If a function doesn't return a certain value using a return expression clause, it is assumed that it implicitly returns None.
  1381.  
  1382. There are only two kinds of circumstances when None can be safely used:
  1383.  
  1384. when you assign it to a variable (or return it as a function's result)
  1385. when you compare it with a variable to diagnose its internal state.
  1386. Just like here:
  1387. '''
  1388.  
  1389. value = None
  1390. if value is None:
  1391.     print("Sorry, you don't carry any value")
  1392.  
  1393. def strange_function(n):
  1394.     if(n % 2 == 0):
  1395.         return True
  1396. print(strange_function(2)) # True
  1397. print(strange_function(1)) # None
  1398.  
  1399. def list_sum(lst):
  1400.     s = 0
  1401.     for elem in lst:
  1402.         s += elem
  1403.     return s
  1404. print(list_sum([5, 4, 3])) # 12
  1405. print(list_sum(5)) # TypeError: 'int' object is not iterable
  1406.  
  1407. def strange_list_fun(n):
  1408.     strange_list = []
  1409.     for i in range(0, n):
  1410.         strange_list.insert(0, i)
  1411.     return strange_list
  1412. print(strange_list_fun(5)) # [4, 3, 2, 1, 0]
  1413.  
  1414. '''
  1415. 1. You can use the return keyword to tell a function to return some value. The return statement exits the function, e.g.:
  1416.  
  1417. def multiply(a, b):
  1418.    return a * b
  1419.  
  1420. print(multiply(3, 4))    # outputs: 12
  1421.  
  1422.  
  1423. def multiply(a, b):
  1424.    return
  1425.  
  1426. print(multiply(3, 4))    # outputs: None
  1427.  
  1428.  
  1429. 2. The result of a function can be easily assigned to a variable, e.g.:
  1430.  
  1431. def wishes():
  1432.    return "Happy Birthday!"
  1433.  
  1434. w = wishes()
  1435.  
  1436. print(w)    # outputs: Happy Birthday!
  1437.  
  1438. Look at the difference in output in the following two examples:
  1439.  
  1440. # Example 1
  1441. def wishes():
  1442.    print("My Wishes")
  1443.    return "Happy Birthday"
  1444.  
  1445. wishes()    # outputs: My Wishes
  1446.  
  1447.  
  1448. # Example 2
  1449. def wishes():
  1450.    print("My Wishes")
  1451.    return "Happy Birthday"
  1452.  
  1453. print(wishes())
  1454.  
  1455. # outputs: My Wishes
  1456. #          Happy Birthday
  1457.  
  1458.  
  1459. 3. You can use a list as a function's argument, e.g.:
  1460.  
  1461. def hi_everybody(my_list):
  1462.    for name in my_list:
  1463.        print("Hi,", name)
  1464.  
  1465. hi_everybody(["Adam", "John", "Lucy"])
  1466.  
  1467.  
  1468. 4. A list can be a function result, too, e.g.:
  1469.  
  1470. def create_list(n):
  1471.    my_list = []
  1472.    for i in range(n):
  1473.        my_list.append(i)
  1474.    return my_list
  1475.  
  1476. print(create_list(5))
  1477.  
  1478. def hi():
  1479.    return
  1480.    print("Hi!")
  1481. print(hi()) # None
  1482.  
  1483. def is_int(data):
  1484.    if type(data) == int:
  1485.        return True
  1486.    elif type(data) == float:
  1487.        return False
  1488. print(is_int(5)) # true
  1489. print(is_int(5.0)) # False
  1490. print(is_int("5")) # None
  1491.  
  1492. def hi():
  1493.    return
  1494.    print("Hi!")
  1495. print(hi()) # None
  1496.  
  1497. def is_int(data):
  1498.    if type(data) == int:
  1499.        return True
  1500.    elif type(data) == float:
  1501.        return False
  1502.  
  1503. print(is_int(5)) # True
  1504. print(is_int(5.0)) # False
  1505. print(is_int("5")) # None
  1506.  
  1507. def even_num_lst(ran):
  1508.    lst = []
  1509.    for num in range(ran):
  1510.        if num % 2 == 0:
  1511.            lst.append(num)
  1512.    return lst
  1513. print(even_num_lst(11)) # [0, 2, 4, 6, 8, 10]
  1514.  
  1515. def list_updater(lst):
  1516.    upd_list = []
  1517.    for elem in lst:
  1518.        elem **= 2
  1519.        upd_list.append(elem)
  1520.    return upd_list
  1521. foo = [1, 2, 3, 4, 5]
  1522. print(list_updater(foo)) # [1, 4, 9, 16, 25]
  1523.  
  1524. def scope_test():
  1525.    x = 123
  1526. scope_test()
  1527. print(x) # NameError: name 'x' is not defined
  1528.  
  1529. def my_function():
  1530.    print("Inside ", var) # Inside  1
  1531. var = 1
  1532. my_function()
  1533. print("Outside ", var) # Outside  1
  1534.  
  1535. '''
  1536. a variable existing outside a function has a scope inside the functions' bodies.
  1537. '''
  1538.  
  1539. def my_function():
  1540.     var = 2
  1541.     print("varInside", var) # varInside 2
  1542. var = 1
  1543. my_function()
  1544. print("varOutside", var) # varOutside 1
  1545.  
  1546. '''
  1547. A variable existing outside a function has a scope inside the functions' bodies, excluding those of them which define a variable of the same name.
  1548. '''
  1549.  
  1550. def my_function():
  1551.     global var
  1552.     var = 2
  1553.     print("varInside", var) # varInside 2
  1554. var = 1
  1555. my_function()
  1556. print("varOutside", var) # varOutside 2
  1557.  
  1558. def my_function(n):
  1559.     print("received", n) # received 1
  1560.     n += 1
  1561.     print("updated", n) # updated 2
  1562. var = 1
  1563. my_function(var)
  1564. print('original outside', var) # original outside 1
  1565.  
  1566. '''
  1567. changing the parameter's value doesn't propagate outside the function (in any case, not when the variable is a scalar, like in the example).
  1568. Function receives the argument's value, not the argument itself. This is true for scalars.
  1569. '''
  1570.  
  1571. def my_function(my_list_1):
  1572.     print("Print #1:", my_list_1) # Print #1: [2, 3]
  1573.     print("Print #2:", my_list_2) # Print #2: [2, 3]
  1574.     my_list_1 = [0, 1]
  1575.     print("Print #3:", my_list_1) # Print #3: [0, 1]
  1576.     print("Print #4:", my_list_2) # Print #4: [2, 3]
  1577. my_list_2 = [2, 3]
  1578. my_function(my_list_2)
  1579. print("Print #5:", my_list_2) # Print #5: [2, 3]
  1580.  
  1581. def my_function(my_list_1):
  1582.     print("Print #1:", my_list_1) # Print #1: [2, 3]
  1583.     print("Print #2:", my_list_2) # Print #2: [2, 3]
  1584.     del my_list_1[0]  # Pay attention to this line.
  1585.     print("Print #3:", my_list_1) # Print #3: [3]
  1586.     print("Print #4:", my_list_2) # Print #4: [3]
  1587. my_list_2 = [2, 3]
  1588. my_function(my_list_2)
  1589. print("Print #5:", my_list_2) # Print #5: [3]
  1590.  
  1591. '''
  1592. if the argument is a list, then changing the value of the corresponding parameter doesn't affect the list (remember: variables containing lists are stored in a different way than scalars),
  1593. but if you change a list identified by the parameter (note: the list, not the parameter!), the list will reflect the change.
  1594.  
  1595. 1. A variable that exists outside a function has a scope inside the function body (Example 1) unless the function defines a variable of the same name (Example 2, and Example 3), e.g.:
  1596.  
  1597. Example 1:
  1598.  
  1599. var = 2
  1600.  
  1601.  
  1602. def mult_by_var(x):
  1603.    return x * var
  1604.  
  1605.  
  1606. print(mult_by_var(7))    # outputs: 14
  1607.  
  1608.  
  1609. Example 2:
  1610.  
  1611. def mult(x):
  1612.    var = 5
  1613.    return x * var
  1614.  
  1615.  
  1616. print(mult(7))    # outputs: 35
  1617.  
  1618.  
  1619. Example 3:
  1620.  
  1621. def mult(x):
  1622.    var = 7
  1623.    return x * var
  1624.  
  1625.  
  1626. var = 3
  1627. print(mult(7))    # outputs: 49
  1628.  
  1629.  
  1630. 2. A variable that exists inside a function has a scope inside the function body (Example 4), e.g.:
  1631.  
  1632. Example 4:
  1633.  
  1634. def adding(x):
  1635.    var = 7
  1636.    return x + var
  1637.  
  1638.  
  1639. print(adding(4))    # outputs: 11
  1640. print(var)    # NameError
  1641.  
  1642.  
  1643. 3. You can use the global keyword followed by a variable name to make the variable's scope global, e.g.:
  1644.  
  1645. var = 2
  1646. print(var)    # outputs: 2
  1647.  
  1648.  
  1649. def return_var():
  1650.    global var
  1651.    var = 5
  1652.    return var
  1653.  
  1654.  
  1655. print(return_var())    # outputs: 5
  1656. print(var)    # outputs: 5
  1657. '''
  1658.  
  1659. def message():
  1660.     alt = 1
  1661.     print("Hello, World!")
  1662. print(alt) # NameError: name 'alt' is not defined
  1663.  
  1664. a = 1
  1665. def fun():
  1666.     a = 2
  1667.     print(a) # 2
  1668. fun()
  1669. print(a) # 1
  1670.  
  1671. a = 1
  1672. def fun():
  1673.     global a
  1674.     a = 2
  1675.     print(a) # 2
  1676. fun()
  1677. a = 3
  1678. print(a) # 3
  1679.  
  1680. a = 1
  1681. def fun():
  1682.     global a
  1683.     a = 2
  1684.     print(a) # 2
  1685. a = 3
  1686. fun()
  1687. print(a) # 2
  1688.  
  1689. def bmi(weight, height):
  1690.     return weight / height ** 2
  1691. print(bmi(52.5, 1.65)) # 19.283746556473833
  1692.  
  1693. def is_a_triangle(a, b, c):
  1694.     if a + b <= c:
  1695.         return False
  1696.     if b + c <= a:
  1697.         return False
  1698.     if c + a <= b:
  1699.         return False
  1700.     return True
  1701. print(is_a_triangle(1, 1, 1))
  1702. print(is_a_triangle(1, 1, 3))
  1703.  
  1704. def is_a_triangle(a, b, c):
  1705.     if a + b <= c or b + c <= a or c + a <= b:
  1706.         return False
  1707.     return True
  1708. print(is_a_triangle(1, 1, 1)) # True
  1709. print(is_a_triangle(1, 1, 3)) # False
  1710.  
  1711. def is_a_triangle(a, b, c):
  1712.     return a + b > c and b + c > a and c + a > b
  1713. print(is_a_triangle(1, 1, 1)) # True
  1714. print(is_a_triangle(1, 1, 3)) # False
  1715.  
  1716. def is_a_triangle(a, b, c):
  1717.     return a + b > c and b + c > a and c + a > b
  1718. def is_a_right_triangle(a, b, c):
  1719.     if not is_a_triangle(a, b, c):
  1720.         return False
  1721.     if c > a and c > b:
  1722.         return c ** 2 == a ** 2 + b ** 2
  1723.     if a > b and a > c:
  1724.         return a ** 2 == b ** 2 + c ** 2
  1725. print(is_a_right_triangle(5, 3, 4)) # True
  1726. print(is_a_right_triangle(1, 3, 4)) # False
  1727.  
  1728. def factorial_function(n):
  1729.     if n < 0:
  1730.         return None
  1731.     if n < 2:
  1732.         return 1
  1733.     product = 1
  1734.     for i in range(2, n + 1):
  1735.         product *= i
  1736.     return product
  1737. for n in range(1, 6):  # testing
  1738.     print(n, factorial_function(n))
  1739. '''
  1740. 1 1
  1741. 2 2
  1742. 3 6
  1743. 4 24
  1744. 5 120
  1745. '''
  1746.  
  1747. def fib(n):
  1748.     if n < 1:
  1749.         return None
  1750.     if n < 3:
  1751.         return 1
  1752.     elem_1 = elem_2 = 1
  1753.     the_sum = 0
  1754.     for i in range(3, n + 1):
  1755.         the_sum = elem_1 + elem_2
  1756.         elem_1, elem_2 = elem_2, the_sum
  1757.     return the_sum
  1758. for n in range(1, 10):  # testing
  1759.     print(n, "->", fib(n))
  1760. '''
  1761. 1 -> 1
  1762. 2 -> 1
  1763. 3 -> 2
  1764. 4 -> 3
  1765. 5 -> 5
  1766. 6 -> 8
  1767. 7 -> 13
  1768. 8 -> 21
  1769. 9 -> 34
  1770. '''
  1771.  
  1772. '''
  1773. Key takeaways
  1774. 1. A function can call other functions or even itself. When a function calls itself, this situation is known as recursion, and the function which calls itself and contains a specified termination condition (i.e., the base case - a condition which doesn't tell the function to make any further calls to that function) is called a recursive function.
  1775.  
  1776. 2. You can use recursive functions in Python to write clean, elegant code, and divide it into smaller, organized chunks. On the other hand, you need to be very careful as it might be easy to make a mistake and create a function which never terminates. You also need to remember that recursive calls consume a lot of memory, and therefore may sometimes be inefficient.
  1777.  
  1778. When using recursion, you need to take all its advantages and disadvantages into consideration.
  1779.  
  1780. The factorial function is a classic example of how the concept of recursion can be put in practice:
  1781.  
  1782. # Recursive implementation of the factorial function.
  1783.  
  1784. def factorial(n):
  1785.    if n == 1:    # The base case (termination condition.)
  1786.        return 1
  1787.    else:
  1788.        return n * factorial(n - 1)
  1789.  
  1790.  
  1791. print(factorial(4)) # 4 * 3 * 2 * 1 = 24
  1792. '''
  1793.  
  1794. def factorial(n):
  1795.     return n * factorial(n - 1)
  1796. print(factorial(4)) # RecursionError: maximum recursion depth exceeded
  1797.  
  1798. def fun(a):
  1799.     if a > 30:
  1800.         return 3
  1801.     else:
  1802.         return a + fun(a + 3)
  1803. print(fun(25)) # 56
  1804.  
  1805.  
  1806.  
  1807.  
  1808.  
  1809.  
  1810.  
  1811.  
Add Comment
Please, Sign In to add comment