___ # Tags #python #p4e #coursera #unfinished # Helpful Docs - [Python for Everyone](http://do1.dr-chuck.com/pythonlearn/EN_us/pythonlearn.pdf) book # Notes #### Chapter 1, Intro - **Reserved words** have special meaning to Python - **Variables** are when you create your own words with special meanings - Here is a list of reserved words in Python ![[Pasted image 20230123210706.png]] - `print` statements can be enclosed in single or double quotes except for when there is an apostrophe involved, it's probably best just to use double quotes to avoid this issue - `print("Hello world!"` - Congrats, this is the first script every user makes for nearly every programmatic language - **Interpreter**, reads source code written by the programmer, parses, and interprets the instructions on the fly - **Variables**, custom data that we create to be stored for later use - Example, `x = 1` - Example, `print(x)`, the output will be 1 - **Syntax errors**, a result of violating syntax within python, python can point out where the error is but sometimes that can be the tip of an iceberg since it moves through errors sequentially - **Logic errors**, these appear when your order of operations or tasks might not be optimal - **Semantic errors**, this happens when your program does not give you the intended output due to a simple error somewhere in the program itself - **Debugging**, you are going to make errors, it's fine! relax and think about the problem, take a break and come back to it - **Repeated Conditional Steps**, programming example ```python # variable storage n = 5 # checks the n variable for an integer while n > 0 : print(n) n = n - 1 # this subtracts 1 after rerunning the "n" check again print("Blast off..!") # once the while statement is met, print ``` #### Chapter 2, Variables - **Integers** - any numerical character, 1 is an integer while one is a string - **Strings** - anything containing letters, string is a string - **Float** - are numbers with a decimal - `type` - will reveal what type a value has - `type("Hello, World!)"` - This would come back as `str` for string - When you wrap anything in quotes such as "3.2", or "17" they will both come back as a string - **Variables** - is any data you store by assigning it - `example = "this is an example of a variable"` - This assigns the variable `example` the `=` output - `+, -, *, /, **` these are all examples of operators and operands - **Expression** - is a combo of values, variables, and operators - Example, `1 + 1` - **Order of Operations** - python uses PEMDAS for mathematical expressions - Parenthesis, Exponents, Mult/Div, Add/Sub - OoO happens from right to left when evaluating like-valued operators - Using `+` with strings performs concatenation - Using `*` with strings will multiply the contents of a string by an integer - **Input** - stops the program/script and waits for a user's input and save it as the variable that called it - Example, `user_input = input()` - Then whatever the user inputs will be saved as the variable `user_input` - `\n` represents a newline command and is used for linebreaking #### Chapter 3, Conditionals - **Conditional Steps** - if statements, creating programs with steps that may or may not run - Example ```python # ask user input in the form of a number, but declare the int() in front of it so python knows to receive it as an integer and not a string x = int(input("Please put in a number 1-25 \n")) # this program will show print anything less than 10 as smaller and anything bigger than 20 as bigger but will do nothing for any integer between 11-19 if x < 10 : print("Smaller") if x > 20 : print("Bigger") # program wraps up print("Finished") ``` - Indentation is huge in python, indentation outlines blocks of text for programmatic continuity - **If/Else** - you can use these reserved words to create forks in your program similar to just repeated `if x` commands like the program above - Example ```python # declare variable x = 4 # using if/else creates forks in the road for the program to navigate down if x > 2 : print ("Bigger") else : print ("Smaller") # program concludes print ("All Done") ``` - **Elif** - stands for else/if, which is a variation on the code just above this, if there is no **else** in the code it's possible that nothing executes - Example ```python # declare variables x = 150 # block of code determining how to respond to the value of x if x < 2 : print("Small") elif x < 10 : print("Medium") elif x < 20 : print("Big") elif x < 40 : print("Large") elif x < 100 : print("Huge") # print the result of all those elif statements else : print("Ginormous!") ``` - **Try-except** - a strategy in python to catch traceback errors - Using `try :` followed by the code that could blow up - This is useful for when your code might result in a traceback - The downside is that you might miss where your code is borking #### Chapter 4, Functions - **Store and reuse** - sometimes you want to recall blocks of code again without rewriting, this can be done with the following code - **Def** - "start the definition of a function", reusable chunks of code are called functions - Example ```python # this defines a block of code, anytime thing() is called it will print "Hello" and "Fun" def thing () : print("Hello") print("Fun") # this will print "Hello" and "Fun" thing () # this prints "Zip" print("Zip") # this will print "Hello" and "Fun" again thing() ``` - **Max** - this returns the "largest" of something - Example ```python max_value_example = max("Hello World!") print(max_value_example) ``` - **Def** statements do not run the code automatically, much like declaring variables, if you do not invoke them, it just gets stored and then tossed away at the end of the program - **Parameters** ![[Pasted image 20230209191555.png]] - **Return Values** ![[Pasted image 20230209192526.png]] - **Return Values, pt 2** ![[Pasted image 20230209193206.png]] - **len** - is a function that returns the number of characters in a string - **int** - can convert floating-point to whole numbers, it cannot convert strings to numbers - **float** - can convert strings and integers into floating-point numbers #### Chapter 5, Iterations - An example of an infinite loop - An infinite loop is create where there isn't some controlling variable to break out of the loop ```python # creates a variable called countdown_timer countdown_timer = 5 # introduces a loop where the "while" condition will never be satisfied because 5 will always be greater than 0 while countdown_timer > 0 : print("Launching in 5") ``` - The proper way to build a countdown timer loop would be - By introducing a controlling variable called `countdown_timer - 1` it will eventually allow the `print("Blast off!")` function to be met ```python countdown_timer = 5 while countdown_timer > 0 : print("Preparing to launch..") countdown_timer = countdown_timer - 1 print(countdown_timer) print("Blast off!") ``` - **break** - this is a statement that can be used to break out of a loop - **continue** - functions similarly except instead of breaking out of a loop entirely it moved onto the next iteration of the loop - Loops continue until a logical condition becomes false - **definite loop** - these are loops with finite iterations - Example ```python for integer in [5,4,3,2,1] : print(integer) print("Blast off!") ``` - An example of a definite loop using strings ```python friends = ["Joe", "Phil", "Amy"] for a_friend in friends : print("Happy International Donut Day!", a_friend) print("All done") ``` ![[Pasted image 20230212201005.png]] - When humans look at a loop - let's say, for the largest number in a series, we have pattern matching brains that can instantly spot a larger number instinctually - Programs have to run in sequence, so if you feed it a bunch of random numbers you can have it check the current number against all of the numbers in the sequence but it will have to do it in order - An example of a loop checking for largest number ```python # sets the value of the variable largest_so_far = -1 # compares the largest_so_far variable against the variable the_number and if the_number is bigger than largest_so_far, it overwrites it and saves the new, larger number as largest_so_far print("Before", largest_so_far) for the_number in [55, 1, 38, 96, 4, 22] : if the_number > largest_so_far : largest_so_far = the_number print(largest_so_far, the_number) # when the series of numbers is checked sequentially, it stops and prints "after" followed by largest_so_far print("After", largest_so_far) ``` #### Chapter 6, Strings - `Index operator` - when looking inside of a string you can take a string like `stamp` and break out the letters into single characters ```python # declares the variable postage = "stamp" # declares the index operator variable named letter_in_stamp to the THIRD letter in stamp because index operators start with 0 letter_in_stamp = postage[2] # this will print out the letter "a" print(letter_in_stamp) ``` - The brackets can also be an expression ```python number = 5 # this takes the string "thirty one" and uses the index operator within the brackets to call the variable "5" and subtract 2 from it, then output that result example = "thirty one"[number - 2] # this would print the letter "r" because "thirty one" broken into an index operator count where 0=t, 1=h, 2=i, 3=r, 4=t, 5=y, then subtract 2 from the index operator, which makes it "r" instead of "t" print(w) ``` - **Looping through a string** - combining a `while` statement, `iteration variable` and `len function` we can create a loop to inspect individual string characters ```python sport = 'football' letter_index = 0 while letter_index < len(sport) : letter = sport[letter_index] print(letter_index, letter) letter_index = letter_index + 1 ``` - The results of the program ![[Pasted image 20230301213946.png]] - A superior way to write the above program is using a `for loop`, these two code snippets produce the same results except one is more succinct ```python sport = 'football' for letter_index in sport : print(letter_index) ``` - **Slicing strings** - looking at a section of a string using a `colon operator` - You can drop the integer before or after the `colon operator`, this just means give me everyone before, or everything after the range you included in the brackets ```python # declare the frog variable frog = 'amphibian' # this says "show me UP TO the first 6 characters" print(frog[0:6]) ``` - Results in printing `amphib` - `for` and `in` do some background work in python, an example of this is - ```python fruit = 'apple' if 'p' in fruit : print('found the letter!') ``` ![[Pasted image 20230303195532.png]] - In this example we see the variable `greet = 'Hello Bob'` - Then we see `zap = greet.lower()` which returns `Hello Bob` because that's the variable but the `.lower` part of it returns it all in lowercase - the `.lower` is part of a string library which is modifications that you can do to the string function - `[variable_name].find` can be used search for a substring within another string ![[Pasted image 20230303204203.png]] - You can also remove whitespace with variables with `.lstrip()` or `.rstrip()` - You can also look for prefixes with `[variable_name][.startswith]` - Using the `dir` function can show you the methods available to an object such as a string #### Chapter 7, Files - Python can be used to open files and parse the data inside, write over it, format it, and modify it in other ways too - To open a file in python, you can use the `open` function and the `'r'` function to read it ```python open_mbox_text = open('/home/visitor/_archive/code/python/python-for-everybody/files/mbox.txt', 'r') print(open_mbox_text) ``` - `\n` creates a `newline`, if you put it in the middle of a string it will get stored as-is, but if you print it out it gets removed and inserts a newline where the `\n` was - Using python to count the lines within a file - ```python # declare the variable and open the file using the full file path + r to read the file open_mbox_text = open('/home/visitor/_archive/code/python/python-for-everybody/files/mbox.txt', 'r') # create a for-loop to count the number of lines in the file count_lines_in_mbox_text = 0 for line in open_mbox_text : count_lines_in_mbox_text = count_lines_in_mbox_text + 1 # print the results from the count print('Total number of lines: ', count_lines_in_mbox_text) ``` - When searching through a file you can use a `for loop` to pull back specific information you are interested in using the `[variable_name].startswith()` ```python # declare the variable and open the file using the full file path + r to read the file open_mbox_text = open('/home/visitor/_archive/code/python/python-for-everybody/files/mbox.txt', 'r') # create a for-loop to search for lines that start with 'From:' and print the results count_lines_in_mbox_text = 0 for line in open_mbox_text : # search for lines that start with 'From:' if line.startswith('From:') : # remove the whitespace that gets generated from \n newline and the print function line = line.rstrip() print(line) ``` - This results in this output - Which is okay if you don't mind all the whitespace, but we can clean that up ```results From: [email protected] From: [email protected] From: [email protected] ``` - There are multiple ways to clean this up, one way would be to use `[variable_name].replace(' ', '')` which would remove all whitespaces, another way would be to use `[variable_name].rstrip()` which removes all the whitespace from the right side of the string - Using `[variable_name].replace(' ', '')` ```results From:[email protected] From:[email protected] From:[email protected] ``` - Using `[variable_name].rstrip()` ```txt From: [email protected] From: [email protected] From: [email protected] ``` - Using `continue` to process only the lines we are interested in, other lines will just be skipped ```python # open the following file, read it, and store the outputopen_mbox_text open_mbox_text = open('/home/visitor/_archive/code/python/python-for-everybody/files/mbox.txt', 'r') for line in open_mbox_text : # remove the whitespace to the right line = line.rstrip() # skip lines that do not start with 'From:' if not line.startswith('From:') : continue # print the 'interesting' line print(line) ``` - You can also use the `[variable_name].find` string method to search for a string within a string - I'm leaving out repeating the same blocks of code over and again in favor of just the snippets that have been changed ```python # using the [variable_name].find method will search for a string within a string, similar to using find in a text editor for a string search if line.find('@uct.ac.za') == -1 : continue ``` - If you wanted to create a small program that asks the user to input the file they want open so you don't have to change your code manually every time you could do the following - ```python # input a path to a file you want open pick_a_file_to_open = input('Pick a file to open: ') opened_file = open(pick_a_file_to_open) count = 0 # count how many times a line starts with 'Subject:' for line in opened_file : if line.startswith('Subject:') : count = count + 1 # print the results of that count print('How many instances counted: ', count, 'in', opened_file) ``` - If you want to build in some graceful exiting so you aren't getting tracebacked you can add some code to give it a `try-except` functionality ```python try: opened_file(pick_a_file_to_open) except: print('Sorry pal, no file found by the name of:', opened_file) exit() ``` #### Chapter 8, Lists - A `list` is a sequence of values of any time, the values in a `list` are called `elements` - The simplest way to create a list is to use brackets, ex - `[1, 2, 3, 4]` or `['sheep', 'dog', 'cat']` - A list within another list is called `nested` - Ex - `[1, 20, 45, ['eight', 'ten']]` - You can create an empty list by not filling in the brackets `[]` - Lists are mutable, you can rearrange them or reassign the elements within it - `eth` is the place of something in the sequences of a list - A list containing `[1, 25, 8009, 67]` has an `eth` of `0, 1, 2, 3` - Using the `in` operator also works on lists