Advertisement
tuomasvaltanen

Untitled

Oct 5th, 2023 (edited)
987
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.51 KB | None | 0 0
  1. # lecture 6.10.2023 - string manipulation and error handling
  2. print("Welcome!")
  3.  
  4. # NEW FILE
  5.  
  6. # " and ' do the same thing -> define as string
  7. # we can mix " and ' if we first start with " and then use ',
  8. # or other way around
  9. name = 'John "Supercoder" Doe'
  10.  
  11. # this also possible
  12. name = "John 'Supercoder' Doe"
  13.  
  14. # if you literally need to print a double quotation mark
  15. # you can use \" => escape character for quotation mark
  16. name = "John \"Supercoder\" Doe"
  17.  
  18. print(name)
  19.  
  20. # NEW FILE
  21.  
  22. # test variable
  23. text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  24.  
  25. # from first character to 10th
  26. subtext1 = text[0:10]
  27. print(subtext1)
  28.  
  29. # from sixth charater to 15th
  30. subtext2 = text[5:15]
  31. print(subtext2)
  32.  
  33. # take last 6 characters (- => go the other way, starting from end)
  34. subtext3 = text[-6:]
  35. print(subtext3)
  36.  
  37. # start from 11th character, and take all the rest what is left
  38. subtext4 = text[10:]
  39. print(subtext4)
  40.  
  41. # NEW FILE
  42.  
  43. # ask user for some text
  44. text = input("Give some text:\n")
  45.  
  46. # shorten the text and add ... in the end
  47. text = text[0:20] + "..."
  48. print(text)
  49.  
  50. # NEW FILE
  51.  
  52. years = "2023-2022-2021-2020-2019-2018-"
  53.  
  54. # this is handy:
  55. # start from 1st character until the second last character (-1)
  56. years_modified = years[0:-1]
  57.  
  58. print(years)
  59. print(years_modified)
  60.  
  61. # NEW FILE
  62.  
  63. text = input("Write a sentence:\n")
  64.  
  65. # length => how many characters in this variable
  66. # note: spaces are also characters
  67. text_length = len(text)
  68.  
  69. print(f"Text has {text_length} characters in total.")
  70.  
  71. # how many lowercase "a" we have in the text
  72. # note: uppercase "A" is a completely different letter in programming languages
  73. a_letters = text.count("a")
  74. print(f"a-letters in the text: {a_letters}")
  75.  
  76. # if text is over 30 characters => long text, otherwise => short text
  77. if text_length > 30:
  78.     print("Long text!")
  79. else:
  80.     print("Short text...")
  81.  
  82. # sometimes we need to react, if text is empty or not
  83. # if length == 0 => empty
  84. if text_length == 0:
  85.     print("You gave an empty text...")
  86.  
  87. # NEW FILE
  88.  
  89. text = "Rovaniemi"
  90.  
  91. # this logic is a bit funky in Python
  92. # basically we select everything from start to finish
  93. # but use -1 as the third parameter => we search the string the wrong way
  94. # => this flips the string reversed
  95. reversed_text = text[::-1]
  96. print(reversed_text)
  97.  
  98. # NEW FILE
  99.  
  100. text = input("Give text:\n")
  101.  
  102. # this logic is a bit funky in Python
  103. # basically we select everything from start to finish
  104. # but use -1 as the third parameter => we search the string the wrong way
  105. # => this flips the string reversed
  106. reversed_text = text[::-1]
  107. print(reversed_text)
  108.  
  109. # NEW FILE
  110.  
  111. # our test data
  112. drinks = "water, milk, coffee, tea, water"
  113.  
  114. # replace water with "wine"
  115. # if you only want to replace the first occurence
  116. # try: drinks.replace("water", "wine", 1)
  117. drinks = drinks.replace("water", "wine")
  118. print(drinks)
  119. print()
  120.  
  121. # we can also replace a character with a newline
  122. new_drinks = drinks.replace(", ", "\n")
  123. print(new_drinks)
  124. print()
  125.  
  126. usertext = input("What would you like to drink?\n")
  127.  
  128. # to check if user's text is inside another text
  129. if usertext in drinks:
  130.     print("Drink found!")
  131. else:
  132.     print("We don't have that, sorry!")
  133.  
  134. # NEW FILE
  135.  
  136. text = input("Give either a number, or text:\n")
  137.  
  138. # if text.isnumeric() is same as if text.isnumeric() == True
  139. # the application now has two lanes
  140. # depending on if user gave a numeric value or text value
  141. # this works only for integers, if user gave a decimal:
  142. # try replacing "." with ""
  143. if text.isnumeric():
  144.     print("You gave a number!")
  145.     number = int(text)
  146.     number = number * 2
  147.     print(number)
  148. else:
  149.     print("You gave text.")
  150.  
  151. # NEW FILE
  152.  
  153. # ask user who they are
  154. choice = input("Student or adult? (s/a)\n")
  155.  
  156. # force the user's choice to be always lowercase
  157. choice = choice.lower()
  158.  
  159. # now this should work with s, S, a and A
  160. if choice == "s":
  161.     print("Student")
  162. elif choice == "a":
  163.     print("Adult!")
  164. else:
  165.     print("Incorrect selection")
  166.  
  167. # NEW FILE
  168.  
  169. try:
  170.     # all the code that has the potential to crash
  171.     # goes inside the try-block
  172.     number = input("Give a number:\n")
  173.     number = int(number)
  174.  
  175.     print(f"Your number: {number}")
  176. except ValueError:
  177.     # handle the error situation here (print error message)
  178.     print("You wrote text! Please run the application again!")
  179.  
  180. # NEW FILE
  181.  
  182. try:
  183.     # all the code that has the potential to crash
  184.     # goes inside the try-block
  185.     number = input("Give a number:\n")
  186.     number = int(number)
  187.  
  188.     divided = 100 / number
  189.  
  190.     print(f"Your number: {number}")
  191.     print(divided)
  192. except ValueError:
  193.     # handle the error situation here (print error message)
  194.     print("You wrote text! Please run the application again!")
  195. except ZeroDivisionError:
  196.     # we also have to take care of this since ValueError doesn't help
  197.     print("You can't divide by zero!")
  198.  
  199. # NEW FILE
  200.  
  201. try:
  202.     # all the code that has the potential to crash
  203.     # goes inside the try-block
  204.     number = input("Give a number:\n")
  205.     number = int(number)
  206.  
  207.     divided = 100 / number
  208.  
  209.     print(f"Your number: {number}")
  210.     print(divided)
  211. except Exception as e:
  212.     # generic error message from Python
  213.     print("Error:" + str(e))
  214.  
  215. # NEW FILE
  216.  
  217. # this example combines everything: conditional statements,
  218. # string operations and error management
  219.  
  220. # INSTRUCTIONS: create an application, that checks if the given
  221. # client identifier is in correct format (imagein: phone operators etc.)
  222. # example client identifier = C1234_2345
  223.  
  224. # logic: client identifier is ALWAYS 10 characters long, sixth letter is always
  225. # underscore,
  226.  
  227. # let's use try/except just in case
  228. # C1234_2345
  229.  
  230. try:
  231.     # ask user for a client identifier
  232.     client = input("Give a client identifier:\n")
  233.  
  234.     text_length = len(client)
  235.  
  236.     # check that the length is exactly 10
  237.     if text_length != 10:
  238.         print("Client identifier, incorrect length (10 required).")
  239.     elif client[5] != "_":
  240.         # sixth character has to be underscore
  241.         print("Underscore missing in client identifier.")
  242.     else:
  243.         # split the identifier into client and order number
  244.         identifier = client[0:5]
  245.         order = client[6:10]
  246.  
  247.         # convert order number to in
  248.         order = int(order)
  249.  
  250.         print(identifier)
  251.         print(order)
  252.  
  253.         # if the conditions above were OK, we will finally arrive
  254.         # this else-statement
  255.         print("Identier OK!")
  256.  
  257. except Exception as e:
  258.     # if something goes wrong, do this lastly
  259.     # for example: C1234_HOLA
  260.     print("Incorrect client identifier.")
  261.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement