GEOG 376 Midterm (The basics of Python) PDF

Title GEOG 376 Midterm (The basics of Python)
Course Introduction to Computer Programming for GIS
Institution University of Maryland
Pages 5
File Size 98.8 KB
File Type PDF
Total Downloads 32
Total Views 127

Summary

This study guide will introduce you to some of the basic functions of Python...


Description

GEOG 376 Midterm Review I. Intro to Computer Programming A. The Crash Course  A computer program is a collection of instructions that performs a specific task when executed by a computer. It requires programs to function and is usually written in a programming language  Compiled programming: Humans write source code which is then compiled by a compiler which produces machine code—a form consisting of instructions that the computer can directly execute (e.g., C++ language)  Interpreted programming: a computer program may be executed with the aid of an interpreter (e.g., Python).  Geographers need to program for automation (Increase efficiency, Avoid human error, kill boredom), Customization, and modeling B. Program development Cycle 1. Define the problem (be sure you understand what the program should do, what the output should be and what input you need.) 2. Design the solution (find a logical sequence of steps that solve the problem, i.e. develop an algorithm.) 3. Code: write actual code in a given computer language. 4. Test and debug: test – find errors in the program, debug – correct the errors 5. Write documentation: organize the materials that describe the program. Commenting should occur as an on-going process rather than be the last step of the program. But it should be finalized once the program is completed. II. Data Types, Variables, and Operators A. Values and Variables  Values are one of the fundamental things that can be manipulated by a program. Variables can store values in the memory of the computer and to name them for later retrieval.  Variables must begin with a letter, be alphanumeric, and have no reserved words.  Integers and Floats are commonly assigned to variables (Integers can only be whole numbers while floats are decimal number and need a float command to be treated as such and can store up to 15 decimal places) 1. Bits, Bytes, and ASCII code  All values are stored as a sequence of bits with a single binary value of either 0 or 1. Bit multiples are called bytes which are usually made up of 8 bits in most computer systems. B. Strings  String: a sequence of one or more characters (letters, numbers, symbols) that can be stored in a variable. It is an immutable sequence, meaning it is unchanging  Serves as an important building block to programming since text is such a common form of data that we use in everyday life.  Strings can exists within either single quotes or double quotes, but whatever quotes you use should be consistent within the program (Do NOT start with a single quote and end with a double quote.)

Concatenation: joining strings together end-to-end to create a new string. This is done through the “+” operator. (Although the + operator is meant for addition, it is used as a join operator in strings)  Spaces make no difference to operators, but it will not work for variable names C. String Formatting and Functions  String literals are what we see in the source code of a computer program, including the quotation marks. A string value is what we see when we call the print () function and run the program.  Case function: str.title ( ) will capitalize the first letter of each word and lowercase the rest. str.upper ( ) and str.lower ( ) will return a string with all the letters of an original string converted to upper or lowercase letters.  Length: The len () function returns the number of characters in a string. It can also be used to determine where a character index is.  Join: Concatenate two strings, but in a way that passes one string through another.  Split: Splits strings and the result is a list containing two elements III. Collection Data Types A. Indexing and Slicing  Each of a string’s characters correspond to a number starting with 0. Since each character in a string has a corresponding index number, it allows us to access and manipulate strings at the character level, and isolate one of the characters in a string with square brackets.  A positive index number counts from the left of the string (even though it starts at 0) while a negative index number begins at the right of the string as -1.  Slicing is used to call out a range of characters from the string by creating a range of index numbers separated by a colon [x:y] (the first index number is where the slice starts (inclusive), and the second index number is where the slice ends (exclusive).) If we want to include either end of the string, we can omit one of the numbers in the string[n:n] syntax B. Lists  Lists are mutable (a.k.a. changeable), ordered sequence of elements  Defined as square brackets [ ]  Each element or value that is inside of a list is called an item.  Stride is a type of slicing technique that refers to which interval to display after the first item is retrieved from the list. a. Various list commands  List.append(x): adds an item(x) to the end of a list  List.insert(i, x): takes two arguments, with i being the index position you would like to add an item to, and x being the item itself.  List.extend: Used to combine more than one list  List.remove: Can remove an item from a list. It only removes the first occurrence of a value, not all of them if there are multiples  List.pop: Returns the item to the given index position from the list and then removes that item.  List.count: Will return the number of times the value x occurs within a specified list. (Useful when there is a long list with a lot of matching value.) 

List.sort: Sorts the items in a list. Just like the count command, sort an make it more apparent how many of a certain integer value we have, and it can also put an unsorted list of numbers into numeric order. C. Tuples  A restricted version of a list  They are immutable, which means that their values cannot be modified. This conveys to others that you do not intend for there to be changes to a certain sequence of values  Defined as parentheses ( )  Tuples with one value must have a comma  Most functions and methods available to lists are available to tuples except for extend, append, remove, and sort  Usually stores values of only one data type D. Dictionaries  Defined as curly brackets { }  They map keys to values in key-value pairs (the key/ variable is on the left and the value is on the right, with a colon separating them both)  Unlike lists and tuples, dictionaries do not preserve order and cannot be indexed. The order will be arbitrary, but the key-value pairs will remain intact, enabling us to access data based on their relational meaning. IV. Loops and Command statements  Loops are used to repeat a certain block (group of lines) of code a specified number of times or until a condition is met.  Loops rely on indentation  For loops implement the repeated execution of code based on a loop counter or loop variable.  They are used most often when the number of iterations are known before entering the loop. (Ex. A range of values) The range command is useful for the for loop as it controls how many times the loop will repeat  Variables used in a for loop are temporary ones created for use within the block of code to run during the loop  Nested loop: A loop that occurs within another loop A. While loops and flow control  A While loop implements the repeated execution of code based on a given Boolean condition. (Statements of the Boolean data type can either be True or False) Operator Definition == Equal to != Not equal to < Less than > Greater than = Greater than or equal to 

X and Y True and True True and False

Returns True False

False and True False False and False False True or True True True or False True False or True True False or False False  Note: Be careful with how you use while loops. If, for example, the condition of your while loop is to only stop when a number = 10 (for example)... and the number never equals 10… your loop will run FOREVER!  This can have unexpected consequences (such as halting the rest of your code or overheating your computer) B. Conditional statement  By using conditional statements, programs can determine whether certain conditions are being met and then be told what to do next.  Operates under Boolean logic like while loops  If statement: will evaluate whether a statement is true or false, and run code only in the case that the statement is true. (Uses indentation)  Else statement: This is to make sure that the code does something even when the condition of the IF statement is not met. (Usually goes hand in hand with the IF statement)  ELSE IF statement (elif): Works more as an update to the if statement and comes before an else statement V. Functions and Modules  A function is a block of instructions that performs an action and, once defined, can be reused. This makes a code more modular, allowing you to use the same code over and over again.  Defined using the def keyword, followed by a name of our choosing, a set of parentheses that will hold any parameters the function will take (they can be empty), and ending with a colon. A return statement might be added at the end to pass an expression back to the caller.  Parameter: a named entity in a function definition, specifying an argument that the function can accept.  It is recommended to create a function if there is a block of code that will get run multiple times (Programmers are lazy and will try to find shortcuts to running code). Make sure that you define the function before you call it in your script A. A closer look at modules  Although Python comes with a built in set of functions, you can also use modules for a more in-depth analysis. They can contain definitions of functions and variables that can then be utilized in other Python programs.  They can be accessed via the import statement, allowing us to execute the code of the module, keeping the scopes of the definitions so that your current file(s) can make use of these.  When we import a module, we are making it available to us in our current program as a separate namespace. This means that we will have to refer to the function in dot notation, as in [module].[function]



Although you can import as many modules as you want, it can make your python program more bloated since modules require the allocation of memory...


Similar Free PDFs