UNIT 2 code and lecture notes python
what was the first ever coding system
SCII (American Standard Code for Information Interchange)
integer division result in
a float number alwasy
variables
a named place in the memory where a programmer can store data and later retrieve the data using the variable "name" ou can change the contents of a variable in a later statement (by updating them)
reserve word
a word specific to the language
Assignment Statements
assigns value to variable using = it has an expression on the right side and the stores it in the name of the variable on the left
what happens when you put both an integer and a float in an expression?
the result would be converted to a float
literal
the way a value if a data type looks to a programmer
numeric expression %
modulus or remainder ex: 13 % 2 = 1 this is bc 13/2 = 6*2= 12 and one left over. alwasy remebr order which is PEMDAS and you go left to right
popular python packages
numPy Pendulum MoviePy pandas Matplotlib (look at definitiosn on slides)
the int() function is part of what
Pythons built in functions
which of these will python give an error? '98'+10 '98'+ str(10) print('98') int('98') + 10
'98'+10 this gives error because 98 is a sting and 10 is an int, and you cannot add them. '98'+ str(10) this will print out 9810 because they are now both strings and it adds them together. print('98') this just prints 98 int('98') + 10 this will convert 98 to an integer and then it can add them together to get 108
constants
Fixed values such as numbers, letters, and strings, because their value does not change
<string 1> + <string 2>
Glues the two strings together and returns the result. Concatenating
spyder is a ______
IDE or integreated development enviornment
library
Library is a collection of packages.
module
Module is a file that contains Python code. Similar code is put together into a single module. It is easy to reuse code that is in the same module.
Python Script
Most programs are much longer, so we type them into a file and tell Python to run the commands in the file. the file acts like a script and ends in .py
rules for variable names
Must start with a letter or underscore _ • Must consist of letters, numbers, and underscores • Case Sensitive • Cannot be a reserved word give variables meaningful manes
package
Package is like a folder that holds sub-packages and modules. While we can create our own packages, we can also use one from the Python Package Index (PyPI) to use for our projects.
why is python popular?
Python is easy to learn and use Python has many libraries and frameworks Python is free open-source Python is used in data science and machine learning Python has a highly supportive community Python is flexible and reliable Python automates tasks well
best way to format and structure python code
Start with an introductory comment stating the author's name, the purpose of the program, and other relevant information. This information should be in the form of a docstring. Then, include statements that do the following: Import any modules needed by the program. Initialize important variables, suitably commented. Prompt the user for input data and save the input data in variables. Process the inputs to produce the results. Display the results.
some built in modules we discussed in lecture
They are loaded automatically as a shell starts and are always available, print () input() int() float()
import math radius = float(input("Enter the radius: ")) area = math.pi * radius**2 print ("the radius of your circle is", "{:.6f}".format(area)) output is: Enter the radius: 5 the radius of your circle is 78.539816
This code first imports math because i want to use a more accurate pi number than just 3.14 I then prompt the user to enter their radius as a float. I then calculate area using the variable we got from the user input I want to display to the user so I print, but I only want to use a cirtain number of decimal points so I use teh format function to display only 6 decimal places.
# The next three lines ask the user to input the sides of the triangle and strore them in variables 'a', 'b', and 'c'. # Since the 'input' function produces a 'string', we use the 'float' function to convert the strings to floating-point (fractional) numbers. a = float(input("Enter a: ")) b = float(input("Enter b: ")) c = float(input("Enter c: ")) s = (a + b + c)/2 # Semi perimeter of the triangle. White spaces in 'a + b + c' are for readability. area = (s*(s-a)*(s-b)*(s-c))**0.5 #Area of the triangle using Heron's formula. print("Area is:", area)
This will prompt the user to inter a float number for a b and c the the s is a variable used in calculation the we find the area (sequential code) how python reads this is it evaluates the math on the right side and assigns that value to the area variable finally we will print area out. this print statement puts out a string and then displays the variables number
Script
You enter a sequence of statements (lines) into a file using a text editor and tell Python to execute the statements by running the file this is the better way, use for longer code
interactive
You type directly to Python one line at a time, and it responds like we did in IDLE Shell or will do in Spyder Console
character set
a complete set of the characters and their number codes that can be recognized by a computer. This is also called a Coding System
type conversion example print(float(99) + 100) 199.0 >>> i = 42 >>> type(i) <class'int' >>>> f = float(i) >>> print(f) 42.0 >>> type(f)<class'float'
becaue it is an integer and a float it becomes a float i is an integer type but we can create a new variable and convert i to a float and when it gets printed, its a float
""" """ or \n
can be used to make multi lines
sequence
code is run in a sequence line by line
what is this bit of code doing? zxhftsi = 6.0 xsiofnc = 2.5 fggths = zxhfts * xsiofnc print (fggths) displying fggths displaying 15 assigning values calculations
displaying 15 displays the value of the variable which is the two other variable multiplied by each other
how to convert a number to a string?
ex: >>> i = 42 >>> type(i) <class'int' >>>> s = str(i) >>> type(s) <class'str '>>>> s + '10' >>> '4210' i is an int. we can convert I to string using a new variable and suing str(i) now that we want to add them togther, it is just two strings do the numbers are just merged togther and not added.
simple assignment variable example X= .6 x = 3.9 * x * ( 1 - x )
first the expression is evaluated so they solve for it then that value is now stored within teh varibale x
in python when dividing two numbers you get what?
float
how do you import all module resources without using the qualifier?
from module import * ex: from math import *
how do you use just a select few resources form a module, and avoid the qualifier?
from module import and list resources ex: >>> from math import pi, sqrt >>>print(pi, sqrt(2))3.14159265359 1.41421356237
Radious = float(input("Enter sphere radious: ")) import math pi = math.pi Diameter = 2 * Radious Circumference = Diameter * pi SurfaceArea= 4 * pi * Radious ** 2 Volume = 4/3 * pi * Radious ** 3 print("Diameter : " + str(Diameter)) print("Circumference: " + str(Circumference)) print("Surface are : " + str(SurfaceArea)) print("Volume. : " + str(Volume))
here we are asking for the user input we also gave made math.pi a vaiable so we coudl just use pi then we did the math for each thing we wanted to find and then we print it out, again we use the +str but could just use a comma note, this all happens sequentially and at teh same time as soon as teh radius is entered, all 4 of teh print statements are executed at teh same time
print("His power level is over", plvl, sep="...", end ="?!") His power level is over...9000?!
here we are using a print function. the , separates the string and then displayes teh number the sep = " " this means that the separation bereen teh sringa dn number is equal to what inside it "..." and then end = " " is just used to put the explitives at the end.
Year = 365 Day = 24 Hour = 60 x = Hour * Day * Year print("The number of minutes in a year is " + str(x))
here we create our variables then we create a new variable that does the math then we print that new varible
seconds = 365 * 24 * 60 ** 2 rate = 3 * 10 ** 8 x = seconds * rate print("Light Travels", str(x), "meters in a year.")
here we create varibles the we create a new varible that does the math the we print it out
Python is ______ language
high level
which of these is an invalid variable name _if if If IF
if
Use the round function to modify the program to display at most two digits of precision in the output number.
incomeTax = round(taxableIncome * TAX_RATE, 2) the round function goes in a varibale, after the expression, say how many numbers you want it to round to.
types of data
integers, real numbers, character strings
complex numbers
is a number that can be expressed in the form a + bi, where a and b are real numbers, and i represents the "imaginary unit", satisfying the equation. Because no real number satisfies this equation, i is called an imaginary number.
string literals
is a sequence of characters enclosed in single or double quotation marks " " is an empty string
Integrated Development Environment
is software application that provides comprehensive facilities to programmer for code development
variable
location in memory we use to store content names
what are the pieces of a computing statement
reserve words variables constants
conditional
some lines of code may be skipped if condition is not met. like an if statement
elements of python code
story structure (constructing a program for a purpose) Vocabulary / Words - variables and reserved words Sentence structure - valid syntax patterns
input functions always returns a
string thats why we have to clarify if we need it a number we can use a type conversion function eg: usf = int(inp)+1 or we can go float(input("expression"))
using * in strings
the * operator allows you to build a string by repeating another string a given number of times. ex: " " *10 + "Python results in ' Python' the " " is an empty syring and thw * 10 says to repeat that string 10 times and the we concatentation the two strings togther
inp = input('Europe floor?') usf = int(inp) + 1 print('US floor', usf)
thei code prompts a user to input a floor number (it we be returned as a string tho) next we convert ut into an integer so we can add 1 the we print it results look like Europe floor? 0US floor 1 this is becuase the issuer inputed 0 and the code ran and printed out a 1
Old = 2.00 New = 3.00 NewMovies = int(input("Enter the number of new videos: ")) OldMovies = int(input("Enter the number of old videos: ")) TotalCost = NewMovies * New + OldMovies * Old print("The total cost is $" + str(TotalCost))
this code starts with some variables we then prompt the user to enter the number of movies form each category then we calculate the total cost then we print out the total cost note we converted it to a string and contenated the two strings, but we could have just ended the string and put a comma and then the variable
x = 2
this is an assignment statement. it means x is 2
x = 2 x= x + 2
this is assignment with an expression you have x = 2 then x = x (which is 2) + 2 which is 4. now if you were to print x the variable would be updated to 4
sequential step code x = 2 print(x) x = x + 2 print(x)
this will run teh first print function and output a two, it will then evaluate x+2 (which will take x (2) + 4) and reassign the value to x and print out the new value of ex output: 2 4
numeric expression **
to the power
repeated steps example n = 5 while n > 0 : print(n) n = n - 1 print('Blastoff!')
we have n which = 5 while n is greater than 0 we want the following step to repeat which is print the value of n, next we reassign the value of n to n - 1. it jumps back up to the top and n now = 4 n is greater than 0 so it goes through the steps again, which will now make n = 3 and it will repeat until n = 0 since this means n is no longer greater than 0 it will then skip the middle steps and print blast off
conditional step code ex: x = 5 if x < 10: print('Smaller') if x > 20: print('Bigger') print('Finis')
we know x = 5 if x (which is 5) is less than 10 it will print smaller. if x greater than 20 (its not at 5) so it wont print out greater. and will skip down to the final step which is the last print statement if x was 11 it would skip the first part and do the second part
concatenate
when + is used to merger strings togther ex: number >>> ddd = 1 + 4 print(ddd) 5 eee = 'hello ' + 'there' print(eee) hello there if you try and add a number and a string you will get an error
loops
when a step (written code) needs to be repeated
when do you have to use a module qualifier? (module.resourse)
when you just import it at the top ex: import math have to use math.pi
'This very long sentence extends\nall the way to the next line.'
where the \n is where the new line starts note, it you do not use a print function, you will still be able to see the \n also note the \n goes inside the string
"""This very long sentence extends all the way to the next line.""
where the enter is signifies a new line with 3 """
reserve words
words that you can not use as a varibale name bc they have a function/meaning in python already
floating point formatting a certian number of decimals
you use str.format() "{:.nf}".format (enter variabel you want to format) the f reprecents a floating number n reprecents any number