unit 3 lecture and code python
how to left justify?
"%-nums" % "stirng or output" num is length of feild s bc its a sting and the - signifies left justofy
how to use formating for floating numbers?
"%num.palcesf" % data num is the length of feild .places is teh number of places after the decimal and f is for float note this is different than the round function (print(round(p, 2)) and you can use the len() function to easily see the length of somthing to see how long to make the feild width in the formatting. stirng formmatting commands temporarily store the data
how do you right justify?
"%nums" % "string" the num is the feild length and the s is bc its a string
while loop simple explanation for steps
1. A while loop evaluates the condition 2. If the condition evaluates to True, the code inside the while loop is executed .3. condition is evaluated again if the updated interation varibale is still true 4. This process continues until the condition is False. 5. When condition evaluates to False, the loop stops.
how many spaces is indentation
4, but teh number of spaces can be anyting its up to user, but must be a minumum of 1 space first line cant be indented and the indentation must be consistant trhoughout the entire script of code dont use tabs!!! can mess up indentation and give errors
list of comparison operators
< Less than <= Less than or Equal to == Equal to >= Greater than or Equal to > Greater than != Not equal
counter
A counter variable is created and initialized to a starting value before the loop is started. The condition that is tested before each iteration of the loop is whether the counter has reached a predetermined value. The counter itself is incremented inside the while loop, to adjust the count
largest_so_far = -1 print('Before', largest_so_far) for value in [9, 41, 12, 3, 74, 15] : if value > largest_so_far : largest_so_far = value print(largest_so_far, value) print('After', largest_so_far)
Essentially for this code, we have a larger number and we print that out before the we look at the list value will take on the value of the numbers in the list sinquentially (list have [ ]) if the new value is larger than the previous value we want to update the largest do far to that new large number. for teh for loop, we want to print out the new value for largest so par and teh cuurent value of the value variable (value wll be 9, then next loop, 41 etc). fianlly once the for loop is completed, we print the no matter what print statement exentially "We make a variable that contains the largest value we have seen so far. If the current number we are looking at is larger, it is the new largest value we have seen so far."
is and is not operators
Python has an is operator that can be used in logical expressions• Implies "is the same as"• Similar to, but stronger than ==• is not also is a logical operator
two way decisions
Sometimes we want to do one thing if a logical expression is true and something else if the expression is false • It is like a fork in the road - we must choose one or the other path but not both they include the else statement
steps for making smart loops
The trick is "knowing" something about the whole loop when you are stuck writing code that only sees one entry at a time Set some variables to initial values for things in data: Look for something or do something to each entry separately, updating a variable Look at the variables
iteration variables
While loops (repeated steps) have iteration variables that change each time through a loop. Often these iteration variables go through a sequence of numbers.
definite loops
a for loop for loop is called a "definite loop" because it execute an exact number of times. • for loop iterates over a set of items. can be used for a list or range that are finite "definite loops iterate through the members of a set" Definite loops (for loops) have explicit iteration variablesthat change each time through a loop. These iteration variables move through the sequence or set. the iteration varible must move through all values in the sequence
how are lists defined ?
a list of valued between square brackets
while True:
a loop that is continuously True and therefore runs endlessly. It will never stop until you force it to stop. true is the condition for the loop other examples had a condition like X>5 this just simply states that the while loop will run at least one while true loops typically have a nested if statement
indefinite loops
a while loop while loops are called "indefinite loops" because they keep going until a logical condition becomes False • The loops we have seen so far are pretty easy to examine to see if they will terminate or if they will be "infinite loops" • Sometimes it is a little harder to be sure if a loop will terminate
Assignment Operator
allows a program to change the value represented by a variable even = even + 1 or shortcut even += 1
a = float(input("Enter the first side: ")) b = float(input("Enter the second side:")) c = float(input("Enter the third side: ")) if a**2==b**2+c**2 or b**2==c**2+a**2 or c**2==b**2+a**2 : print("The triangle is a right triangle.") else : print("The triangle is not a right triangle.")
another if else statment that takes inputs and prints out what triangle it is if the first if statment is met, we will be done, but if not met it prints second statement
what is the output of this code for i in range (0,10,2): print (i, end = " ") print ()
answer: 0, 2, 4,6,8 explination i will take the value of each number in the range that starts at 0 and ends at 9 (10-1), when increasing by 2's it wont include 10 and 9 is not an increase by 2 which is why it stops at 8. the end = " " ensures that all of the i values will be printed on one line (otherwise they would print vertically) the no matter what print statement is just to print an extra blank line
Boolean expressions
ask a question and produce a Yes or Noresult which we use to control program flow
two way decisions ex: x = 4 if x > 2 : print('Bigger') else : print('Smaller') print('All done')
bc x is 4 and is greater than 2, it will print bigger, and then it skips the else statments and prints out the no matter what print statement if x were 1, it would check if teh if statement was true- since its not, it skips and goes to the else statement, which then will print, then it prints that last unindented print statement
to exit a loop prematurely use the ______
break
how to excape an infinate loop?
control+c
def prediction(): organism = int(input("Enter the initial number of organisms: ")) rate = float(input("Enter the rate of growth [a real number > 1]: ")) while(rate < 1): print("Use a real number > 1.") rate = float(input("Enter the rate of growth [a real number > 1]: ")) period = int(input("Enter the number of hours to achieve the rate of growth: ")) totalHours = int(input("Enter the total hours of growth: ")) NewOrganism = organism hours = 1 while (hours < totalHours): NewOrganism *= rate hours += period print("The total population is", NewOrganism) prediction()
explain
import math smaller = int(input("Enter the smaller number: ")) larger = int(input("Enter the larger number: ")) Maxguess= math.log(larger-smaller+1) +1 count = 0 while True: count += 1 print (smaller, larger) myNumber = ((larger+smaller)//2) print("Your number is", myNumber) userNumber = input("Enter =, <, or >: ") if count > Maxguess: print("I'm out of guesses, and you cheated") break elif userNumber == ">": smaller = myNumber + 1 elif userNumber == "<": larger = myNumber - 1 else: print("Hooray, I've got it in", count, "tries!") break myNumber = ((larger+smaller)//2)
first we import math so we can use its function we ask for a few initial inputs and then we set the intial level for the changing varibale we enter the while true statement which has many other nested statements inside it while the loop runs we want count to increase by one ask for help explaining
difference between for and while loops
for knows number of iterations can end early via break or skip with continue uses an iteration variable can always rewrite a for loop using a while loop while loop: unbounded number of iterations can end early via break or skip with continue can use a counter, but must initialize before loop and increment it inside loop may not be able to rewrite a while loop using a for loop
found = False target = 3 print('Before', found) for value in [9, 41, 12, 3, 74, 15] : if value == target : found = True break print('After', found)
here we are setting to values before the loop and printing them before then we jump into the for loop where value will take on a new value each iteration wile running through the for loop, if teh value is = to 3 teh criteria is met and its true and then we break the if statment finally after knowing the statement is true, one value takes on teh value of 3 at interation 4, the whol loop will end and will print the no matter what statement
a= float(input("Enter the first side: ")) b= float(input("Enter the second side: ")) c= float(input("Enter the theird side: ")) if a==b and b==c : print("The triangle is equilateral.") else : print("The triangle is not equilateral.")
here we are simply asking for some inputs the we have an if else statement that says if teh sides are equal to piunt one thing and then be done, but if they arent equal to print the second part.
nested decisions example x = 42 if x > 1 : print('More than one') if x < 100 : print('Less than 100') print('All done')
here we have a numer 42 so since 42 is greater than one it pirnts the more than one statement it then looks to see if it is less than 100 and if it is it will print that out finally since all done is not indented, it gets printed anyways
_count = 0 _sum = 0 print('Before', _count, _sum) for value in [9, 41, 12, 3, 74, 15] : _count += 1 _sum += value print(_count, _sum, value) average = _sum / _count print('After', _count, _sum, average)
here we have two variables we want to track so we have them before the loop. then we want to print them out then we just to the loop value is going to run through the list and take the values each time it goes through loop after getting a new value, we want to increase teh count by one and also add to the sum variable and print them out each time then once the loop is done we want to find the average and then print the no matter what statement
simple definite loop example for i in [5, 4, 3, 2, 1] : print(i) print('Blastoff!')
i is the explicit iteration variable that changes each time by just taking on the value of each item in the set in order it prints i which will be 5, then 4 and so on once it iterates through every part of list it is done and prints the no matter what prints statement
simple syntax for condition statement
if condition: intended statement black If the condition is true, then do the indented statements
indentation with conditions and loops for print statement
if the print statement is in the block (indented inside the if), that means that it will be executed, only if the statement is true. if the print in not indented, (even with the if) it will be printed no matter what
break statement
its a statement that ends the current loop and jumps to the statement immediately following the loop can happen anywhere in the body of a loop
can there be an infinite loop within a for construct
no this is bc a for construct us predetermined
if or is used in a condition
only one of the statements has to be to be true for the block of code to execute look at weather example
formating a print statment
print ("formting,formatting" % the thing you want to print) ex if have two collumns to format it looks like this print("%-3d%12d" %(exponent, 10 ** exponnet)) in this example the first collumn is left alignad nad teh second collumn is right alligned the we print what goes in each collum colum one will list the exponent and collum two will list the actuall number ist d bc its an integer
range function
returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
multiway example if x < 2 : print('small') elif x < 10 : print('Medium') else : print('LARGE') print('All done')
say x = 5 it would skip first statment bc not true it would then go to elif statement and since its true the print is ran, it then skips over the else and then prints all done say x=0 it is true for first statemenet so it runs and skipps teh other two and prints all done if x = 20 it will skip the first 2 statements bc they are false, since neither of teh first two statements are true, it has to be teh else statement, then it prints all done
continue statement example while True: line = input('> ') if line[0] == '#' : continue if line == 'done' : break print(line) print('Done!')
since while true, this just means teh statement will be true and run unless its broken ist asking for an input from users and the next line signicals if teh first letter starts wuth # to contiue back to the begeining of the loop and try again. but is loop doesnt have # we will go through rest of code, if it doesnt have done entered, it wil simply print the line and go back up to the top until the loop is broke (by someon typing done) this will then skip down and print the no matter what statement done
x = 5 if x > 2 : print('Bigger than 2') print('Still bigger') print('Done with 2') for i in range(5) : print(i) if i > 2 : print('Bigger than 2') print('Done with i', i) print('All Done')
since x is greater than 2 the first 2 print statements will be printed, and then the 3rd one will be too bc its unindented which means it get sprinted no matter what. for the first print (i), this will happen for any thing in the range. but it is a nested loop, so for anything that is is the range that is bigger than 2, it will print larger than 2 the pint done with i is unidented back to the if statement bc it will will be executed no matter what (but only if its apart of teh for loop) laststly all done print no matter what bc it is not indented at all. this is teh output Bigger than 2 Still bigger Done with 2 0 Done with i 0 1 Done with i 1 2 Done with i 2 3 Bigger than 2 Done with i 3 4 Bigger than 2 Done with i 4 All Done
continue statement
statement ends the current iteration and jumps to the top of the loop and starts the next iteration
if and is used in a condition
that means both conditions must be true to run the statement look at slides for weather example
break statement indentation
the break statement must be indented under the statement it is for so when its in the if statement its part if teh block and then is indented
Which will never print regardless of the value for x? if x < 2 : print('Below 2') elif x >= 2 : print('Two or more') else : print('Something else')
the else statement will never print bc any number will be smaller or greater than or equal to 2
range with 2 arguments in function ex range (2,5)
the first number is now the start and the later number is the end of the range -1 (4)
if 3 arguments in range function ex range (1,5,2)
the first number is the start the second number is the end -1 and the last number is the increments, so this range increments up by 2
what's wrong with this loop? n = 0 while n > 0 : print('Lather') print('Rinse') print('Dry off!')
the loop is never entered bc n = 0 it will never be greater than 0 so teh loop will never run
what is wrong with this loop n = 5 while n > 0 : print('Lather') print('Rinse') print('Dry off!')
the loop will never end. its an infinite loop this is bc there is no change to the iteration variable meaning it will alwasy be 5 which will alwasy be greater than 0
multiway decisions
these use if, elif and else (else isnt required, there just wont be a certain action for it)
nested decisions
they are an if decision within an if decision.
simple break loop example while True: line = input('> ') if line == 'done' : break print(line) print('Done!')
this code is asking for an input from user if that line is equal to done, then we break the loop and go streight down to the no matter what print statement
examples salesAmt = 1100 if salesAmt >= 1000 : commissionRate = .08 elif salesAmt >= 500 : commission Rate = .06 else : commissionRate = .05
this code says if sales amount is larger than 1000 use 8% if not larger than 1000 check to see if larger or = to 500 and use 6% othereise we will use the 5% rate.
range definite loop example # Iterating over range 0 to n-1 n = 4 for i in range(n) : print(i) print('Done!')
this means i is going to take on the value of each number in range of n the n range is 0,1,2,3 this is bc it starts at 0 (unless told otherwise) and counts to n-1 which is 3 once i has completed moving in the range, it is done with loop and then the no matter what print statement is completed.
example of repeated steps n = 5 while n > 0 : print(n) n = n - 1 print('Blastoff!') print(n)
this starts out with n = 5 since 5>0 it prints teh number n (which is 5) then runs though the calculation which changes the interation varibale to 4 then it check again is 4 is true and loops though until n is no longer greater then 0 it then prints teh no matter what print statements of blastoff and the new value of n
one argument in a range function ex: range(5)
this will default start at 0 and then go until range-1 (4)
Boolean expressions using comparison operators evaluate to
true/false or yes/no
one way decisions
use just an if statement, if the statement is correct if flows to the next statement, if not it skips the block of code
multiple conditions
uses an or not
x = 5 if x < 10: print('Smaller') if x > 20: print('Bigger') print('Finish')
we have x which is 5 since x is less than 10 we want to print smaller, then since 5 is less than 10 it doesnt meet the second if statemnt so it flows down to the end print statement
smallest = -1 print('Before', smallest) for value in [9, 41, 12, 3, 74, 15] : if value < smallest : smallest = value print(smallest, value) print('After', smallest)
we set our variable we want to track outside the loop and print it the we jump into the for loop and value takes on teh vlaue of each number each itteration within the for loop is value is less than teh smallest number we want smallest to take that value at the end of each itteration of the for loop, we want to print the numbers finally once for loop is completed, we want to print the no matter what statement
using the is and is not operator example smallest = None print('Before') for value in [3, 41, 12, 9, 74, 15] : if smallest is None : smallest = value elif value < smallest : smallest = value print(smallest, value) print('After', smallest)
we set our varibale to non to start with and print it the we enter teh foor lopp to start we check if smallest is none if it i we want smallest to take on the new value of value if its not non, and value is smaller than smallest we want to to take on the new value the each iteration of the for loop we want to print smallest finally after the loop is done we want to print the no matter what print statement "The ==operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory." We still have a variable that is the smallest so far. The first time through the loop smallest is None, so we take the first value to be the smallest.
ss = float(input("Enter starting Salary: $")) api = float(input("Enter anual percengate increase: ")) years = int(input("Enter number of years: ")) #make sure the print function format is correct and order!! print("Year Salary") for i in range (1, years+1): print (i, "\t", end="") print ("%.2f"% ss) ss = ss * (1+api/100)
we start by asking for some input varibales then we print the title of the table the we wnter a for loop we are usng the range starting at 1 and go through number of years from the input plus 1 (bc teh range would be less than number inputted by 1) then as i is iterating though the loop each time we want it to print its value (year 1) and the ask for explaination
repeated steps
we use a loop
complex condistions
when an if statement conatins many and, or or not we use parenthases to entitle what is looked at first look at slide 27
_sum = 0 print('Before', _sum) for value in [9, 41, 12, 3] : _sum += value print(_sum, value) print('After', _sum)
with this code we have a count type of variable which we have to set prirar to loop, and we want to print it then we have the value take on the value of all of the numbers in a list then we want the sum varible to add the new value to itself every time it takes on a new value. then we print the sum, value for each time through teh loop( where value takes on a new value) fianlly once the for loop is complete, we print the no matter what print statement "To add up a value we encounter in a loop, we introduce a sum variable that starts at 0 and we add the value to the sum each time through the loop. Note: sum is a built-in function of Python. While you can define a variable named sum, it's best not to use built-in function names as variable names. That's why our variables name is _sum to avoid overwriting sum."