lesson1-4.pdf
Document Details
Uploaded by WellSphinx
Tags
Full Transcript
What is Python? High-level, interpreted programming language Created by Guido van Rossum and released in 1991 Known for its simplicity and readability Widely used in AI, ML, web development, automation, and more...
What is Python? High-level, interpreted programming language Created by Guido van Rossum and released in 1991 Known for its simplicity and readability Widely used in AI, ML, web development, automation, and more What can Python do? Python can be used on a server to create web applications. Python can be used alongside software to create workflows. Python can connect to database systems. It can also read and modify files. Python can be used to handle big data and perform complex mathematics. Python can be used for rapid prototyping, or for production-ready software development. Why Python? Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc). Python has a simple syntax similar to the English language. Python has syntax that allows developers to write programs with fewer lines than some other programming languages. (Interoperability with other languages/tools) Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick. Python can be treated in a procedural way, an object-oriented way or a functional way. Python vs Other Languages Python was designed for readability, and has some similarities to the English language with influence from mathematics. Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses. Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose. Why Python for AI and ML? Simplicity and readability: Easy to learn and write Extensive libraries: Pre-built libraries like Numpy, Pandas, TensorFlow, Scikit-learn, and Keras Active community support: Large and active Python community for AI and ML Platform independence: Python runs on various platforms (Windows, macOS, Linux) Integration capabilities: Works well with other languages and tools Python Basics Variables and data types: Strings Integers Floats Booleans Comments and syntax rules Python Syntax and Structure Python uses indentation (not braces {}) to define code blocks Case-sensitive language No need for semicolons to end statements Python Comments Single-line comments: Use # before the comment text Multi-line comments: Use triple quotes (''' or """) Purpose: Comments help explain code and improve readability Data Types in Python Basic data types: Numbers Strings Booleans Collections: Lists Tuples Dictionaries Sets Data Types in Python Example Data Type x = "Hello World" str (String) x = 20 int (Integer) x = 20.5 float x = ["apple", "banana", "cherry"] list x = ("apple", "banana", "cherry") tuple x = {"name" : "John", "age" : 36} dict (Dictionary) x = {"apple", "banana", "cherry"} set x = True bool (Boolean) Control Structures in Python Conditional Statements: if elif else Loops: for loop while loop Basic Input and Output Output: Use the print() function to display text or variable values Input: Use input() function to capture user input Python Variables Python allows you to assign values to multiple variables in one line: And you can assign the same value to multiple variables in one line: Python Collection If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables. This is called unpacking. Getting the Data Type You can get the data type of any object by using the type() function: Python Conversion There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-oriented language, and as such it uses classes to define data types, including its primitive types. Python Casting There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-oriented language, and as such it uses classes to define data types, including its primitive types. Casting vs Conversion Type Casting: In typing casting, a data type is converted into another data type by the programmer using the casting operator during the program design. In typing casting, the destination data type may be smaller than the source data type when converting the data type to another data type, that’s why it is also called narrowing conversion. Type conversion : In type conversion, a data type is automatically converted into another data type by a compiler at the compiler time. In type conversion, the destination data type cannot be smaller than the source data type, that’s why it is also called widening conversion. One more important thing is that it can only be applied to compatible data types. Casting vs Conversion Casting Conversion In type casting, a data type is converted into Whereas in type conversion, a data type is another data type by a programmer using converted into another data type by a compiler. casting operator. Type casting can be applied to compatible data Whereas type conversion can only be applied to types as well as incompatible data types. compatible datatypes. In type casting, casting operator is needed in Whereas in type conversion, there is no need for order to cast a data type to another data type. a casting operator. In typing casting, the destination data type may Whereas in type conversion, the destination data be smaller than the source data type, when type can’t be smaller than source data type. converting the data type to another data type. Casting vs Conversion Casting Conversion Type casting takes place during the program Whereas type conversion is done at the compile design by programmer. time. Type casting is also called narrowing conversion Whereas type conversion is also called widening because in this, the destination data type may be conversion because in this, the destination data smaller than the source data type. type can not be smaller than the source data type. Type casting is often used in coding and Whereas type conversion is less used in coding competitive programming works. and competitive programming as it might cause incorrect answer. Type casting is more efficient and reliable. Whereas type conversion is less efficient and less reliable. Python Conditional Statements Python supports the usual logical conditions from mathematics: Equal a == b Not Equals a != b Less than a= b Python Conditional Statements An "if statement" is written by using the if keyword. Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose. Python Conditional Statements The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition". Python Conditional Statements The else keyword catches anything which isn't caught by the preceding conditions. Shorthand If ○ If you have only one statement to execute, you can put it on the same line as the if statement. Python Loops Python has two primitive loop commands: ○ while loops ○ for loops With the while loop we can execute a set of statements as long as a condition is true. WHILE LOOP With the break statement we can stop the loop even if the while condition is true: With the continue statement we can stop the current iteration, and continue with the next: WHILE LOOP With the else statement we can run a block of code once when the condition no longer is true: FOR LOOP Python Loops A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). FOR LOOP This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-oriented programming languages. With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. The for loop does not require an indexing variable to set beforehand. FOR LOOP Even strings are iterable objects, they contain a sequence of characters: With the break statement we can stop the loop before it has looped through all the items: Exit the loop when x is "banana". Exit the loop when x is "banana", but this time the break comes before the print. FOR LOOP With the continue statement we can stop the current iteration of the loop, and continue with the next: To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. FOR LOOP The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6): The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3): FOR LOOP The else keyword in a for loop specifies a block of code to be executed when the loop is finished: The else block will NOT be executed if the loop is stopped by a break statement. A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop": FOR LOOP for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error. LESSON 3 - PYTHON FUNCTIONS Functions A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. In Python a function is defined using the def keyword: Functions A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. In Python a function is defined using the def keyword: To call a function, use the function name followed by parenthesis: Arguments Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name: Arguments Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name: Arguments are often shortened to args in Python documentations. Arguments Parameters or Arguments? The terms parameter and argument can be used for the same thing: information that are passed into a function. By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less. Arbitrary Arguments, *args If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition. This way the function will receive a tuple of arguments, and can access the items accordingly: Keyword Arguments You can also send arguments with the key = value syntax. This way the order of the arguments does not matter. The phrase Keyword Arguments are often shortened to kwargs in Python documentations. Arbitrary Keyword Arguments, **kwargs If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition. This way the function will receive a dictionary of arguments, and can access the items accordingly: Functions - Default Value The following example shows how to use a default parameter value. If we call the function without argument, it uses the default value: Functions To let a function return a value, use the return statement: function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error. Functions You can specify that a function can have ONLY positional arguments, or ONLY keyword arguments. To specify that a function can have only positional arguments, add , / after the arguments: To specify that a function can have only keyword arguments, add *, before the arguments: Functions You can combine the two argument types in the same function. Any argument before the / , are positional-only, and any argument after the *, are keyword-only. LESSON 4 - FILE HANDLING FILE HANDLING File handling is an important part of any web application. Python has several functions for creating, reading, updating, and deleting files. The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode. There are four different methods (modes) for opening a file: SYMBOL WORD DESCRIPTION “r” Read - Default value Opens a file for reading, error if the file does not exist “a” Append Opens a file for appending, creates the file if it does not exist “w” Write Opens a file for writing, creates the file if it does not exist “x” Create Creates the specified file, returns an error if the file exists FILE HANDLING In addition you can specify if the file should be handled as binary or text mode SYMBOL WORD DESCRIPTION “t” Text Default value. Text mode “b” Binary Binary mode (e.g. images) To open a file for reading it is enough to specify the name of the file: FILE HANDLING - OPENING FILE Assume we have the following file, located in the same folder as Python: To open the file, use the built-in open() function. The open() function returns a file object, which has a read() method for reading the content of the file: FILE HANDLING - OPENING FILE If the file is located in a different location, you will have to specify the file path, like this: By default the read() method returns the whole text, but you can also specify how many characters you want to return: FILE HANDLING - READ FILE You can return one line by using the readline() method: By calling readline() two times, you can read the two first lines: FILE HANDLING - READ FILE & CLOSE FILE By looping through the lines of the file, you can read the whole file, line by line: It is a good practice to always close the file when you are done with it. FILE HANDLING - WRITE FILE To write to an existing file, you must add a parameter to the open() function: SYMBOL WORD DESCRIPTION “a” Append will append to the end of the file “w” Write will overwrite any existing content FILE HANDLING - CREATE FILE To create a new file in Python, use the open() method, with one of the following parameters: SYMBOL WORD DESCRIPTION “x” Create will create a file, returns an error if the file exist “a” Append will create a file if the specified file does not exist “w” Write will create a file if the specified file does not exist FILE HANDLING - DELETE FILE To delete a file, you must import the OS module, and run its os.remove() function: To avoid getting an error, you might want to check if the file exists before you try to delete it: FILE HANDLING - DELETE FOLDER To delete an entire folder, use the os.rmdir() method: Note: You can only remove empty folders.