Python Lecture 25 PDF
Document Details
Uploaded by SlickAgate3499
Academy of Future Robotics
Viduranga Jayakody
Tags
Summary
This document provides a detailed introduction to Python programming concepts, focusing on MySQL and SQL, with specific examples and explanations. It covers filtering records with WHERE clauses, handling wildcard characters in SQL, and preventing SQL injection attacks.
Full Transcript
Viduranga Jayakody Academy of Future Robotics 0760944206 Python Lesson 25 MySQL Where Select With a Filter When selecting records from a table, you can filter the selection by using the "WHERE" statement: Wildcard Characters You can also select the record...
Viduranga Jayakody Academy of Future Robotics 0760944206 Python Lesson 25 MySQL Where Select With a Filter When selecting records from a table, you can filter the selection by using the "WHERE" statement: Wildcard Characters You can also select the records that starts, includes, or ends with a given letter or phrase. Use the % to represent wildcard characters: Prevent SQL Injection When query values are provided by the user, you should escape the values. This is to prevent SQL injections, which is a common web hacking technique to destroy or misuse your database. Viduranga Jayakody Academy of Future Robotics 0760944206 The mysql.connector module has methods to escape query values: MySQL Order By Sort the Result Use the ORDER BY statement to sort the result in ascending or descending order. The ORDER BY keyword sorts the result ascending by default. To sort the result in descending order, use the DESC keyword. ORDER BY DESC Use the DESC keyword to sort the result in a descending order. Viduranga Jayakody Academy of Future Robotics 0760944206 MySQL Delete From By Delete Record You can delete records from an existing table by using the "DELETE FROM" statement: Important!: Notice the statement: mydb.commit(). It is required to make the changes, otherwise no changes are made to the table. Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which record(s) that should be deleted. If you omit the WHERE clause, all records will be deleted! Prevent SQL Injection It is considered a good practice to escape the values of any query, also in delete statements. This is to prevent SQL injections, which is a common web hacking technique to destroy or misuse your database. The mysql.connector module uses the placeholder %s to escape values in the delete statement: Viduranga Jayakody Academy of Future Robotics 0760944206 MySQL Drop Table Delete a Table You can delete an existing table by using the "DROP TABLE" statement: Drop Only if Exist If the table you want to delete is already deleted, or for any other reason does not exist, you can use the IF EXISTS keyword to avoid getting an error. Viduranga Jayakody Academy of Future Robotics 0760944206 MySQL Update Table Update Table You can update existing records in a table by using the "UPDATE" statement: Overwrite the address column from "Valley 345" to "Canyon 123": Important!: Notice the statement: mydb.commit(). It is required to make the changes, otherwise no changes are made to the table. Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated! Prevent SQL Injection It is considered a good practice to escape the values of any query, also in update statements. Viduranga Jayakody Academy of Future Robotics 0760944206 This is to prevent SQL injections, which is a common web hacking technique to destroy or misuse your database. The mysql.connector module uses the placeholder %s to escape values in the delete statement: Python Try Except The try block lets you test a block of code for errors. The except block lets you handle the error. The finally block lets you execute code, regardless of the result of the try- and except blocks. Exception Handling When an error occurs, or exception as we call it, Python will normally stop and generate an error message. These exceptions can be handled using the try statement: Viduranga Jayakody Academy of Future Robotics 0760944206 The try block will generate an exception, because x is not defined: Since the try block raises an error, the except block will be executed. Without the try block, t he program will crash and raise an error: Many Exceptions You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error: Print one message if the try block raises a NameError and another for other errors: Error Types Exception Description AssertionError Raised when the assert statement fails. AttributeError Raised on the attribute assignment or reference fails. EOFError Raised when the input() function hits the end-of-file condition. FloatingPointError Raised when a floating point operation fails. GeneratorExit Raised when a generator's close() method is called. Viduranga Jayakody Academy of Future Robotics 0760944206 Exception Description ImportError Raised when the imported module is not found. IndexError Raised when the index of a sequence is out of range. KeyError Raised when a key is not found in a dictionary. KeyboardInterrupt Raised when the user hits the interrupt key (Ctrl+c or delete). MemoryError Raised when an operation runs out of memory. NameError Raised when a variable is not found in the local or global scope. NotImplementedError Raised by abstract methods. OSError Raised when a system operation causes a system-related error. Raised when the result of an arithmetic operation is too large to be OverflowError represented. Raised when a weak reference proxy is used to access a garbage ReferenceError collected referent. RuntimeError Raised when an error does not fall under any other category. Raised by the next() function to indicate that there is no further item to StopIteration be returned by the iterator. SyntaxError Raised by the parser when a syntax error is encountered. IndentationError Raised when there is an incorrect indentation. TabError Raised when the indentation consists of inconsistent tabs and spaces. SystemError Raised when the interpreter detects internal error. SystemExit Raised by the sys.exit() function. Raised when a function or operation is applied to an object of an TypeError incorrect type. Raised when a reference is made to a local variable in a function or UnboundLocalError method, but no value has been bound to that variable. UnicodeError Raised when a Unicode-related encoding or decoding error occurs. UnicodeEncodeError Raised when a Unicode-related error occurs during encoding. UnicodeDecodeError Raised when a Unicode-related error occurs during decoding. UnicodeTranslateError Raised when a Unicode-related error occurs during translation. Raised when a function gets an argument of correct type but improper ValueError value. Raised when the second operand of a division or module operation is ZeroDivisionError zero. Viduranga Jayakody Academy of Future Robotics 0760944206 Else You can use the else keyword to define a block of code to be executed if no errors were raised: In this example, the try block does not generate any error: Finally The finally block, if specified, will be executed regardless if the try block raises an error or not. Raise an exception As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword. Viduranga Jayakody Academy of Future Robotics 0760944206 The raise keyword is used to raise an exception. You can define what kind of error to raise, and the text to print to the user. Python Sets A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets. Note: Sets are unordered, so you cannot be sure in which order the items will appear. Access Items You cannot access items in a set by referring to an index, since sets are unordered the items has no index. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword. Viduranga Jayakody Academy of Future Robotics 0760944206 Change Items Once a set is created, you cannot change its items, but you can add new items. Add Items To add one item to a set use the add() method. To add more than one item to a set use the update() method. Get the Length of a Set To determine how many items a set has, use the len() method. Remove Item To remove an item in a set, use the remove(), or the discard() method. Note: If the item to remove does not exist, remove() will raise an error. Viduranga Jayakody Academy of Future Robotics 0760944206 Note: If the item to remove does not exist, discard() will NOT raise an error. pop() You can also use the pop(), method to remove an item, but this method will remove the last item. Remember that sets are unordered, so you will not know what item that gets removed. The return value of the pop() method is the removed item. Note: Sets are unordered, so when using the pop() method, you will not know which item that gets removed. clear() The clear() method empties the set: del keyword The del keyword will delete the set completely: Viduranga Jayakody Academy of Future Robotics 0760944206 Join Two Sets There are several ways to join two or more sets in Python. You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another: Note: Both union() and update() will exclude any duplicate items. The set() Constructor It is also possible to use the set() constructor to make a set. Viduranga Jayakody Academy of Future Robotics 0760944206 Set Methods Python has a set of built-in methods that you can use on sets. Python sets are crucial data structures with several key advantages: Viduranga Jayakody Academy of Future Robotics 0760944206 Uniqueness: Sets only contain unique elements. If you try to add an element that is already in the set, it won't be added again. This property is extremely useful when dealing with collections of unique items, such as unique identifiers, unique values from data, or eliminating duplicates from a list. Membership Testing: Sets offer very efficient membership testing. Checking whether an element is present in a set is significantly faster than doing the same check on a list or tuple. This makes sets ideal for scenarios where you need to quickly determine whether an element is part of a collection. Set Operations: Sets support various mathematical set operations like union, intersection, difference, and symmetric difference. These operations make it easy to perform common tasks like finding common elements between two sets, finding unique elements in each set, or finding elements that are present in one set but not the other. Mutable and Immutable Elements: While the set itself is mutable (you can add or remove elements), the elements within a set must be immutable. This means you can't have mutable objects like lists or dictionaries as elements, but you can have immutable objects like integers, strings, or tuples. This restriction ensures the integrity of the set operations and allows for predictable behavior. Hashing for Fast Lookup: Sets use hash tables internally, which makes element lookup extremely fast even for large sets. This makes sets ideal for scenarios where you need to efficiently check for the presence of elements. Iterability: Like lists and tuples, sets are iterable, allowing you to loop through their elements easily. This makes sets compatible with various Python constructs like for loops, list comprehensions, and more. In summary, Python sets offer efficient storage and retrieval of unique elements, making them invaluable for tasks involving membership testing, eliminating duplicates, and performing set operations. Viduranga Jayakody Academy of Future Robotics 0760944206 Download & Install PyCharm From below link you can download PyCharm community Version https://www.jetbrains.com/pycharm/download/#section=windows Check the “ Update PATH Variable” Start 1st PyCharm Project File > New Project Viduranga Jayakody Academy of Future Robotics 0760944206 Name the project and press “Create” button Close main.py file and right click on your project file and press New> Python File Viduranga Jayakody Academy of Future Robotics 0760944206 Name it and Press enter key. Run HelloWorld program Run> Run> Select your File Viduranga Jayakody Academy of Future Robotics 0760944206