Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # lecture 6.10.2023 - string manipulation and error handling
- print("Welcome!")
- # NEW FILE
- # " and ' do the same thing -> define as string
- # we can mix " and ' if we first start with " and then use ',
- # or other way around
- name = 'John "Supercoder" Doe'
- # this also possible
- name = "John 'Supercoder' Doe"
- # if you literally need to print a double quotation mark
- # you can use \" => escape character for quotation mark
- name = "John \"Supercoder\" Doe"
- print(name)
- # NEW FILE
- # test variable
- text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- # from first character to 10th
- subtext1 = text[0:10]
- print(subtext1)
- # from sixth charater to 15th
- subtext2 = text[5:15]
- print(subtext2)
- # take last 6 characters (- => go the other way, starting from end)
- subtext3 = text[-6:]
- print(subtext3)
- # start from 11th character, and take all the rest what is left
- subtext4 = text[10:]
- print(subtext4)
- # NEW FILE
- # ask user for some text
- text = input("Give some text:\n")
- # shorten the text and add ... in the end
- text = text[0:20] + "..."
- print(text)
- # NEW FILE
- years = "2023-2022-2021-2020-2019-2018-"
- # this is handy:
- # start from 1st character until the second last character (-1)
- years_modified = years[0:-1]
- print(years)
- print(years_modified)
- # NEW FILE
- text = input("Write a sentence:\n")
- # length => how many characters in this variable
- # note: spaces are also characters
- text_length = len(text)
- print(f"Text has {text_length} characters in total.")
- # how many lowercase "a" we have in the text
- # note: uppercase "A" is a completely different letter in programming languages
- a_letters = text.count("a")
- print(f"a-letters in the text: {a_letters}")
- # if text is over 30 characters => long text, otherwise => short text
- if text_length > 30:
- print("Long text!")
- else:
- print("Short text...")
- # sometimes we need to react, if text is empty or not
- # if length == 0 => empty
- if text_length == 0:
- print("You gave an empty text...")
- # NEW FILE
- text = "Rovaniemi"
- # this logic is a bit funky in Python
- # basically we select everything from start to finish
- # but use -1 as the third parameter => we search the string the wrong way
- # => this flips the string reversed
- reversed_text = text[::-1]
- print(reversed_text)
- # NEW FILE
- text = input("Give text:\n")
- # this logic is a bit funky in Python
- # basically we select everything from start to finish
- # but use -1 as the third parameter => we search the string the wrong way
- # => this flips the string reversed
- reversed_text = text[::-1]
- print(reversed_text)
- # NEW FILE
- # our test data
- drinks = "water, milk, coffee, tea, water"
- # replace water with "wine"
- # if you only want to replace the first occurence
- # try: drinks.replace("water", "wine", 1)
- drinks = drinks.replace("water", "wine")
- print(drinks)
- print()
- # we can also replace a character with a newline
- new_drinks = drinks.replace(", ", "\n")
- print(new_drinks)
- print()
- usertext = input("What would you like to drink?\n")
- # to check if user's text is inside another text
- if usertext in drinks:
- print("Drink found!")
- else:
- print("We don't have that, sorry!")
- # NEW FILE
- text = input("Give either a number, or text:\n")
- # if text.isnumeric() is same as if text.isnumeric() == True
- # the application now has two lanes
- # depending on if user gave a numeric value or text value
- # this works only for integers, if user gave a decimal:
- # try replacing "." with ""
- if text.isnumeric():
- print("You gave a number!")
- number = int(text)
- number = number * 2
- print(number)
- else:
- print("You gave text.")
- # NEW FILE
- # ask user who they are
- choice = input("Student or adult? (s/a)\n")
- # force the user's choice to be always lowercase
- choice = choice.lower()
- # now this should work with s, S, a and A
- if choice == "s":
- print("Student")
- elif choice == "a":
- print("Adult!")
- else:
- print("Incorrect selection")
- # NEW FILE
- try:
- # all the code that has the potential to crash
- # goes inside the try-block
- number = input("Give a number:\n")
- number = int(number)
- print(f"Your number: {number}")
- except ValueError:
- # handle the error situation here (print error message)
- print("You wrote text! Please run the application again!")
- # NEW FILE
- try:
- # all the code that has the potential to crash
- # goes inside the try-block
- number = input("Give a number:\n")
- number = int(number)
- divided = 100 / number
- print(f"Your number: {number}")
- print(divided)
- except ValueError:
- # handle the error situation here (print error message)
- print("You wrote text! Please run the application again!")
- except ZeroDivisionError:
- # we also have to take care of this since ValueError doesn't help
- print("You can't divide by zero!")
- # NEW FILE
- try:
- # all the code that has the potential to crash
- # goes inside the try-block
- number = input("Give a number:\n")
- number = int(number)
- divided = 100 / number
- print(f"Your number: {number}")
- print(divided)
- except Exception as e:
- # generic error message from Python
- print("Error:" + str(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 (imagein: 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("Identier 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