Advertisement
tuomasvaltanen

Untitled

Oct 10th, 2024 (edited)
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.19 KB | None | 0 0
  1. # lecture 5, 10.10.2024, string manipulation / exception handling
  2. print("Welcome!")
  3.  
  4. # NEW FILE
  5.  
  6. # " and ' do the same thing => define a string
  7. # we can mix " and ' if we first start with " and then '
  8. # also vice versa
  9. name = 'John "Supercoder" Doe'
  10. print(name)
  11.  
  12. # also possible
  13. name = "John 'Supercoder' Doe"
  14. print(name)
  15.  
  16. # we can also literally use quotation marks
  17. # with the \-character => special character
  18. name = "John \"Supercoder\" Doe"
  19. print(name)
  20.  
  21. # virtually both are the same value-wise
  22. name2 = "John"
  23. name3 = 'John'
  24.  
  25. print(name2)
  26. print(name3)
  27.  
  28. # NEW FILE
  29.  
  30. # you could also ask this from the user
  31. text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  32.  
  33. # from first to 10th
  34. # REMEMBER: empty space is also a letter/character
  35. # this is very useful in the text shortening exercises in exercises 4
  36. subtext1 = text[0:10]
  37. print(subtext1)
  38.  
  39. # take from the middle, starting at position 10
  40. # until 15 (11th character onwards)
  41. subtext2 = text[10:15]
  42. print(subtext2)
  43.  
  44. # start from 6th character, and after that
  45. # take all characters that remain
  46. # (take everything after this character
  47. subtext3 = text[5:]
  48. print(subtext3)
  49.  
  50. # get last five characters by using the negative index
  51. # so basically start from the 5th character from the end, and take
  52. # all text that is left
  53. subtext4 = text[-5:]
  54. print(subtext4)
  55.  
  56. # sometimes handy, just remove the final character (often some
  57. # kind of extra mess we have to clean up
  58. subtext5 = text[0:-1]
  59. print(subtext5)
  60.  
  61. # NEW FILE
  62.  
  63. text = input("Write a sentence:\n")
  64.  
  65. text_length = len(text)
  66.  
  67. # get text length / amount of characters
  68. # empty spaces are also characters
  69. print(f"Text length: {text_length} characters")
  70.  
  71. # check if text is long or short
  72. # this could also be useful in checking
  73. # that is the user's new password long enough
  74. if text_length > 30:
  75.     print("Long text!")
  76.  
  77.     # text is too long, let's shorten it up and add the
  78.     # typical ... in the end
  79.     shortened = text[0:30] + "..."
  80.     print(shortened)
  81. else:
  82.     print("Short text...")
  83.  
  84. # count the amount of letters, this case lowercase a
  85. # NOTE: capital letters and lowercase letters are completely
  86. # different letters in programming, because otherwise
  87. # the code would never know went to print a capital or
  88. # or a lowercase letter
  89. a_letters = text.count("a")
  90. print(f"Amount of a-characters: {a_letters}")
  91.  
  92. # check if text is empty
  93. if text_length == 0:
  94.     print("EMPTY TEXT GIVEN!")
  95. else:
  96.     print("Text not empty.")
  97.  
  98. # NEW FILE
  99.  
  100. text = input("Give text:\n")
  101.  
  102. # reversing a text in Python is quite different
  103. # than in other languages, but this works
  104. # basically this uses the substring -syntax
  105. # but we choose everything from beginning to end, but traverse
  106. # the string the other way (-1)
  107. # [ : : -1]
  108.  
  109. # palindrome is a word that is the same forwards and backwards
  110. # for example "racecar" is the same both directions
  111. reversed_text = text[::-1]
  112. print(reversed_text)
  113.  
  114. # NEW FILE
  115.  
  116. # our test data
  117. drinks = "water, milk, coffee, tea, water"
  118.  
  119. # replace water with
  120. drinks = drinks.replace("water", "soda")
  121. print(drinks)
  122. print()
  123.  
  124. # any character will do, even special characters like new line!
  125. new_drinks = drinks.replace(", ", "\n")
  126. print(new_drinks)
  127.  
  128. # NEW FILE
  129.  
  130. # our test data
  131. drinks = "water, milk, coffee, tea, water"
  132.  
  133. # replace water with
  134. # if you want to limit the amount of replacements
  135. # try: drinks.replace("water", "soda", 2)
  136. drinks = drinks.replace("water", "soda")
  137. print(drinks)
  138. print()
  139.  
  140. # any character will do, even special characters like new line!
  141. # you can "remove" a word by replacing with an empty string ""
  142. new_drinks = drinks.replace(", ", "\n")
  143. print(new_drinks)
  144. print()
  145.  
  146. # ask user for text
  147. usertext = input("What would you like to drink?\n")
  148.  
  149. # check if the user's text was in the original text
  150. if usertext in drinks:
  151.     print("Drink found!")
  152. else:
  153.     print("We don't have that, sorry!")
  154.  
  155. # NEW FILE
  156.  
  157. text = input("Give a value:\n")
  158.  
  159. # use this as the basis for advanced exercise 4-7
  160. # e.g. 12345 => number, "one two three four five" -> text
  161. if text.isnumeric():
  162.     print("User gave numbers...")
  163. else:
  164.     print("User gave text!")
  165.  
  166. # NEW FILE
  167.  
  168. text = input("Are you a student or an adult? (s/a)\n")
  169.  
  170. # a nice trick you can do with string functions
  171. # we force the value to lowercase
  172. # and now we don't have to have complex comparisons
  173. # like if text == "s" or text == "S"
  174. text = text.lower()
  175.  
  176. # check the user's status (given by input)
  177. if text == "s":
  178.     print("You're a student!")
  179. elif text == "a":
  180.     print("You're an adult!")
  181. else:
  182.     print("Incorrect selection")
  183.  
  184. # NEW FILE
  185.  
  186. # try-block has the code that has the potential
  187. # to crash in some event. in this case, our code assumes
  188. # user always gives a number, but what if they give text?
  189. # except -block is launched, if the error actually happens
  190. # print error message etc.
  191. try:
  192.     number = input("Give a number:\n")
  193.     number = int(number)
  194.     print(f"Your number: {number}")
  195. except ValueError:
  196.     print("You wrote text, only numbers supported. Run app again!")
  197.  
  198. # NEW FILE
  199. # this version handles two different types of errors
  200. # remember: all uncaught errors will crash the app!
  201. try:
  202.     number = input("Give a number:\n")
  203.     number = int(number)
  204.     result = 100 / number
  205.     print(f"Result: {result}")
  206. except ValueError:
  207.     print("You wrote text, only numbers supported. Run app again!")
  208. except ZeroDivisionError:
  209.     print("Can't divide by zero, run app again!")
  210.  
  211. # NEW FILE
  212.  
  213. # you can also create a generic error handling
  214. # but the messages are often technical and straigt from Python
  215. # might also be a good idea to wrap to whole
  216. # basic app around this, so it doesn't crash in most cases
  217. try:
  218.     number = input("Give a number:\n")
  219.     number = int(number)
  220.     result = 100 / number
  221.     print(f"Result: {result}")
  222. except Exception as e:
  223.     print(f"Error message: {e}")
  224.  
  225. # NEW FILE
  226.  
  227. # this example combines everything: conditional statements,
  228. # string operations and error management
  229.  
  230. # INSTRUCTIONS: create an application, that checks if the given
  231. # client identifier is in correct format (imagine: phone operators etc.)
  232. # example client identifier = C1234_2345
  233.  
  234. # logic: client identifier is ALWAYS 10 characters long, sixth letter is always
  235. # underscore,
  236.  
  237. # let's use try/except just in case
  238. # C1234_2345
  239.  
  240. try:
  241.     # ask user for a client identifier
  242.     client = input("Give a client identifier:\n")
  243.  
  244.     text_length = len(client)
  245.  
  246.     # check that the length is exactly 10
  247.     if text_length != 10:
  248.         print("Client identifier, incorrect length (10 required).")
  249.     elif client[5] != "_":
  250.         # sixth character has to be underscore
  251.         print("Underscore missing in client identifier.")
  252.     else:
  253.         # split the identifier into client and order number
  254.         identifier = client[0:5]
  255.         order = client[6:10]
  256.  
  257.         # convert order number to in
  258.         order = int(order)
  259.  
  260.         print(identifier)
  261.         print(order)
  262.  
  263.         # if the conditions above were OK, we will finally arrive
  264.         # this else-statement
  265.         print("Identifier OK!")
  266.  
  267. except Exception as e:
  268.     # if something goes wrong, do this lastly
  269.     # for example: C1234_HOLA
  270.     print("Incorrect client identifier.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement