Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something.

Similar presentations


Presentation on theme: "Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something."— Presentation transcript:

1 Exception Handling and String Manipulation

2 Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something that causes a runtime error Example: X = “Donald” Y = int (X)

3 Exceptions When an exception occurs Python will generate a “traceback” Tracebacks give information about the exception that occurred, including the line number that caused the issue We normally say an exception has been “raised” by the program >> int(“The Donz”) Traceback (most recent call last): File “ ”, line 1, in int(“The Donz”) Value Error: invalid literal for int() with base 10: “Donald”

4 Preventing Exceptions Many times we can avoid exceptions all together by adjusting how the code is written. For example, in the following code an exception will be raised if x = 0: x = int( input( “give me a number”) ) print (100 / x)

5 Preventing Exceptions We can avoid the potential exception by including the second line of code in a selection statement x = int( input( “give me a number”) ) if x != 0: print (100 / x)

6 Catching Exceptions Python has an exception handling statement that can be used to “catch” exceptions and prevent them from crashing your program We use the word “try” to tell Python to test for a valid code or input from the user It comes along with the words “except” which runs if an exception is raised and “else” which executes only if the input of the “try” block was satisfactory

7 Catching Exceptions try: # questionable code except: # this line of code runs if the code in the “try” block # raised an exception else: # this block runs if the code in the “try” block was run # successfully without exceptions

8 Data Validation You can use the Try / Except statement to validate the data type of inputted data try: x = int(input(“give me a number”)) except: print (“that’s not an integer”) else: print(“great!”)

9 Data Validation As we saw in the “if” selection statements, the “else” statement is not necessary in our try / exception statements try: x = int(input(“give me a number”)) print(x) except: print(“that’s not a number”)

10 Data Validation You’ll notice that the “except” block is executed the moment an exception is raised The rest of the “try” block will not execute if an exception was previously raised

11 Data Validation We can also loop a try / except statement so that the user will be continually prompted until they enter a valid input

12 Programming Challenge Write a program that continually prompts the user for the price of an item until they enter a valid price

13 Programming Challenge while True: try: x = int(input(“price: ”)) break except: print(“not a valid input”)

14 Finally The try / except statement can include one additional block called the “finally” This block will always execute at the end of the try / except statement (even after the word “break” in a loop)

15 Finally try: x = int(input(“give me a number”)) except: print (“that’s not an integer”) else: print(“great!”) finally: print(“this will always print”)

16 Finally while True: try: x = int(input(“give me a number”)) break except: print (“that’s not an integer”) finally: print(“this will always print”)

17 String Manipulation Previously, we saw that we could concatenate strings and perform string repetitions Full_name = “Donald ” + “The Man ” + “Seok” Lyrics = “I know” * 8

18 String Manipulation We were also able to compare strings, and convert other data types into strings and also count the length of a string if “animal” > “apple”: print(“animal will come before apple in the dictionary”) x = str(43.95) print( len( “Donald” ) )

19 String Manipulation Sometimes, we will need to access individual characters in a string We can do this by using a for loop, which will iterate the number of times equivalent to the length of a string Through each iteration, your target variable will hold a different character value, in order of the string

20 String Manipulation for x in “Donald”: print (x) >> D o n a l d

21 Programming Challenge Write a program that counts the number of “S”s there are in the string: “Sally Sells Seashells By The Sea Shore” Rewrite this program to include all “S”s and “s”s

22 Updating Strings However, you cannot directly update a string while iterating over it through a for loop Name = “Donald” for x in Name: x = “A” print (Name) >> Donald

23 Updating Strings You can achieve this task by creating a new variable Name = “Donald” NewName = “” for x in Name: NewName += “A” print(Name) print (NewName) >> Donald AAAAAA

24 Indexing We can also analyze individual elements in a string by a method called “indexing” We can call any specific character in a string by calling it’s variable name followed by brackets with an integer denoting the place of the character word = “Donald” print(word[2]) >> n

25 Indexing Indexes always start with the zero value Therefore the first character in a string can be denoted as the “0 th value” The index of the last character is denoted by the length of the string minus one

26 Indexing # S u p e r m a n # 0 1 2 3 4 5 6 7 word = “Superman” print(len(word)) print(word[0]) >> 8 S

27 Indexing Negative indexes work backwards So -1 will denote the last character in a string, -2 will denote the second to last character, etc. number = “456” print(number[-1], number[-2], number[-3], sep = “”)

28 Indexing If you use an integer index value that is greater than the length of the word, you will raise an exception word = “Superman” print(word[10]) # error!

29 Programming Challenge Define a function that accepts two arguments: a string literal and a single character. Have the function return the number of times you find the specified character within the string literal. Then use the function to ask the user what character they would like to search for in a word / phrase and print out the result

30 Programming Challenge Write a program that counts the number of vowels found in a particular word / phrase Use your function from the previous challenge

31 Programming Challenge: Pig Latin In Pig Latin, the first letter of each word is removed and re-attached to the end of the string with the additional “ay” Create a function that converts words into Pig Latin Example: hello  ellohay


Download ppt "Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something."

Similar presentations


Ads by Google