Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # lecture 5, 10.10.2024, string manipulation / exception handling
- print("Welcome!")
- # NEW FILE
- # " and ' do the same thing => define a string
- # we can mix " and ' if we first start with " and then '
- # also vice versa
- name = 'John "Supercoder" Doe'
- print(name)
- # also possible
- name = "John 'Supercoder' Doe"
- print(name)
- # we can also literally use quotation marks
- # with the \-character => special character
- name = "John \"Supercoder\" Doe"
- print(name)
- # virtually both are the same value-wise
- name2 = "John"
- name3 = 'John'
- print(name2)
- print(name3)
- # NEW FILE
- # you could also ask this from the user
- text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- # from first to 10th
- # REMEMBER: empty space is also a letter/character
- # this is very useful in the text shortening exercises in exercises 4
- subtext1 = text[0:10]
- print(subtext1)
- # take from the middle, starting at position 10
- # until 15 (11th character onwards)
- subtext2 = text[10:15]
- print(subtext2)
- # start from 6th character, and after that
- # take all characters that remain
- # (take everything after this character
- subtext3 = text[5:]
- print(subtext3)
- # get last five characters by using the negative index
- # so basically start from the 5th character from the end, and take
- # all text that is left
- subtext4 = text[-5:]
- print(subtext4)
- # sometimes handy, just remove the final character (often some
- # kind of extra mess we have to clean up
- subtext5 = text[0:-1]
- print(subtext5)
- # NEW FILE
- text = input("Write a sentence:\n")
- text_length = len(text)
- # get text length / amount of characters
- # empty spaces are also characters
- print(f"Text length: {text_length} characters")
- # check if text is long or short
- # this could also be useful in checking
- # that is the user's new password long enough
- if text_length > 30:
- print("Long text!")
- # text is too long, let's shorten it up and add the
- # typical ... in the end
- shortened = text[0:30] + "..."
- print(shortened)
- else:
- print("Short text...")
- # count the amount of letters, this case lowercase a
- # NOTE: capital letters and lowercase letters are completely
- # different letters in programming, because otherwise
- # the code would never know went to print a capital or
- # or a lowercase letter
- a_letters = text.count("a")
- print(f"Amount of a-characters: {a_letters}")
- # check if text is empty
- if text_length == 0:
- print("EMPTY TEXT GIVEN!")
- else:
- print("Text not empty.")
- # NEW FILE
- text = input("Give text:\n")
- # reversing a text in Python is quite different
- # than in other languages, but this works
- # basically this uses the substring -syntax
- # but we choose everything from beginning to end, but traverse
- # the string the other way (-1)
- # [ : : -1]
- # palindrome is a word that is the same forwards and backwards
- # for example "racecar" is the same both directions
- reversed_text = text[::-1]
- print(reversed_text)
- # NEW FILE
- # our test data
- drinks = "water, milk, coffee, tea, water"
- # replace water with
- drinks = drinks.replace("water", "soda")
- print(drinks)
- print()
- # any character will do, even special characters like new line!
- new_drinks = drinks.replace(", ", "\n")
- print(new_drinks)
- # NEW FILE
- # our test data
- drinks = "water, milk, coffee, tea, water"
- # replace water with
- # if you want to limit the amount of replacements
- # try: drinks.replace("water", "soda", 2)
- drinks = drinks.replace("water", "soda")
- print(drinks)
- print()
- # any character will do, even special characters like new line!
- # you can "remove" a word by replacing with an empty string ""
- new_drinks = drinks.replace(", ", "\n")
- print(new_drinks)
- print()
- # ask user for text
- usertext = input("What would you like to drink?\n")
- # check if the user's text was in the original text
- if usertext in drinks:
- print("Drink found!")
- else:
- print("We don't have that, sorry!")
- # NEW FILE
- text = input("Give a value:\n")
- # use this as the basis for advanced exercise 4-7
- # e.g. 12345 => number, "one two three four five" -> text
- if text.isnumeric():
- print("User gave numbers...")
- else:
- print("User gave text!")
- # NEW FILE
- text = input("Are you a student or an adult? (s/a)\n")
- # a nice trick you can do with string functions
- # we force the value to lowercase
- # and now we don't have to have complex comparisons
- # like if text == "s" or text == "S"
- text = text.lower()
- # check the user's status (given by input)
- if text == "s":
- print("You're a student!")
- elif text == "a":
- print("You're an adult!")
- else:
- print("Incorrect selection")
- # NEW FILE
- # try-block has the code that has the potential
- # to crash in some event. in this case, our code assumes
- # user always gives a number, but what if they give text?
- # except -block is launched, if the error actually happens
- # print error message etc.
- try:
- number = input("Give a number:\n")
- number = int(number)
- print(f"Your number: {number}")
- except ValueError:
- print("You wrote text, only numbers supported. Run app again!")
- # NEW FILE
- # this version handles two different types of errors
- # remember: all uncaught errors will crash the app!
- try:
- number = input("Give a number:\n")
- number = int(number)
- result = 100 / number
- print(f"Result: {result}")
- except ValueError:
- print("You wrote text, only numbers supported. Run app again!")
- except ZeroDivisionError:
- print("Can't divide by zero, run app again!")
- # NEW FILE
- # you can also create a generic error handling
- # but the messages are often technical and straigt from Python
- # might also be a good idea to wrap to whole
- # basic app around this, so it doesn't crash in most cases
- try:
- number = input("Give a number:\n")
- number = int(number)
- result = 100 / number
- print(f"Result: {result}")
- except Exception as e:
- print(f"Error message: {e}")
- # NEW FILE
- # this example combines everything: conditional statements,
- # string operations and error management
- # INSTRUCTIONS: create an application, that checks if the given
- # client identifier is in correct format (imagine: phone operators etc.)
- # example client identifier = C1234_2345
- # logic: client identifier is ALWAYS 10 characters long, sixth letter is always
- # underscore,
- # let's use try/except just in case
- # C1234_2345
- try:
- # ask user for a client identifier
- client = input("Give a client identifier:\n")
- text_length = len(client)
- # check that the length is exactly 10
- if text_length != 10:
- print("Client identifier, incorrect length (10 required).")
- elif client[5] != "_":
- # sixth character has to be underscore
- print("Underscore missing in client identifier.")
- else:
- # split the identifier into client and order number
- identifier = client[0:5]
- order = client[6:10]
- # convert order number to in
- order = int(order)
- print(identifier)
- print(order)
- # if the conditions above were OK, we will finally arrive
- # this else-statement
- print("Identifier OK!")
- except Exception as e:
- # if something goes wrong, do this lastly
- # for example: C1234_HOLA
- print("Incorrect client identifier.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement