


























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



























What is a Program? A program is a sequence of instructions that specifies how to perform a computation. Though the details look different in different languages, a few basic instructions appear in just about any language: Input, Output, Math, Conditional Execution and Repetition.
Python is a High Level Language (i.e. a language that is designed to be easy for humans to read and write).
Computers can only execute programs written in a Low Level Language (i.e. a language that is designed to be easy for a computer to execute; also called machine language or assembly language).
So how does the computer understand the code I have written in a high level language? The compiler does that important job! A compiler is a special program (or a set of programs) that transforms the source code written in a high level programming language (source language) into the object code written in a low level computer language (target language) that the computer’s processor can use.
What is debugging? Programming errors are called bugs and the process of tracking them down and correcting them is called debugging. Three kinds of errors can occur in a program:
language). A syntax error is an error in the syntax of a program that makes it impossible to parse and compile.
Comments A comment in a computer program is text that is intended only for the human reader – it is completely ignored by the interpreter. In Python, “#” token starts a comment.
What is an algorithm? It is a set of specific steps for solving a category of problems.
VALUES, VARIABLES and DATA TYPES
A value is one of the fundamental things that a program manipulates. They are classified into different classes or data types.
Some basic data types are:
“type” function: To find out what “class” a value falls into use the “type” function.
Variable: A variable is a name that refers to a value. I. Variable Naming Rules: Variable names can be arbitrarily long. Variable names can contain letters, underscores and digits, but they have to begin with a letter or underscore. “case” matters when naming variables. II. The assignment operation: The assignment statement gives a value to a variable. >>>message = “What’s up?” (“=” is the assignment operator) Note: The assignment statement binds a name (on the left) to a value (on the right). It evaluates the expression on the right first and then makes the assignment of that value to the variable. >>>n = 5 >>>n = n+ This statement may look weird if you think about it as a mathematical expression. How can “n” equal “n+1”? Understand that the “=” token is not the usual equal to symbol in math, here it assigns the value on the right to the variable on the left. So it evaluates the expression on the right first (i.e. n+ = 5+1 = 6) and now reassigns the value 6 to “n”. So, after executing the two statements above “n” holds the value 6.
Mathematical Operation The order of evaluation depends on the “Rules of Precedence”.
a) Order: left to right b) Priority: PEMDAS (Parentheses > Exponentiation > Multiplication = Division = Modulo > Addition = Subtraction) When two operations have the same precedence, then we evaluate from Left to Right. Addition: + Subtraction: - Multiplication: * Integer Division: // (answer will be an integer) The integer division (or floor division) always gives a whole number as a result and in order to adjust, it always moves to the left of the number. Floating Point Division: / (answer will be a float) Power: ** Modulo: % This operator works on integers and yields the remainder when one number is divided by another.
an integer.
HOWEVER, using integer division (//) with a float will yield the integer answer as a floating point rather than the correct decimal approximation. In other words, it will do integer division, but return it as a float (see example for better understanding). e.g.: 11/3 = 3. 11/3.0 = 3. 11//3 = 3 11//3.0 = 3.0 *instead of 3.6, integer division gives the integer answer (3) converted to a float (3.0)
Operations on Strings In general, you cannot perform mathematical operations on strings, even if the strings look like numbers.
There can be any number of parameters separated by commas and enclosed in parentheses. The parameter specifies what information, if any, we have to provide in order to use the new function.
Note that defining a new function does not make a function run. To do that we need a function call. Function calls contain the name of the function being executed, followed by a list of values called arguments which are assigned to the parameters in the function definition.
>>>addTwoNums(5,10) The sum of the two given numbers is 15.
Variables and Parameters are local. When we create a local variable inside a function, it only exists inside the function definition and we cannot use it outside. In the example above, if we try to use x or y outside the function, we’ll get an error. >>>a Name Error: name ‘x’ is not defined The variables x and y are local to addTwoNums function and are not visible outside the function. When execution of the function terminates, the local variables are destroyed.
Functions that return a value are called fruitful functions.
Function call Output
def name(): name = input(“Enter your name”) return name
def addTwoNums (x,y) : sumOfNum = x + y print (“The sum of the two given numbers is ” + sumOfNum + “.”)
Since this function returns a value stored in the variable “name”, it means that when I call this function it will return/store a value (in this case, a string) and to use that value further in my program I can assign it to a variable. The return statement is followed by an expression that will be evaluated and returned to the caller as the “fruit” of calling this function. >>>result = name() >>>print(“The result is ” + result)
The opposite of a fruitful function is a void function – one that is not executed for its resulting value but is executed because it does something useful.
This function displays the value stored in the variable “age” on the screen but does not store/return it.
Even though void functions are not executed for their resulting value, Python always wants to return something. So, if the programmer doesn’t arrange to return a value, Python will automatically return the value “None”. >>>result = age() >>>print(result) 18 None Huh? What happened? It should print just 18 why does it print None as well? To understand this subtle point, we need to understand the difference between print and return (more detailed in next section). Explanation: In Step 1 - The function age() is being called and the value it returns is being assigned to result. On calling age(), the function gets executed (recall that the right side is evaluated first) and on executing the
def age(): age = 18 print(age)
>>>tester() Hey #Notice no quotes when printed ‘Bye’ #Notice quotes when returned >>>x = tester() Hey #Notice, now only Hey is printed because the value returned is assigned to a variable >>>x ‘Bye’ #Here it returns the value stored in x, hence the quotes >>>print(x) Bye #Now the value stored in x, i.e. the value returned by the function is printed hence no quotes
Example: def testing(): print(“1”) return 2 print(“3”)
>>>testing() 1 #Notice no quotes since it is printed 2 #Notice no quotes since the value returned is not a string, it is an int #Notice 3 is not printed to the screen because once the function hit the return statement, it stopped executing further statements >>>y = testing() 1 #Notice now only 1 is printed because the value returned is assigned to a variable >>>print(y) 2 #Now the value stored by the function is printed to the screen
Example: def test(): print(“Hello World”)
>>>result = test() Hello World #Notice when this assignment is made, the right side is evaluated first and test() function is called as a result Hello World is printed to the screen
>>>print(result) None #Now the value stored in the function is printed to the screen. Since this function does not contain any return statement it implicitly returns None and therefore None is printed to the screen
CONDITIONALS
A Boolean value is either True or False.
A Boolean expression is an expression that evaluated to produce a result which is a Boolean value. >>>2 == 3 False
Logical Operators There are three logical operators - and, or, not; they allow us to build more complex Boolean expressions from simpler Boolean expressions. and
or
not not True = False not False = True
Order and Priority Order: left to right Priority: parentheses > not > and > or
Conditional Statement: A statement that controls the flow of execution depending on some condition.
True False True True False False False False
True False True True True False True False
y = 6 if (x > y) : #if family 1 print(“Python is hard”) elif (x == y): #still if family 1 print(“Python? The snake right?”) else: #yup if family 1 print(“Python is cool”) if (x == 3): #if family 2 print(“Hey”) elif (x == 4): #if family 2 print(“Yo”) if (y == 3): #if family 3 print(“Sup?”) else: #if family 3 print(“I love CS 1301”)
>>>tester() Python is cool Hey I love CS 1301
Short Circuit Evaluation: o The expression on the left of the “or” operator is evaluated first; if the result is True, Python does not (and need not) evaluate the expression on the right. o For the “and” operator, if the expression on the left yields False, Python does not evaluate the expression on the right. o This is called Short-Circuit evaluation.
ITERATIONS
Iteration: Repeated execution of a set of programming statements.
for loop
The for loop processes each item in a sequence. Each item in turn is (re-) assigned to the loop variable and the body of the loop is executed.
The statements will be executed for every item in aSequence. For each execution, the variable identifier defined by the programmer (item) will be assigned to point to the next item in the sequence, and may be used to refer to it in the block of statements. At the end of the for loop, the variable will remain pointing at the last item in the sequence.
Example: >>>for i in [“Joe”, “Sam”, “Jacob”]: print(i) Joe Sam Jacob
while loop
The statements will be executed repeatedly until the Boolean expression becomes False.
When using while loop, do not forget to initialize the counter before the loop and do increment/decrement in the loop. Example: >>>x = 0 #where to start >>>while x < 5: #end as x becomes greater than or equal to 5 print(“Hey”)
for item in aSequence: statements
while aBooleanExpression: statements
The continue statement: This is a control flow statement that causes the program to immediately skip the processing of the rest of the body of the loop, for the current iteration. But the loop still carries on running for its remaining iterations. >>>for i in [12,16,17,24,29,30] if i % 2 == 1: continue #If the number is odd print(i) #Don’t process it print(“done”) This prints: 12 16 24 30 Done
The range function range(x) – returns a list of numbers from 0 up to but not including x. >>>range(4) [0,1,2,3] range(start,stop) – returns a list of numbers from start up to but not including stop. >>>range(5,11) [5,6,7,8,9,10] range(start,stop,step) – returns a list of numbers from start up to but not including stop with an increment of step. >>>range(5,11,2) [5,7,9]
BINARY CONVERSIONS
Definition
Binary (base 2): 10011 = 124 + 023+ 022+ 121+ 12* Octal-decimal (base 8): 725 = 782 + 281 + 58* Decimal (base 10): 342 = 3102 + 4101 + 210* Hexadecimal (base 16): C1A = 12162 + 1161 + 1016*
General process: Decimal Binary Octal-decimal / Hexadecimal ** You can do octal-decimal / hexadecimal to decimal conversion by a general process (convert to binary version first and then to decimal).
Decimal Binary Example: 156(base 10) to base 2 Step 1: Divide 156 by 2. Write down the result and the remainder as following:
Step 2: Keep doing this for all the quotients until you get 0 for quotient. Step 3: Copy the remainders in a reverse order.
Binary Decimal Example: 1011101 (base 2) to base 10 Step1: calculate by definition 1011101 (base 2) = 126 + 025 + 124 + 123 + 122 + 021 + 12* Result: 1011101 (base 2) is 93 (base 10)
aVariable [ start : ] Slice everything after start E.g. x = “python” x[2:] = “thon”
aVariable [ : stop ] Slice everything before stop E.g. x = “python” x[:4] = “pyth”
aVariable [ start : stop ] Slice from start (included) to stop E.g. x = “python” x[1:5] = “ytho”
aVariable [ start : stop : step ] Slice from start to stop with common difference step E.g. x = “python” x[1:5:2] = “yh”
aVariable [ : : step ] Slice everything with common difference step E.g. x = “python” x[::-1] = “nohtyp” x[::2] = “pto”
String Formatting Format operator: The % operator takes a format string and a tuple of values and generates a string by inserting the data values into the format string at the appropriate locations.
>>>print(“My name is {} and I weigh {:.2f} pounds”.format(“Aaron”,109.9622))
My name is Aaron and I weigh 109.96 pounds Types: d and i for decimal integer .nf for float with n decimal places ( .n is optional) s for string
Strings are immutable which means you cannot change an existing string. The best you can do is create a new string that is a variation on the original and re-assign it to the same variable. >>>x = “Hello World” >>>y = “J” + x[1:] >>>x = y >>>print(x) Jello World
The “in” and “not in” operator The “in” operator tests for membership. When both the arguments to “in” are strings, “in” checks whether the left argument is a substring of the right argument. >>> “ap” in “apple” True >>> “pa” in “apple” False #The order of characters must also match The “not in” operator returns the logical opposite results of “in”. >>> “x” not in “apple” True
Useful Methods upper: It is a method that can be invoked on any string object and create a new string, in which all characters are in uppercase while the original string remains unchanged. x = “hello” y = x.upper() >>>y HELLO >>>x