🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Cognate-1-Introduction-to-Python.docx

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

**Week 1 -- Introduction to Python** Most PCs and Macs come with Python pre-installed. To verify if Python is installed on a Windows PC, enter the following command in the Command Prompt (cmd.exe): C:\\Users\\Your Name\>python \--version If Python is not installed on your computer, you can downl...

**Week 1 -- Introduction to Python** Most PCs and Macs come with Python pre-installed. To verify if Python is installed on a Windows PC, enter the following command in the Command Prompt (cmd.exe): C:\\Users\\Your Name\>python \--version If Python is not installed on your computer, you can download it for free from the official website: **RUNNING A PYTHON CODE** There are several ways to run Python code: 1. **Running a Python File from the Command Line:** - Write your Python code in a.py file using a text editor. - Open the command line (Windows, Mac, or Linux). - Navigate to the directory where the.py file is saved. - Run the file using the command: python filename.py 2. **Using the Python Command Line (Interactive Mode):** - Open the command line and type python (or py on some systems) to start the Python interpreter. - Write and execute Python code directly in the command line. - Example: 3. **Using an Integrated Development Environment (IDE):** - Write and run Python code within an IDE such as PyCharm, VS Code, or IDLE. - The IDE provides tools to run the Python file directly within the environment. - Use an IDE for larger projects, advanced features, and when you need productivity tools. - Use IDLE Shell for learning, quick tests, simple scripts, and when you prefer a lightweight environment. **PYTHON INDENTATION** Python Indentation - Indentation refers to the spaces at the beginning of a code line. - Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. - Python uses indentation to indicate a block of code. - The number of spaces is up to you as a programmer, the most common use is four, but it has to be at least one. **PYTHON COMMENTS** Comments - In Python, you can add comments within your code to serve as in-code documentation. To create a comment, begin the line with a \#. Anything following this symbol on the same line will be treated as a comment and ignored by Python when the code runs. - For multi-line comments, you can either start each line with a \# or use triple quotes (\'\'\' or \"\"\"). However, the triple quotes are technically not comments but rather a multi-line string that is not assigned to a variable, so it is ignored by the interpreter. **Week 2 -- Python Basics** **PYTHON VARIABLES** Variables - Variables are containers for storing data values. - Variables do not need to be declared with any particular *type*, and can even change type after they have been set. Casting - If you want to specify the data type of a variable, this can be done with casting. - *E.g. zip code* - int() - str() - float() Naming Rules - A variable name must begin with a letter or an underscore (\_). - A variable name cannot begin with a number. - Variable names can only include alphanumeric characters and underscores (A-Z, a-z, 0-9, and \_). - Variable names are case-sensitive, meaning age, Age, and AGE are treated as three distinct variables. - A variable name cannot be a reserved Python keyword *(e.g class, def).* - camelCase, PascalCase, snake\_case Additional Info: - Python allows you to assign values to multiple variables in one line. - You can assign the *same* value to multiple variables in one line. Output Variables - The Python print() function is often used to output variables. - You can use '+' and ',' symbols to output multiple variables. --------------------------------------------------------------------------------------------- \+ , -------------------------------------------- ------------------------------------------------ Spaces must be manually added in strings:\ Automatically adds a space between variables:\ print(\"Hello \" + \"World!\") print(\"Hello\", \"World!\")\ **Output:** Hello World! Adds numeric values:\ Prints multiple numbers with spaces:\ print(5 + 10)\ print(5, 10)\ **Output:** 15 **Output:** 5 10 Requires explicit conversion:\ Automatically handles mixed types:\ print(\"Age: \" + str(25))\ print(\"Age:\", 25)\ **Output:** Age: 25 **Output:** Age: 25 --------------------------------------------------------------------------------------------- **DATA TYPES** - str: A string data type that represents a sequence of characters, such as text. Strings are enclosed in quotes (e.g., \"Hello\"). - int: An integer data type that represents whole numbers, both positive and negative, without any decimal points (e.g., 5, -3). ![](media/image2.png) - float: A floating-point data type that represents numbers with decimal points (e.g., 3.14, -0.001). - bool: A boolean data type that represents one of two values: True or False. It is used for logical operations. ![](media/image4.png) - list: A collection data type that holds an ordered sequence of items, which can be of different types. Lists are mutable and are defined using square brackets (e.g., \[1, 2, \"apple\"\]). - dict: A dictionary data type that stores key-value pairs, where each key is unique. Dictionaries are defined using curly braces (e.g., {\"name\": \"Alice\", \"age\": 25}). ![](media/image6.png) - set: A collection data type that holds an unordered collection of unique items. Sets are defined using curly braces or the set() function (e.g., {1, 2, 3}). - tuple: An ordered collection data type similar to a list, but tuples are immutable, meaning they cannot be changed after creation. Tuples are defined using parentheses (e.g., (1, 2, \"apple\")). **PYTHON NUMBERS** - There are three numeric types in Python: int, float, complex Int - Int, or integer, is a whole number, positive or negative, without decimals Float - Float, or \"floating point number\" is a number, positive or negative, containing one or more decimals. Complex - Complex numbers are written with a \"j\" as the imaginary part. **PYTHON STRINGS** Strings - In Python, strings can be enclosed in either single quotes (\') or double quotes (\"). Both methods are equivalent and can be used interchangeably. - You can assign a multiline string to a variable by using three quotes. - Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. Square brackets can be used to access elements of the string. - In Python, strings are immutable. This means that once a string is created, its content cannot be changed or modified. Any operation that seems to modify a string actually creates a new string rather than altering the original one. Slicing Strings - You can extract a range of characters from a string by using slice syntax. By specifying the start index and the end index, separated by a colon, you can return a specific part of the string. - By leaving out the start index, the range will start at the first character. - By leaving out the *end *index, the range will go to the end. - Use negative indexes to start the slice from the end of the string **PYTHON LISTS** Lists - Lists are used to store multiple items in a single variable. It is one of 4 built-in data types in Python used to store collections of data. - Lists are created using square brackets. - List items can be of any data type - A list can include elements of various data types - Lists can have items with the same value Accessing List Items - List items are indexed, allowing you to access them by referring to their index number. - Negative indexing starts from the end of the list, where -1 refers to the last item, -2 to the second-to-last, and so on. - You can specify a range of indexes to access a portion of the list by defining the start and end points of the range. - If you omit the start index, the range will begin from the first item in the list. - If you omit the end index, the range will continue to the last item in the list. Replacing List Items - Additional info: To check if a specific item is present in a list, you can use the in keyword. - To change the value of a specific item, refer to the index number - To replace the values of items within a certain range, create a list with the new values and assign it to the corresponding range of index numbers where you want the changes to occur. \*\* Add List Items - To add a new item to a list without replacing any existing values, you can use the insert(index, item) method. - To add an item to the end of the list, use the append() method Remove List Items - The remove() method deletes the specified item from the list. If multiple items have the same value, only the first occurrence is removed. - The pop() method removes the item at the specified index. If no index is provided, it removes the last item in the list. - The clear( ) method empties the list, leaving it with no content, but the list itself still exists. - The del keyword can also delete the list completely Loop Lists - You can loop through the list items by using a for loop **PYTHON TUPLES** Tuples - Tuples are used to store multiple items in a single variable. It is one of 4 built-in data types in Python used to store collections of data. - Tuples are written with round brackets - Tuple items can be of any data type - A tuple can include elements of various data types - Tuples can have items with the same value Accessing Tuple Items - You can access items in a tuple by using the index number within square brackets. - Negative indexing allows you to start from the end of the tuple. - You can define a range of items by specifying the start and end index. - If you omit the start index, the range will begin from the first item. - If you omit the end index, the range will continue to the last item in the tuple. - Additional info: To check if a specific item is present in a tuple, you can use the in keyword. Update Tuples - Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created, but there are some workarounds. Joining Tuples - To join two or more tuples, you can use the + operator **PYTHON DICTIONARIES** Dictionaries - Dictionaries are used to store multiple items in a single variable. It is one of 4 built-in data types in Python used to store collections of data. - Dictionaries are written with curly brackets and have keys and values. ![](media/image8.png) - Dictionary items have a defined order, and that order will not change. - Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created. - Dictionaries cannot have two items with the same key Accessing Dictionary Items - You can access the items of a dictionary by referring to its key name, inside square brackets. - There is also a method called get() that will give you the same result. - Additional: The keys() method will return a list of all the keys in the dictionary while the values() method will return a list of all the values in the dictionary Replacing Dictionary Items - You can change the value of a specific item by referring to its key name - The update() method will update the dictionary with the items from the given argument Adding Dictionary Items - Adding an item to the dictionary is done by using a new index key and assigning a value to it - The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added. Removing Dictionary Items - The pop() method removes the item with the specified key name. This will result into an error if you did not pass an argument. - The del keyword removes the item with the specified key name Loop Dictionaries - When looping through a dictionary, the return value are the *keys* of the dictionary - You can also use the values() method to return values of a dictionary - You can use the keys() method to return the keys of a dictionary - Loop through both *keys* and *values*, by using the items() method **Week 3 -- Python Control Flow Statements** **PYTHON CONDITIONS AND IF STATEMENTS** Review of the usual logical conditions: - - - - - - These conditions can be used in several ways, most commonly in \"if statements\" and loops. - An \"if statement\" is written by using the if keyword, followed by the logical condition, and a colon. - The elif keyword is Python\'s way of saying \"if the previous conditions were not true, then try this condition\". - The else keyword catches anything which isn\'t caught by the preceding conditions. - If you have only one statement to execute, you can put it on the same line as the if statement. - If you have only one statement to execute, one for if, and one for else, you can put it all on the same line. **PYTHON LOGICAL OPERATORS** - The 'and' keyword is a logical operator, and is used to combine conditional statements && - The 'or' keyword \|\| - The not keyword is used to reverse the result of the conditional statement. ! **PYTHON LOOPS** Python has two primitive loop commands: - while loops - for loops **While Loop** - With the while loop we can execute a set of statements as long as a condition is true. Remember to always have a statement that will stop the loop, or else it will continue forever. (Incrementing the indexing variable/using the break statement) ![A white background with black and red text Description automatically generated](media/image10.png) - With the break statement we can stop the loop even if the while condition is true. - With the else statement we can run a block of code once when the condition no longer is true. - With the continue statement we can stop the current iteration, and continue with the next. **For Loop** - A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). - This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages. - With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. 1. Looping Through a String - Even strings are iterable objects, they contain a sequence of characters. 2. 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. - The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter. - 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. **PYTHON FUNCTIONS** - A function is a block of code which only runs when it is called. - In Python, a function is defined using the def keyword. - To call a function, use the function name followed by parenthesis. - Information can be passed into functions as arguments. - A parameter is the variable listed inside the parentheses in the function definition. - An argument is the value that is sent to the function when it is called. - By default, a function must be called with the correct number of arguments. - 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. (Arbitrary Arguments) - You can also send arguments with the *key* = *value* syntax. This way the order of the arguments does not matter. (Keyword Arguments) - Default parameter value - To let a function return a value, use the return statement. **PYTHON LAMBDA** - Small anonymous function - Syntax: lambda *arguments *: *expression* - Lambda functions can take any number of arguments. **EXCEPTION HANDLING** - When an error occurs, or an exception as we call it, Python will normally stop and generate an error message. - The try block lets you test a block of code for errors. - The except block lets you handle the error. - If the try block raises an error, the except block will be executed. - You can execute a special block of code for a special kind of error. - You can use the else keyword to define a block of code to be executed if no errors were raised. - The 'finally' block, if specified, will be executed regardless if the try block raises an error or not. - You can choose to throw an exception if a condition occurs. - The raise keyword is used to raise an exception. **PYTHON FILE HANDLING** - The key function for working with files in Python is the open() function. - The open() function takes two parameters; *filename*, and *mode*. - Syntax: f = open(\"filename\", \"mode\") **1. Read Mode (r) -- Default Value:** Scenario: You have an existing file with stored data that you want to access without modifying it. Example: You are reading student grades from a pre-existing file for analysis. You don't need to change anything in the file; you only need to read the data. Why: Since you\'re only reading the data, you wouldn\'t want to accidentally overwrite or modify the file. **2. Append Mode (a):** Scenario: You are logging data or adding new entries to an existing file without altering the current content. Example: You\'re keeping a daily log of user activity in an application. Each time an action occurs, you append new log entries to the existing log file. Why: This mode ensures that you preserve previous data and only add new data at the end of the file. **3. Write Mode (w):** Scenario: You need to create or overwrite a file with new content. Example: You want to generate a fresh report based on new data, and you don\'t need the old content anymore. You can overwrite the existing report file with new information. Why: This mode is useful when you want to ensure the file contains only the latest data, and any old data is irrelevant. **4. Create Mode (x):** Scenario: You need to create a new file but want to avoid overwriting an existing one. Example: You\'re generating a unique configuration file for a specific setup and want to ensure that if a file with that name already exists, an error is raised (to prevent accidentally overwriting important configuration files). Why: This mode helps prevent accidental data loss by ensuring that the file is only created if it doesn't already exist. **PYTHON READ FILES** - The open() function returns a file object, which has a read() method for reading the content of the file - By default the read() method returns the whole text, but you can also specify how many characters you want to return. - You can return one line by using the readline() method - It is a good practice to always close the file when you are done with it **PYTHON WRITE FILES** - To write to an existing file, you must add a parameter to the open() function: - \"a\" - Append - will append to the end of the file - \"w\" - Write - will overwrite any existing content **PYTHON CREATE FILES** - To create a new file in Python, use the open() method, with one of the following parameters: - \"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 **PYTHON 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. Do this with os.path.exists() function

Use Quizgecko on...
Browser
Browser