Advertisement
RMKhatib

Python Basics Cheat Sheet

Nov 30th, 2021 (edited)
1,429
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 28.11 KB | None | 0 0
  1. Variable name:
  2. Variable name in Python can only contain letters (a - z, A - B), numbers or underscores (_).
  3.  
  4. However, the first character cannot be a number. Hence, you can name your variables user_car or user_car2 but not 2user_car.
  5.  
  6. variable names are case sensitive so user_car is not the same as user_Car or User_car or User_Car.
  7.  
  8. Variable name:
  9.  
  10. Special words can’t be used because these words are built in as a part of python expressions and functions like print, input, if, while, for etc.
  11.  
  12. These words are (False, class, finally, is, return, None, continue,For, lambda, try, True, def, from, nonlocal, while, and, with, as, elif, if, else, or, yield, assert, import, pass, break, except, in, raise)
  13.  
  14. Operators types :
  15.  
  16. Assignment Operators:
  17. give you new value of variable
  18. x = x + 5 can be coded by another way as x + = 5
  19.  
  20. x = x – 5 can be coded by another way as x - = 5
  21.  
  22. Logic operators : give you False or True
  23.  
  24. x > 5 x more than 5 or x >= 5 x more than or equal to 5
  25.  
  26. x < 5 x less than 5 or x >= 5 x less than or equal to 5
  27.  
  28. also
  29.  
  30. x != 5 x not equal to 5
  31.  
  32. Arithmetic Operators:
  33. Suppose x = 3, y = 2
  34.  
  35. Addition:
  36.  
  37. x + y = 5
  38.  
  39. Subtraction:
  40.  
  41. x - y = 1
  42.  
  43. Multiplication:
  44.  
  45. x*y = 6
  46.  
  47. Division:
  48.  
  49. x/y = 1.5
  50.  
  51. Floor Division:
  52.  
  53. x//y = 1 (rounds down the answer to the nearest whole number)
  54.  
  55. Modulus:
  56.  
  57. x%y = 1 (gives the remainder when 3 is divided by 2)
  58.  
  59. Exponent:
  60.  
  61. x**y = 9 (3 to the power of 2)
  62.  
  63. Python data types:
  64.  
  65. Integers:
  66.  
  67. integers are numbers with no decimal parts, such as -3, -1, -2
  68.  
  69. , 0, 6, 10 etc.
  70.  
  71. To declare an integer in Python, simply code as following :
  72.  
  73. Variable_name = interger value
  74.  
  75. Examples:
  76.  
  77. user_car_speed = 100
  78.  
  79. car_ number_plate= 123569
  80.  
  81. Python data types:Floats
  82. Floats are numbers that have decimal parts, such as 1.56, -0.0056,
  83.  
  84. 10.015
  85.  
  86. To declare a float in Python, you will code as following:
  87.  
  88. Variable_name = float value
  89.  
  90. Examples:
  91.  
  92. user_car_speed = 100.55
  93.  
  94. User_height = 1.72
  95.  
  96. Python data types: strings
  97. String are composed of elements like letters, numbers, special characters to build a text. To declare a string, you can either use variable_name =string(single quotes)
  98.  
  99. Variable_name =string(double quotes)
  100.  
  101. Example:
  102.  
  103. user_car_speed =100or user_car_speed =100
  104.  
  105. user_car_color = ‘red !?’ or user_car_color = “red !?”
  106.  
  107. Casting in python:
  108. Casting in python is converting one data type to another data type.
  109.  
  110. Using build_in python functions int(), float(), and str()
  111.  
  112. Examples:
  113.  
  114. user_car_speed =100.55
  115.  
  116. float (user_car_speed) = 100.55
  117.  
  118. int(float (user_car_speed) ) = 100
  119.  
  120. int(user_car_speed) = 100
  121.  
  122. String functions in python:
  123. Format() function :
  124.  
  125. >>>name = “Alexander”
  126.  
  127. >>>car_color = “red.”
  128.  
  129. >>>print(“hello world, my name is”+ “ ”+name+“ ”+“,and my car color is
  130.  
  131. + “ “+car_color)
  132.  
  133. hello world, my name is Alexander ,and my car color is red
  134.  
  135. msg = “hello world, my name is {} , and my car color is {}.format(name, car_color)
  136.  
  137. >>> print(msg)
  138.  
  139. hello world, my name is Alexander ,and my car color is red.
  140.  
  141. String len() function:
  142. >>> print(len(msg))
  143.  
  144. 58
  145.  
  146. >>> print(len(name))
  147.  
  148. 9
  149.  
  150. >>> print(len(name[0:4]))
  151.  
  152. 4
  153.  
  154. >>> Print(Name[0:4])
  155.  
  156. Alex
  157.  
  158. Used to count the entire string or specific character of a string
  159.  
  160. >>>‘This is user car’.count(‘r’)
  161.  
  162. 2
  163.  
  164. In order to count from index 5 to end of string
  165.  
  166. >>>‘This is user car’.count(‘r’, 5)
  167.  
  168. 2
  169.  
  170. In order to count from index 5 to 12
  171. >>> ‘This is user car(‘s’, 5, 12 )
  172.  
  173. 1
  174.  
  175. In orde count ‘T’. There’s only 1 ‘T’ as the function is case sensitive:
  176.  
  177. Example:
  178.  
  179. >>>‘This is user car’.count(‘T’)
  180.  
  181. 1
  182.  
  183. >>>‘This is user car’.count(‘u’)
  184.  
  185. 1
  186.  
  187. >>>‘This is user car’.count(‘U’)
  188.  
  189. 0
  190.  
  191. endswith () and startswith() functions:
  192.  
  193. this function Return True if the string ends with the specified suffix, otherwise return False and it is case-sensitive function.
  194.  
  195. Example:
  196.  
  197. In order to check if a string contain specific suffix like car
  198.  
  199. >>>‘user_car’.endswith(‘car’)
  200.  
  201. True
  202.  
  203. # check from index 4 to end of string
  204.  
  205. >>>‘‘user_car’.endswith(‘car’, 4)
  206.  
  207. True
  208.  
  209. To check from index 5 to 7
  210.  
  211. >>>‘user_car’.endswith(‘car’, 5, 7)
  212.  
  213. False
  214.  
  215. To check from index 4 to 8
  216.  
  217. >>>‘‘user_car’.endswith(‘car’,4, 8)
  218.  
  219. True
  220.  
  221. In order to use a tuple of suffixes as we check from index 4 to 8
  222.  
  223. >>>‘‘user_car’.endswith((‘car’, ‘ar’), 4, 8)
  224.  
  225. True
  226.  
  227. Startswith() like endwiths() but used for bega
  228.  
  229. Find() string function:
  230.  
  231. Return the index in the string where the first occurrence of the substring sub is found
  232.  
  233. Examples:
  234.  
  235. In order to check specific character in a string
  236.  
  237. >>>‘This is user_car’.find(‘i’)
  238.  
  239. 2
  240.  
  241. In order to check from index 2 to end of a string
  242.  
  243. >>>‘This is user_car’.find(‘s’, 2)
  244.  
  245. 3
  246.  
  247. In order to check from index 8 to 12
  248.  
  249. >>>‘This is user_car’.find(‘s’, 8,12 )
  250.  
  251. 9
  252.  
  253. In order to check special character which is not found in string
  254.  
  255. .find() function is like .index() function but differ in the next example:
  256.  
  257. >>> 'This is user_car'.find(‘d’)
  258.  
  259. -1
  260.  
  261. >>> 'This is user_car'.index(‘d’)
  262.  
  263. ValueError
  264.  
  265. islower () and isupper() functions:
  266.  
  267. islower() return True if all characters in the string are lowercase and return False otherwise.
  268.  
  269. [Example]
  270.  
  271. >>>‘abc’.islower()
  272.  
  273. True
  274.  
  275. >>>‘ABc’.islower()
  276.  
  277. False
  278.  
  279. >>>‘ABC’.islower()
  280.  
  281. False
  282.  
  283. isupper() :
  284.  
  285. return True if all characters in the string are uppercase and return False otherwise.
  286.  
  287. Examples:
  288.  
  289. >>>‘ABC’.isupper()
  290.  
  291. True
  292.  
  293. >>>‘AbC’.isupper()
  294.  
  295. False
  296.  
  297. >>>‘abc’.isupper()
  298.  
  299. False
  300.  
  301. lower() and upper() functions:
  302.  
  303. Lower (): the function that convert string case into lower case.
  304.  
  305. Example:
  306.  
  307. >>>‘This is User Car’.lower()
  308.  
  309. this is user car
  310.  
  311. Example:
  312.  
  313. upper (): the function that convert string case into upper case.
  314.  
  315. >>>‘This is User Car’.upper ()
  316.  
  317. THIS IS USER CAR
  318.  
  319. replace() string function:
  320.  
  321. This function return a copy of the string with all occurrences of substring old replaced by new.
  322.  
  323. [Example]
  324.  
  325. >>>‘This is user car’.replace(user, ‘my’)
  326.  
  327. This is my car
  328.  
  329. In order to replace a character many times:
  330.  
  331. >>>‘This is user car’.replace(‘s’, ‘c’, 3)
  332.  
  333. 'Thic ic ucer car'
  334.  
  335. strip() string functions:
  336.  
  337. This function return a copy of the string with the starting orending character removed but If character is not provided, whitespaces will be removed.
  338.  
  339. Example:
  340.  
  341. >>>‘ This is my car’.strip()
  342.  
  343. 'This is my car'
  344.  
  345. >>>‘ This is my car’.strip(‘p’)
  346.  
  347. 'This is a my car'
  348.  
  349. >>>‘This is my car’.strip(‘r’)
  350.  
  351. ‘This is my ca’
  352.  
  353. Print and Input functions:
  354.  
  355. We take and practice print() function which is so simple, now we will take about input() function which store variable data as string
  356.  
  357. Example:
  358.  
  359. >>> user_name = input(“Please enter your name”)
  360.  
  361. Please enter your name
  362.  
  363. >>> Alex
  364.  
  365. >>> print(user_name)
  366.  
  367. Alex
  368.  
  369. How to deal with string special characters in python?
  370.  
  371. In order to print string without errors we should use back slash
  372.  
  373. Character to prevent interfere of these characters with string quotes.
  374.  
  375. Example:
  376.  
  377. >>> msg1= “I’m”
  378.  
  379. >>> msg1= “I\’m”
  380.  
  381. >>> msg2= “I can’t”
  382.  
  383. >>> msg2 =" can\’t”
  384.  
  385. >>> print(msg1+” “ +msg2)
  386.  
  387. I’m can’t
  388.  
  389. Lists in python : []
  390.  
  391. Lists are a collection of data values stored as a list and values are separated by a comma.
  392.  
  393. To declare a list, you code as following :
  394.  
  395. We use square brackets [ ] when declaring a list.
  396.  
  397. list_name = [Multiple values are separated by a comma]
  398.  
  399. Example:
  400.  
  401. user_cars_colors = [‘red’, ‘yellow’, ‘black’, ‘blue’]
  402.  
  403. List commands in python
  404.  
  405. user_cars_colors = [‘red’, ‘yellow’, ‘black’, ‘blue’]
  406.  
  407. To assign user_cars_colors (from index 1 to 3) and print
  408.  
  409. user_cars_colors = user_cars_colors[1:3]
  410.  
  411. print (user_cars_colors)
  412.  
  413. >>>You’ll get [yellow, black]
  414.  
  415. In order to modify the second item in List and print the updated list
  416.  
  417. user_cars_colors[1] = ‘green’
  418.  
  419. print(user_cars_colors)
  420.  
  421. >>> [‘red’, ‘green’, ‘black’, ‘blue’]
  422.  
  423. To append a new item to user_cars_colors and print the list :
  424.  
  425. user_cars_colors.append(“white”)
  426.  
  427. print(user_cars_colors)
  428.  
  429. >>>[‘red’, ‘green’, ‘black’, ‘blue’, ‘white’]
  430.  
  431. To remove the fifth item from user_cars_colors and print the list :
  432.  
  433. del user_cars_colors [4]
  434.  
  435. print(user_cars_colors)
  436.  
  437. >>>[‘red’, ‘green’, ‘black’, ‘blue’]
  438.  
  439. len(): returns how many elements are in a list.
  440.  
  441. Users_cars_speeds = [100, 50, 30, 20,120]
  442.  
  443. len(Users_cars_speeds)
  444.  
  445. >>> 5
  446.  
  447. max() returns the greatest element of the list.
  448.  
  449. Users_cars_speeds = [100, 50, 30, 20,120]
  450.  
  451. max(Users_cars_speeds)
  452.  
  453. >>> 120
  454.  
  455. min(): returns the smallest element in a list.
  456.  
  457. Users_cars_speeds = [100, 50, 30, 20,120]
  458.  
  459. min(Users_cars_speeds)
  460.  
  461. >>> 20
  462.  
  463. sorted() returns a copy of a list ordered from smallest to largest
  464.  
  465. Users_cars_speeds = [100, 50, 30, 20,120]
  466.  
  467. sorted(Users_cars_speeds)
  468.  
  469. >>> 120, 100, 50, 30, 20
  470.  
  471. Sum():
  472.  
  473. returns the sum of the elements in a list.
  474.  
  475. >>> Users_cars_speeds = [100, 50, 30, 20,120]
  476.  
  477. >>>sum(Users_cars_speeds)
  478.  
  479. 320
  480.  
  481. pop():
  482.  
  483. removes the last element from a list and returns it.
  484.  
  485. >>> Users_cars_speeds = [100, 50, 30, 20,120]
  486.  
  487. >>> Users_cars_speeds.pop
  488.  
  489. 120
  490.  
  491. Using range( ) in list:
  492.  
  493. >>> x = range(5)
  494.  
  495. >>> print(x)
  496. [0,1,2,3,4]
  497. Zero = x[0] equals 0, lists are 0-indexed
  498. One = x[1]
  499. Two = x[2]
  500.  
  501. Three = x[3]
  502.  
  503. Four = x[4] fifth element of the x list of range(5).
  504. Four = x[-1] fifth element of the x list of range(5).
  505. >>>
  506.  
  507. Tuples : ()
  508.  
  509. Tuples are just like lists, but we cannot modify their data values.
  510.  
  511. Example:
  512.  
  513. Year_monthes = (“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”)
  514.  
  515. In order to access specific values of a tuple use their indexes like what we do with a list.
  516.  
  517. so, year_monthes [0] = “January”, & year_monthes [-1] = “December”
  518.  
  519. Del() tuple function:
  520.  
  521. This function will delete the whole tuple
  522.  
  523. [Example]
  524.  
  525. year_monthes = (“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”)
  526.  
  527. del year_monthes
  528.  
  529. print (year_monthes)
  530.  
  531. => NameError: name ' year_monthes ' is not defined
  532.  
  533. In use for tuples:
  534.  
  535. This function will check if an item is in a tuple
  536.  
  537. [Example]
  538.  
  539. year_monthes = (“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”)
  540.  
  541. ‘1’ in year_monthes
  542.  
  543. => False
  544.  
  545. ‘January’ in year_monthes
  546.  
  547. => True
  548.  
  549. len( ) tuple function:
  550.  
  551. This function will calculate number of items in tuple.
  552.  
  553. [Example]
  554.  
  555. year_monthes = (“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”)
  556.  
  557. print (len(year_monthes))
  558.  
  559. >>> 12
  560.  
  561. Addition of tuples:
  562.  
  563. year_monthes = (“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”)
  564.  
  565. print (year_monthes +(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))
  566.  
  567. >>>(“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
  568.  
  569. multiplication of tuples:
  570.  
  571. year_monthes = (“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”)
  572.  
  573. print (year_monthes * 2)
  574.  
  575. >>>(“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”, “January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”)
  576.  
  577. Dictionary : {}
  578.  
  579. Dictionary is group of pairs of data values each pair have two parts
  580.  
  581. Dictionary key and data value {key1:value1, key2:value 2, etc….}
  582.  
  583. Example:
  584.  
  585. >>> User_name_and_car_color = { “David”:”red”, “John”:”green”, ”Sara”: “yellow”}
  586.  
  587. In order to declare a dictionary we use dict() method
  588.  
  589. >>> User_name_and_car_color = dict(David = red, John = green, Sara = yellow)
  590.  
  591. {“David”:”red”, “John”:”green”, ”Sara”: “yellow”}
  592.  
  593. In order to add a new item and print the updated dictionary:
  594.  
  595. >>>user_name_and_car_color[“Kate”] = “black”
  596.  
  597. >>>print(user_name_and_car_color)
  598.  
  599. {“Kate”, “black”, “David”:”red”, “John”:”green”, ”Sara”: “yellow”}
  600.  
  601. In order to remove the item with key = “Kate” and print dictionary:
  602.  
  603. >>>del user_name_and_car_color [“Kate”]
  604.  
  605. >>>print(user_name_and_car_color)
  606.  
  607. {“David”:”red”, “John”:”green”, ”Sara”: “yellow”}
  608.  
  609. Example:
  610.  
  611. >>>Print(user_name_and_car_color)
  612.  
  613. {“David”:”red”, “John”:”green”, ”Sara”: “yellow”}
  614.  
  615. In order to print the item with key = “David” code as following:
  616.  
  617. >>>print(user_name_and_car_color[“David”]) red
  618.  
  619. In order to print the item with key =Sara code as following:
  620.  
  621. >>> print(user_name_and_car_color[“Sara”])
  622.  
  623. yellow
  624.  
  625. In order modify the item with key = John and print the dictionary
  626.  
  627. >>> user_name_and_car_color[“John”] = “white”
  628.  
  629. >>>print(user_name_and_car_color”David”)
  630.  
  631. red
  632.  
  633. Dictionary .get() :
  634.  
  635. returns a value for the given key If the key is not found, it’ll return the keyword None.
  636.  
  637. Example:
  638.  
  639. user_name_and_car_color = {“David”:”red”, “John”:”green”, ”Sara”: “yellow”}
  640.  
  641. print(user_name_and_car_color)
  642.  
  643. >>>{“David”:”red”, “John”:”green”, ”Sara”: “yellow”}
  644.  
  645. print(user_name_and_car_color. get(“John”))
  646.  
  647. >>>green
  648.  
  649. user_name_and_car_color = {“David”:”red”,“John”:”green”, ”Sara”: “yellow”}
  650.  
  651. >>>print(user_name_and_car_color)
  652.  
  653. {“David”:”red”, “John”:”green”, ”Sara”: “yellow”}
  654.  
  655. print(user_name_and_car_color. get(“kate”))
  656.  
  657. None
  658.  
  659. Dictionary .del( ):
  660.  
  661. It delete the whole dictionary.
  662.  
  663. Example:
  664.  
  665. >>> user_name_and_car_color = {“David”:”red”, “John”:”green”, ”Sara”: “yellow”}
  666.  
  667. >>> user_name_and_car_color.del()
  668.  
  669. >>>print (user_name_and_car_color)
  670.  
  671. NameError: name 'dic1' is not defined
  672.  
  673. Dictionary .clear( ):
  674.  
  675. It removes all elements of the dictionary, returning an empty dictionary
  676.  
  677. Example:
  678.  
  679. >>> user_name_and_car_color = {“David”:”red”, “John”:”green”, ”Sara”: “yellow”}
  680.  
  681. >>> user_name_and_car_color.clear()
  682.  
  683. >>>print (user_name_and_car_color)
  684.  
  685. { }
  686.  
  687. Dictionary In( ):
  688.  
  689. We use it to check if an item is in a dictionary
  690.  
  691. Example:
  692.  
  693. >>>user_name_and_car_color = {“David”:”red”, “John”:”green”, ”Sara”: “yellow”}
  694.  
  695. Use it on the key
  696.  
  697. >>>David in user_name_and_car_color
  698.  
  699. True
  700.  
  701. >>>Kate in user_name_and_car_color
  702.  
  703. False
  704.  
  705. Use It on the value:
  706.  
  707. Example:
  708.  
  709. user_name_and_car_color = {“David”:”red”, “John”:”green”, ”Sara”: “yellow”}
  710.  
  711. ‘red’ in user_name_and_car_colo.values()
  712.  
  713. => True
  714.  
  715. ‘black’ in user_name_and_car_colo.values()
  716.  
  717. => False
  718.  
  719. Dictionary .items( )
  720.  
  721. We use it to return a list of dictionary’s pairs as tuples
  722.  
  723. [Example]
  724.  
  725. user_name_and_car_color = {“David”:”red”, “John”:”green”, ”Sara”: “yellow”}
  726.  
  727. user_name_and_car_color.items()
  728.  
  729. >>> dict_items([(“David”:”red”), (“John”:”green”), (”Sara”: “yellow”)])
  730.  
  731. Dictionary .len( ):
  732.  
  733. We use it to calculate the number of items in a dictionary
  734.  
  735. Example:
  736.  
  737. >>>year_monthes = {“January” : 1, “February” : 2, “March” : 3, “April”: 4, “May”: 5, “June”: 6, “July”: 7, “August”: 8, “September”: 9, “October”: 10, “November”: 11, “December”: 12 }
  738.  
  739. >>> print (len(year_monthes))
  740.  
  741. 12
  742.  
  743. >>>
  744.  
  745. Dictionary . update( ):
  746.  
  747. We use this to Add one dictionary’s key-values pairs to another. Duplicates are removed.
  748.  
  749. Example:
  750.  
  751. >>> year_monthes = {“January” : 1, “February” : 2, “March” : 3, “April”: 4, “May”: 5, “June”: 6}
  752.  
  753. >>> second_six_year_monthes = {“July”: 7, “August”: 8, “September”: 9, “October”: 10, “November”: 11, “December”: 12}
  754.  
  755. >>> year_monthes.update(second_six_year_monthes)
  756.  
  757. >>> print (year_monthes)
  758.  
  759. {“January” : 1, “February” : 2, “March” : 3, “April”: 4, “May”: 5, “June”: 6, “July”: 7, “August”: 8, “September”: 9, “October”: 10, “November”: 11, “December”: 12 }
  760.  
  761. >>>print second_six_year_monthes
  762.  
  763. {“July”: 7, “August”: 8, “September”: 9, “October”: 10, “November”: 11, “December”: 12}
  764.  
  765. So there is no change in second_six_year_monthes dictionary.
  766.  
  767. Dictionary . values( )
  768.  
  769. This will returns list of the dictionary's values
  770.  
  771. Example:
  772.  
  773. >>> year_monthes = {“January” : 1, “February” : 2, “March” : 3, “April”: 4, “May”: 5, “June”: 6, “July”: 7, “August”: 8, “September”: 9, “October”: 10, “November”: 11, “December”: 12 }
  774.  
  775. >>>year_monthes.values()
  776.  
  777. dict_values([‘1', ‘2‘, ‘3', ‘4‘, ‘5', ‘6‘, ‘7', ‘8‘, ‘9', ‘10‘, ‘11', ‘12‘])
  778.  
  779. Dictionary . keys( )
  780.  
  781. We use it to returns list of the dictionary's keys
  782.  
  783. [Example]
  784.  
  785. >>> year_monthes = {“January” : 1, “February” : 2, “March” : 3, “April”: 4, “May”: 5, “June”: 6, “July”: 7, “August”: 8, “September”: 9, “October”: 10, “November”: 11, “December”: 12 }
  786.  
  787. >>> year_monthes.keys()
  788.  
  789. dict_keys([“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”])
  790.  
  791. Sets:
  792.  
  793. set is data structure, which represents a collection ofspecific elements:
  794. set = set()
  795. set.add(a)
  796. set.add(b)
  797. set.add(c)
  798. x = len(set) print(x) >>>x= 3
  799. y = d in set print(y) >>>y= False
  800. z = c in set print(z) >>>z= False
  801.  
  802. Why it is preferred to use sets?
  803.  
  804. 1. It is a very fast code operation on sets than lists.
  805. 2. set is it more appropriate than a list, If we have a large collection of items that we want to use for elements presence in set test:
  806.  
  807. >>> x = [1,2,3,4,5,6,7,8,9,10]
  808.  
  809. >>>print(1 in set(x), 15 in set(x),20 in set(x))
  810.  
  811. (True, False, False)
  812.  
  813. Types of Exception & Cause of Error:
  814.  
  815. AssertionError :  Raised when assert statement fails.
  816.  
  817. AttributeError : Raised when attribute assignment or reference fails.
  818.  
  819. EOFError : Raised when the input() functions hits end-of-file condition.
  820.  
  821. FloatingPointError : Raised when a floating point operation fails.
  822.  
  823. GeneratorExit : Raise when a generator's close() method is called.
  824.  
  825. ImportError : Raised when the imported module is not found.
  826.  
  827. IndexError : Raised when index of a sequence is out of range.
  828.  
  829. KeyError : Raised when a key is not found in a dictionary. KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
  830.  
  831. MemoryError : Raised when an operation runs out of memory.
  832.  
  833. NameError : Raised when a variable is not found in local or global scope.
  834.  
  835. NotImplementedError : Raised by abstract methods.
  836.  
  837. OSError : Raised when system operation causes system related error.
  838.  
  839. OverflowError : Raised when result of an arithmetic operation is too large to be represented. ReferenceError Raised when a weak reference proxy is used to access a garbage collected referent.
  840.  
  841. RuntimeError : Raised when an error does not fall under any other category.
  842.  
  843. StopIteration : Raised by next() function to indicate that there is no further item to be returned by iterator.
  844.  
  845. SyntaxError : Raised by parser when syntax error is encountered.
  846.  
  847. IndentationError : Raised when there is incorrect indentation.
  848.  
  849. TabError : Raised when indentation consists of inconsistent tabs and spaces.
  850.  
  851. SystemError :Raised when interpreter detects internal error.
  852.  
  853. SystemExit : Raised by sys.exit() function.
  854.  
  855. TypeError : Raised when a function or operation is applied to an object of incorrect type.
  856.  
  857. UnboundLocalError : Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.
  858.  
  859. UnicodeError : Raised when a Unicode-related encoding or decoding error occurs.
  860.  
  861. UnicodeEncodeError : Raised when a Unicode-related error occurs during encoding.
  862.  
  863. UnicodeDecodeError : Raised when a Unicode-related error occurs during decoding.
  864.  
  865. UnicodeTranslateError : Raised when a Unicode-related error occurs during translating.
  866.  
  867. ValueError : Raised when a function gets argument of correct type but improper value.
  868.  
  869. ZeroDivisionError : Raised when second operand of division or modulo operation is zero.
  870.  
  871. Python functions:
  872. Function: are pre-written lines of code that do a specific task.
  873.  
  874. Function: are composed of:
  875.  
  876. 1. Definition code line.
  877.  
  878. 2. Argument.
  879.  
  880. 3. Retrun or print or yield or result making lines of code.
  881.  
  882. Python functions:
  883.  
  884. We define our own functions in Python and reuse them in the same program as many times as we need.
  885.  
  886. def function_name(parameters):
  887.  
  888. lines of code of the function should do
  889.  
  890. return something
  891.  
  892. Variable Scope:
  893.  
  894. There two types of variables according to variable scope:
  895.  
  896. Local variable:
  897.  
  898. When the variable located and assigned to data value inside the function only, so it will affect that data value of the that variable inside that function only.
  899.  
  900. Global variable:
  901.  
  902. When the variable located and assigned to data value outside the function, so it will affect that data value of the that variable inside and out side that function.
  903.  
  904. Python functions examples:
  905.  
  906. 1.Function That returns a value according to its argument :
  907.  
  908. >>>def rectangle_area(width, length)
  909.  
  910. area = width * length
  911.  
  912. return area
  913.  
  914. >>>def rectangle_area(6, 9)
  915.  
  916. Result :54
  917.  
  918. >>>def rectangle_area(4, l5)
  919.  
  920. Result : 20
  921.  
  922. 2. Function that returns Boolean value :
  923.  
  924. Example 1:
  925.  
  926. def is_even(x):
  927. if x % 2 == 0:
  928. return True
  929. else:
  930. return False
  931. >>>def is_even(10)
  932.  
  933. Result: True
  934.  
  935. 2. Function that returns Boolean value:
  936.  
  937. Example 2:
  938.  
  939. def is_odd(y):
  940. if y % 2 == 0:
  941. return True
  942. else:
  943. return False
  944. >>>def is_odd(8)
  945.  
  946. Result: False
  947.  
  948. 3.Function that prints specific data:
  949.  
  950. Example 1:
  951.  
  952. def countdown(x):
  953. while x> 0:
  954. print n
  955. x = x-1
  956. print “Stop this is the end!"
  957. >>>def countdown(2)
  958.  
  959. Result: 2
  960.  
  961. 1
  962.  
  963. Stop this is the end!
  964.  
  965. 3. Function that print specific data:
  966.  
  967. Example 2:
  968.  
  969. def is_even_or_odd(n):
  970. if n % 2 == 0:
  971. return “this number is even”
  972. else:
  973. return “this number is odd”
  974. >>>def is_even_or_odd(2)
  975.  
  976. Result: this number is even
  977.  
  978. >>>def is_even_or_odd(7)
  979.  
  980. Result: this number is odd
  981.  
  982. If statement:
  983. If statement is commonly used in programs coded in python and the strcture of if statement as follow:
  984.  
  985. if condition = value:
  986.  
  987. do something
  988.  
  989. elif condition = value:
  990.  
  991. do something
  992.  
  993. else:
  994.  
  995. do some thing
  996.  
  997. If name == “Alex”:
  998.  
  999. print(“Hi Alex”)
  1000.  
  1001. elif name == “Sara”:
  1002.  
  1003. print(“Hi Sara”)
  1004.  
  1005. elif name == “kate”:
  1006.  
  1007. print(“Hi Kate”)
  1008.  
  1009. else:
  1010.  
  1011. print(“Hi everybody”)
  1012.  
  1013. distance = input(“what is the distance of this road?”)
  1014.  
  1015. >>> what is the distance of this road?
  1016.  
  1017. 25
  1018.  
  1019. msg= “this road 11 if distance == 20 else “this is another road”
  1020.  
  1021. >>>Print (msg)
  1022.  
  1023. we observe that user input distance = 25
  1024.  
  1025. So it will print :
  1026.  
  1027. this is another road
  1028.  
  1029. For Loop:
  1030.  
  1031. The for loop Looping through an iterable executes a block of code repeatedly until the condition in the for statement is no longer valid.
  1032.  
  1033. an iterable In Python refers to anything that can be looped over, such as a string, list or tuple.
  1034.  
  1035. The syntax for looping through an iterable is as follows:
  1036.  
  1037. for i in iterable:
  1038.  
  1039. print (i)
  1040.  
  1041. Example:
  1042.  
  1043. colors = [‘red', ‘yellow', ‘green', ‘blue‘, black]
  1044.  
  1045. for color in colors:
  1046.  
  1047. print (color)
  1048.  
  1049. 1. we first declare the list of colors and give it the members ‘red', ‘yellow', ‘green', ‘blue‘, black.
  1050.  
  1051. 2. Next the statement for color in colors, so the program loops through the colors list and assigns each member in the list to the variable color.
  1052.  
  1053. If you run the program, you’ll get
  1054.  
  1055. red
  1056.  
  1057. yellow
  1058.  
  1059. green
  1060.  
  1061. blue
  1062.  
  1063. black
  1064.  
  1065. the index of the members in the list can be displayed by use the enumerate() function.
  1066.  
  1067. for index, color in enumerate(colors):
  1068.  
  1069. print (index, color)
  1070.  
  1071. >>>0 red
  1072.  
  1073. 1 yellow
  1074.  
  1075. 2 green
  1076.  
  1077. 3 blue
  1078.  
  1079. 4 black
  1080.  
  1081. Looping through a sequence of numbers
  1082.  
  1083. Example :
  1084.  
  1085. loop through a string data.
  1086.  
  1087. msg = ‘Hi’
  1088.  
  1089. for i in msg:
  1090.  
  1091. print (i)
  1092.  
  1093. >>>H
  1094.  
  1095. i
  1096.  
  1097. range() function:
  1098.  
  1099. if start is not given, the numbers generated start from zero.
  1100.  
  1101. For instance,
  1102.  
  1103. range(5) will generate the list [0, 1, 2, 3, 4]
  1104.  
  1105. range(3, 10) will generate [3, 4, 5, 6, 7, 8, 9]
  1106.  
  1107. range(4, 10, 2) will generate [4, 6, 8]
  1108.  
  1109. the range() function works inside a for statement:
  1110.  
  1111. Example:
  1112.  
  1113. for i in range(3):
  1114.  
  1115. print (i)
  1116.  
  1117. >>>0
  1118.  
  1119. 1
  1120.  
  1121. 2
  1122.  
  1123. break: using break in for loop:
  1124.  
  1125. sometimes we want to stop the loop when meet specific certain condition so we use the break.
  1126.  
  1127. Example:
  1128.  
  1129. a = 0
  1130.  
  1131. for i in range(10):
  1132.  
  1133. a+= 2
  1134.  
  1135. print (‘i =, i,, a=, a)
  1136.  
  1137. if a== 4:
  1138.  
  1139. break
  1140.  
  1141. we will get:
  1142.  
  1143. i = 0 , a = 2
  1144.  
  1145. i = 1 , a= 4
  1146.  
  1147. Without the break, the coder will loop from i = 0 to i = 10 because we used the function range(10).
  1148.  
  1149. However with the break keyword, the program ends prematurely at i = 2. This is because when i = 2, j reaches the value of 6 and the break keyword causes the loop to end.
  1150.  
  1151. continue: using continue in for loop:
  1152.  
  1153. We use continue to skip specific step in the iteration process.
  1154.  
  1155. Example:
  1156.  
  1157. for num in range(3)
  1158.  
  1159. if num == 1:
  1160.  
  1161. continue
  1162.  
  1163. print('Current number :', num)
  1164.  
  1165. Result: Current number : 0
  1166.  
  1167. Current number : 2
  1168.  
  1169. While Loop
  1170.  
  1171. while loop repeatedly executes code which inside the loop while specific condition remains valid.
  1172.  
  1173. Composition of while loop is as follow:
  1174.  
  1175. while condition is true:
  1176.  
  1177. do something
  1178.  
  1179. Firstly we declare a variable to function as a loop counter(variable counter)
  1180.  
  1181. The condition in which the while statement will evaluate the value of counter to determine if it something more than or less than, so the loop will be executed.
  1182.  
  1183. Example:
  1184.  
  1185. >>>variable_count= 3
  1186.  
  1187. while variable_count > 0:
  1188.  
  1189. variable_count = variable_count - 1
  1190.  
  1191. print ("Variable_count =" , variable_count)
  1192.  
  1193. variable_count = 3
  1194.  
  1195. variable_count = 2
  1196.  
  1197. variable_count = 1
  1198.  
  1199. Continue: using continue in while loop:
  1200.  
  1201. We use continue to skip specific step in the iteration process of while loop.
  1202.  
  1203. Example:
  1204.  
  1205. num = 3
  1206.  
  1207. while num > 0:
  1208.  
  1209. num -= 1
  1210.  
  1211. if num == 1:
  1212.  
  1213. continue
  1214.  
  1215. print('Current number:', num)
  1216.  
  1217. Result: Current number : 0
  1218.  
  1219. Current number : 2
  1220.  
  1221. Zip( ) iterator examples:
  1222.  
  1223. print(list(zip(['red', 'yellow', 'green'], [1, 2, 3])))
  1224.  
  1225. >>>[('red ', 1), ('yellow ', 2), ('green', 3)]
  1226. colors = ['red', 'yellow', 'green']
  1227.  
  1228. nums = [1, 2, 3]
  1229.  
  1230. for color, num in zip(colors, nums):
  1231.  
  1232. print("{}: {}".format(color, num))
  1233.  
  1234. 'red’: 1
  1235.  
  1236. 'yellow': 2
  1237.  
  1238. 'green': 3
  1239.  
  1240. Zip( ) iterator +* examples for lists : unzip nested lists
  1241.  
  1242. Eaxmple 3:
  1243.  
  1244. >>>colors = ['red', 'yellow', 'green']
  1245.  
  1246. >>>nums = [1, 2, 3]
  1247.  
  1248. >>>colors_list = [colors, nums]
  1249.  
  1250. >>>for colors, nums in zip(*colors_list):
  1251.  
  1252. print(colors, nums)
  1253.  
  1254. red 1
  1255.  
  1256. yellow 2
  1257.  
  1258. green 3
  1259.  
  1260. Zip( ) iterator+ * example for tuples: unzip nested tuples
  1261.  
  1262. >>>colors = ('red', 'yellow', 'green')
  1263.  
  1264. >>>nums = (1, 2, 3)
  1265.  
  1266. >>>colors_list = (colors, nums)
  1267.  
  1268. >>>for colors, nums in zip(*colors_list):
  1269.  
  1270. print(colors, nums)
  1271.  
  1272. red 1
  1273.  
  1274. yellow 2
  1275.  
  1276. green 3
  1277.  
  1278. enumerate( ) iterator: for lists:
  1279.  
  1280. It returns an iterator of tuples containing indices and values of a list. use this when you want the index along with each element of an iterable in a loop.
  1281. >>>letters = ['a', 'b', 'c', 'd', 'e']
  1282.  
  1283. >>>for i, letter in enumerate(letters):
  1284.  
  1285. print(i, letter))
  1286. 0 a
  1287. 1 b
  1288. 2 c
  1289. 3 d
  1290. 4 e
  1291.  
  1292. enumerate( ) iterator:for tuples
  1293.  
  1294. Example 2:
  1295.  
  1296. letters =('a', 'b', 'c', 'd', 'e‘)
  1297. for i, letter in enumerate(letters):
  1298. print(i, letter)
  1299. 0 a
  1300. 1 b
  1301. 2 c
  1302. 3 d
  1303. 4 e
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement