Lecture 2 - BPP
Document Details
Uploaded by Deleted User
Tags
Related
- Python Programming Fundamentals PDF
- Meeting 2 - Fundamentals of Python Programming - s.en.ar.pptx PDF
- Cours Python - Programmations: Concepts Fondamentaux - Pratique (PDF)
- CS 110: Computer Science Fundamentals Week 4 PDF
- CS 110: Computer Science Fundamentals Expressions and Arithmetics Lec06_expressions01 PDF
- Python – Podstawy Programowania PDF
Summary
These lecture notes cover fundamental concepts of the Python programming language, including variables, data types, functions, and lists.
Full Transcript
🏕️ Lecture 2 The Console: Text only computer interface 1. Printing to the console so Key Words: function = predefined so it will do whatever the function is designed to do! Print = BLUE KEY WORD (will alwa...
🏕️ Lecture 2 The Console: Text only computer interface 1. Printing to the console so Key Words: function = predefined so it will do whatever the function is designed to do! Print = BLUE KEY WORD (will always print the word on the console) Everything in “” is syntax = can add whatever you want in it. the Comma , will automatically put pace in between *(There is no limit to how many words after comma) NONE: key word, because a function doesn’t give any output. None is a keyword for nothing VOCAB: 1. Console: Area for text based interaction with the computer (Command line) 2. Keyword: Special reserved words that have a set of meaning to python 3. Function: A pre-defined set of behavior that can be run 4. Call: When we run a function (code) 5. Arguments: The data provided to the function, which affects how it runs Python specific: Parameters Lecture 2 1 Also known as: Input but this is a different functions. 6. Variable: A store of Value 7. 🍎 Variables = “A store of value” a=5 (Variable a is storing the value of 5) Declaring Variables in python= variable name = variable Value Ex: (Name a,b,c) (Value 6,7,8) question: a5 = 5.0 b6 = 4 a5 = b6 Print ("a5") 4 =. Because now a5 gets the value of b6 (a5=b6) (cannot be numbers, start with a a letter then have a number) The process of giving variables value is called assignment Variable Types: 1. Variables can have different types= … Static VS. DYNAMIC TYPING TYPING as in “to find the type of something” NOT “Typing on a keyboard” Static = Have to declare the type of a variable beforehand. A number declared as an integer will always have to be an integer. Dynamic = Can be any number doesn’t have to do. Integer = Whole Number ex. 5, 108, 129, 11 Float = Decimal number ex. 5.0, 120.5, 1.1. 0.003 String = Holds text ex. Hello world (Green in pycharm) Lecture 2 2 Boolean = True/false ex. only true/false (nothing else) T ype()fUNCT ION Funtion to determine the type of variable Only takes 1 argument Returns the type of argument Returning: When the function occurs - function finishes. It’s the output of a function Iprint() Functions: Functions: Follow a defined pattern of behavior They all return something TheType= type(5) 5 ➡️ type ➡️ print = class - int Why do we need to know the type? 1. Compatibility = What happens if we add”hello+5? Operations: On numerical variables Subtraction Multiplication Division Modulus What happens when you combine different variable types? a= 5 b= 5.0 type (a+b)( you get a float) Division will always come back a float. Lecture 2 3 division (/) Print (a%b) = % modulus sign T heLENfunction : A function that takes a string as an argument can also take a list and few other varibale types Returns the length of the argument Cannot have numbers in this!!! But will return a number! An integer Addition (between a number and a string) hello+5 = error Parsing = converting one data type to another Lists : Special Variable type that consists of other variables Examples: 1, 2, 5, 3] [5.0, 4.9, 5.0] Lists are type independent = can but everything in a list. Arrays = Type specific(static)= Can only have one type inside it. Index= The index is where a value in a list is stored. Indices = always numbers Indices = always start at 0 The length of a indices = 4. The last item will have an index of the length -1 Access items in lists: Structure: ListName[index] Lecture 2 4 “Lists start with 0” = First Item of the list = 0 Accessing Items at the end of a list: two options: ListName[len(ListName)-1] ListName[-1] (Class)InternalF unctions These are functions that are internal to a variable type (class) They are defined as a part of that class/data type So not keywords to python, but sort of a keyword to a class Can only be run on variables of that type Have a slightly different format Append=Not a keyword, thus we need to tell python what append is! (Thus we need to tell python where to find it) ☎️ The. = where things are! ALIST.APPEND ("DOG") AList.Append (”Dog”) Lecture 2 5 Append Vs. Extend = On.quiz!! Lecture 2 6 ☂️ Lecture 3 cmd + /mac Input Returns what the person writes on the console. It can take 0 or 1 arguments Userinput= input() Print(Userinput) Parsing strings to integers "5" -> int -> 5 UserInput = input ("What is your favorite number?") type_of_user_input= type(UserInput) print (type_of_user_input) Userinput = input("what is your favorite number") print("Your number plus five is: ") Lecture 3 1 user_input_as_int = int(UserInput) print(user_input_as_int+ 5) Avariable = 5 Avariable = str(Avariable) Avariable = 10.9 Avariable = int(variable) # this cannot be done with a boolea Parsing a varibale to itself a = int (a) b= float (b) c= str Control Flow: if statements to determine if a code should run or not. if conditon. #if is a condition. In this case, this condition is a compari iif a==b ##if condition : eeverything that is with the tab- is within withint the tab eOnly indent inside of the environment LFirst line that is not indented -thus will run outside the e Conditons: ALL conditions are boolean values!! Comparisons == < > ≤ > Booleans All conditions are boolean values Lecture 3 2 A condition can either be True (it runs) or False ELSE else is outside the if environment if the (if) statement is false then the else will run. ELIF Elif = "Else if" Will check the first one and then run the rest of the code! Negating Conditions if not false: Combining Conditions (ON QUIZ)!! a= True b= False c= true d= true if(a and b)and(c or d) print("how does this condition evaluate?") Remember: = Assignment ==Comparison Lecture 3 3 🚎 Lecture 4 Foundations: 5 core fundamental concepts loops control flow variables classes/objects functions Next week is about errors! Why we import: Base Python is very robust (but it cant do everything) Why not have all code available all the time? Random numbers: TheVar = random.random() The name fo a variable. This can be anything that isn't a key.Notation = used to access internal information (like internal Before the DOT = name of the library. Random Integers First Attempt = int(random.random()) int function always rounds down!! so it gets rid of the decima Random Integers: SecondAttempt = int(random.random()*9) random.random = produces a Random = Produces a float number between 0-1 between 0-1 exclusive Lecture 4 1 📌 LOOPS Loops to run sections of code multiple times Control flow statements (if - elif - else), loops change the order that our code runs in (specifically, allow us to repeat code without keyword in python. Tells python = so long as the while loop = condition is TRUE, run the code in the environment on a loop. (if statements that repeat) a==b: == this is the condtition. Python While skip this section of code when the condition is false = code For Loops = 2 elements: Example = [8,7,8,9] for number in Example: print(number) iterating variable : This changes will every iteration Iterable variable: This contatins a series of data that can be iterated over (lists) Lecture 4 2 →anything you can do with a while loop you can use a for loop! Range() range (0,1,2,3) Range = keyword in python. Tells python “take between 1-3 integer arguments, and create a range of integers) Ranges are iterable! Range can have one argument - it will Infinite For Loop: Lecture 4 3 Use for loop whenever you know how many time you want to iterate before you start the loop Use a while when you don’t know how many times you want to loop before the start of the loop. → Assigning variables inside of a loop you can accidentally reset your variable. Key word: Continue→ goes to the beginning of the loop Break→ skip this section of code when the condition is false (break ends the loop) Vocab for the week: iteration Lecture 4 4 🔦 Lecture 5 Hardcoding: Design a program with parameters that cannot be altered This is like building a program that does not change with the input Often makes bad assumptions Often lose edge cases String Manipulation: AnewString= "Hellow World" Print(ANewstring Some_string = "This is a string" print(some_string) String = an iterable variable. for a in some_string: print(a) The number to left indicates where to start: indicates where Lecture 5 1 *Python does not allow for you to change the variable = strings are immutable! 📌 Combining variables: 📌 Dictionaries: Every entry in a dictorionary is a key value pair! This is used to access the value. Dictionaries have a curly bracket!! You can name the variable whatever you want! Accessing Items in Dictionary Value = ItemDict[key] Lecture 5 2 Dictionaries Can NOT be keys Lists can NOT be keys Note: Lists and dictionaries Almost everything else can be can be values KEYS have to be UNIQUE! Changing Items in a Dictionary: TheDict = {“key”: “False”, “Strange:6, 6:A”} print(TheDict) TheDict[ “Newkey”] = True print (Dict) Complied Language: High level Language → compiling → Machine Code → execution → Output Machine code = generally can be run by a computer without having some kind of software relatd to the high level language installed. Compiled languages are turned into some kind of executable file that is then run (Need a program called a compiler to create the executable) Lecture 5 3 (Once the executable is created, it can generally be run without other software) Two main types of errors. Python is NOT a complied language - you have to send the source code. Python = Interpreted Language High level Language → Interpreter → Output Interpretation is similar to compiling = it requriees a special program The difference is no intermediate executable is created InterpreterErrors : Errors caused by the programmer (Problem with how the code is written) Code won’t run at all with an interpreter error Pycharm very clearly tells you when you are making an interpreter error Interpreter errors are very easy to avoid - if you are writing coe in an IDE RuntimeErrors : Errors that occur while code is running Runtime errors cause the code to quit Generally caused by the user Bad programming design can also cause Runtime Errors MyDict = {"Key":[True], "slight" : 7, 5:"B"} try: print(MyDict["NewKey]) except: print("That key is not in the dictionary") Lecture 5 4 Bugs Similar to runtime error, in that they occur during runtime! Generally do not cause the program to quit Unintenderd behavior (program stills runs, but not in a way you were expecting! Debugging Strategies: → Setting stop points in Pycharm (Allows you to stop your code at a certain point, just to prevent it from finish, so you have time to examine what is going on) → Littering your code with print statements Print out variable values print out variable types print out that code has reached a certain point Very useful when there’s a peskey if statement that won’t run → Google your error Changes are someone will have faced it and have an idea of how to fix it → Stackoverflow Can post your error and gen an explanation Cipher ROT13 → Want to modify text to either encrypt or decrypt. Lecture 5 5 🌉 Lecture 6 Raising errors: String Manipulation 🚧 Split() Internal function Accessed using dot notation on a string variable Takes one string as argument Returns a list of strings seperated by the argument Lecture 6 1 This is useful to separate certain values from a list CSV → (comma, seperated value) Functions Lecture 6 2 Functions in programming: Variables = store of value Functions = store of process 2 parts to the function : F unctionDeclaration F unctioncall where the function is defined where the function is run what happens when the function runs. Lecture 6 3 Declaring our own functions: Used for: Clean up code Repeated process Similar to declaring variables, but for processes We declare variables so that we don’t need to re-declare values every time in our code We declare functions so that we don’t need to re-declare processes every time in our code 🚧 def *The name of the function cannot be a keyword. → When the fuction code is defined, it doesnt run it’s just saved. → thus it will run the code sequentially. Function Arguments: This is how info is gotten from outside the fuction to inside of the function. Lecture 6 4 Functions can return stuff, so they are more usuful: → Remember to do something with the returned value, this value can be printed. return ends the function, so the code after the return will not run! This is the same as a break in a loop! Lecture 6 5 Function Scope: The scope of a function is where the variables of the function come from Variables can be entirely internal These variables are declared/assigned inside the function environment And only exist inside the function environment Variables can be passed as arguments These variables are declared outside the function and then provided as arguments to the function Functions should be self enclosed If you need a variable in a function, you need to pass that variable to the function Don’t use variables declared outside a function that have not been passed to the function This is a very easy way to make really bad mistakes Lecture 6 6 → Define the variable always inside of the function. → Define A as an argument Printing is NOT returning Function Call Vs. Declaration/definition: → Function call has to happen AFTER the function has been declared. Lecture 6 7 Homework: Dont use input function! Dont ask for user input! Use test code to write! Use spilt: Use return Submit a.py file Don’t submit error code! Lecture 6 8