knowt logo

Python!

  • Python is an interpreter, translating code line by line rather than as a whole. It translates the source code into machine code, which then is run through the CPU and output on a display

  • Python IDLE is what we use to run command line interface code. The python editor is just a blank text, where the python shell has text and goes line by code. The command line is shell, but the editor takes all of the code

  • Functions:

    • def__(): and __()

      • Variables can be stored in the (), like name, which may change over the course of a program. Every time the function is run, the variable will source the current data stored in the variable. The variable is called a formal parameter. Multiple variables can be put into the function.

      • If a function has a variable assigned in its definition, different things can be called to be used in it. The variable is the formal parameter, and the substitutions are value or actual parameters that get assigned to the variable automatically. If strings are assigned, they are called string literals.

      • Example
        def rectArea():
        x=int(input(“Enter the width: “))
        y=int(input(“Enter the length: “))
        print(“The area of the rectangle that is {} x {} is {}”.format(x,y,x*y) #Knowt won’t indent it, pretend
        rectArea() #This runs all of the previously defined code into the display

      • Example:
        def rectArea(x,y):  #Defines x and y, called parameters
        print(“The area of rectangle { } x { } is { }”.format(x,y,x*y))

        def main():
        rectArea(10, 5) #This assigns 10 to the variable x and 5 to the variable y
        rectArea(10, 20) #Calls the function again, with new variable values
        w=5
        l=10
        rectArea(w,l) #sends w which stores a value of 5 to x and l which stores a value of 10 to y
        main() #Runs the whole code

    • print()

      • Print code, which can be things like variables, strings, etc.

      • If doing math, it will use PEMDAS

      • Can be used with numbers and strings to repeat strings [print(“5'“*3) displays 555]

      • Concatenating strings means adding them, which this command can do. [print(‘10’+’5’) displays 105].

    • type()

      • Will check a data type that is put into the () and output what kind of data type it is

      • Can be put into a print function

    • input()

      • Stores an input from the display

      • Typically in the form of variable=input()

      • In the display, a used will be prompted to type and then finish when they hit enter the input

      • Any string inside of the input so that input(“text”) will print the string when the input command is run, eliminating the need for the print command.

      • Will store the imputed text as a string

    • int()

      • Turns strings into variables, or casts them

      • Useful for when an input, which is stored as a string, needs to be a variable

      • For an example
        xString=input(‘Enter a number’) #The number input is 5
        x=int(xString)
        print(type(xString)) #The display will show type=int

    • float()

      • Does the same thing as int() but casts into a float

    • str()

      • Converts other data types into a string

    • .format

      • Used to concatenate things that cannot be concatenated, like strings and numbers, without converting them

      • Things listed after {} symbols will be inserted sequentially

      • Example:
        x=2
        y=6
        sentence=”The sum of {} and {} is {}.”.format(x,y,x+y)
        print(sentence) #This will show ‘The sum of 2 and 6 is 8’ in the display as a string

      • When a specific variable is used multiple times in a given statement, it must be indexed rather than put after the command. The index starts at 0.

      • Example:
        print(“The sum of {1} and {0} is {2}. The difference of {0} and {1} is
        {3}'.format(x, y, x+y, x-y))

      • Can also be used as a f-string, like print(f”{name of variable} is a variable and so is {another variable}”).

    • round(x,#)

      • Rounds a given variable, x, to # decimal places

    • sep=” “

      • Will dictate what symbols will be used as a separator for a given command

      • The separator is a space

    • return

      • Sends the function’s result back to the function

      • Basically stores the result in the function like a variable stores values

      • Can store strings, integers, floats, other functions, etc.

      • Example:
        def add(a, b):

        sum = a+b #sum is a local variable

        return sum #return sum to the function call

        def main():

        x = int(input('Enter a number: '))

        y= int(input('Enter another number: '))

        sum = add(x, y)

      • Can return multiple variables

      • Example:

        def rectAP(w, l):
        area = w*l #w and l are local variables
        perimeter = 2*(w+l)
        return area, perimeter #stores area, perimeter in rectAP(w,l)
        def getWH():
        width = int(input('Enter the width: '))
        height = int(input('Enter the length: '))
        return width, height #stores inputted width and height in getWH()
        def main():
        w, h = getWH() #Assigns the values inputed from the display in the getWH() function to w,h which are local variables
        area, per = rectAP(w , h) #the values in w,h are put into the rectAP function
        print('The area of ', w , 'and' , h , 'is' , area, 'and perimeter is ', per)
        main()  # invoke main()

    • len(listName)

      • Used with lists

      • Stores the number of elements within the given list, listName

      • Example:
        numList=[5, 1, 9, 7, 6]
        n=len(numList) # This returns 5, and stores n as 5
        print(numList[n-1]) #This will output the last element, 6, since numList[n-1] is sourcing indexed elements, starting with 0, meaning the last one is indexed as 4 despite there being 5 elements

    • List specific functions:

      • listName.append()

        • Used with lists, to add items to the end. It will add whatever is in () to the end of a given list, all as one item

      • listName.extend()

        • Used like append, but can add multiple items to a list, by them being seperated by a comma

      • listName.clear()

        • Will clear all elements out of a list

      • listName.copy()

        • Copies the values within a list

      • listName.count()

        • Counts how many elements within a list have a given value

        • The value that the list is counting how many there are of is in ()

      • listName.index()

        • Will give the indexed value of something in ()

        • If the given value is used multiple times, it will only output the first instance it has that value

      • listName.insert(x,y)

        • Inserts a given value before a specified indexed value within a list

        • x is the indexed value for the data y to be inserted before

      • listName.pop(x)

        • This will delete a given indexed data from the list

        • The indexed value of the data wanting to be deleted from the list is x within the ()

      • listName.remove(x)

        • Similar to .pop, but instead of removing an indexed value, will remove the data given in () itself

        • x is the given data that is wanting to be removed, the indexed value doesn’t need to be known

      • listName.reverse()

        • This will completely reverse to order of the list

      • listName.sort()

        • Will sort a function, by default does so alphabetically

        • listName.sort(reverse=true) will sort alphabetically but in reverse order, starting with the last item. Essentially it sorts the list and then reverses it all

        • listName.sort(reverse=false,key=givenFunction) will sort a given list according to a function, givenFunction

    • is

      • Used to check if something is true or false, returns a boolean value

    • for, in

      • Used in iterations, or loops

      • Example:
        def sumList(nums):

        total=0 #local variable

        for num in nums:

        total=total+num

        return total

        numList = [5,2,4,7]

        total = sumList(numList)

        print(total) #This will display 18 in the console

    • range(x)

      • Will return a list of numbers from 0 to x-1

      • range(3) will return [0,1,2]

      • Example:
        a=range(3)

        print(a) #This will print range (0,3)

      • Can be used to create loops, example:
        colorList = ['red', 'green', 'blue','black']
        for idx in range(4): #range(4) is [0,1,2,3]
        print(colorList[idx], end=' ') #This uses the index values from the range function to print every element in the list( idk end=’ ‘)

      • It can also make loops with the len() function if the number of items is unknown. Example:
        colorList = ['red', 'green', 'blue', 'black']
        numList = range(len(colorList)) #Instead of range(4) like before
        for indexNum  in numList: #This assigns indexes from the previous line to different elements in a given list, in this case colorList
        print(colorList[indexNum], end=' ')

      • Can also be used to generate lists that count up like range(start, stop, step). For example,
        numList1=range(0,6,2) #This will store [0,2,4], as 0 is the starting number as the first argument in the function, 6 is the last number but it is exclusive so the last number is actually 5 (n-1, 6-1), and it is counting up by the third number, or 2.
        numList1 = range(0,6,2) #this generates a series = [0,2,4]

    • sorted(x)

      • Sorts x, which is typically a list, either alphabetically or numerically

      • To reverse the order, use sorted(x, reverse=true)

  • Operators:

    • + adds two things

    • - subtracts the second from the first

    • * Multiplies two things

    • / divides the first by the second

    • // divides the first by the second but gets rid of remainders (5//3 is 1)

    • % divides the two numbers and gives only the remainder (5%3 is 2)

    • ** is like an exponent (2**5 is 32)

  • Data types:

    • String:

      • Enclosed in either single, double, or triple (3 ‘) quotes

      • Contains text, can be any kind of symbol

      • Can be printed, stored in variables

      • Using multiple quotes is necessary when having quotes in the string itself (‘“Ur mom is a hoe,” I said to the little rat bitch who took my seat.’)

      • Putting numbers inside a string treats them as if they are strings, and no longer numbers.

    • Integer:

      • Numbers

      • Can have math done

    • Float:

      • Can be whole numbers

      • Can have decimals

      • More precise than integers

      • If math is done with a float and an integer, the output will be a float

    • Boolean:

      • Also known as ‘Bool’

      • True/False

    • List/Array:

      • An ordered sequence or arbitrary data objects, with each individual unit being called an element or item

      • Elements are automatically indexed, which allows elements to be used and called based on their index values. Indexing starts at 0

      • Elements can be other data types, like numbers, floats, strings, booleans, variables, or even other lists

      • To create a list, use factorsOfEight=[1,2,4,8]

      • To display the whole list, say factorsOfEight, use print(factorsOfEight) to display [1, 2, 4, 8]

      • Single elements can be changed within the list using their index value, like colorList[3]=’white’ will change the 4th element to the string ‘White’

      • Math can be used with elements in a list. Given that i=1, twoNum=numList[i]+numList[i+1] is the same as
        twoNum=numList[1]+numList[2] (since i stores the value of 1, and 1+1 is two). Say i=3, then twoNum=numList[i]+numList[i+1] is equal to numList[4]

      • A list can be empty, containing nothing, like emptyList=[]

      • Has a few built in functions, like len(listName) and others here https://www.w3schools.com/python/python_lists_methods.asp

  • Variables:

    • Store the value of something inside text

    • If price=2 using the command print(price) will output 2. Using print(type(price)) will output int for integer.

    • Can store strings, floats, integers, and Booleans

    • Can be used to do math, using the values of the variable if they store integers or floats

    • When naming one, they cannot contain any special characters other than _ and $

    • They may contain digits, so long as they are not the starting character

    • Case sensitive, price is not the same as Price

    • Common convention says when naming variables, the first word is lowercase and the first letter of the next words are capitalized i.e. firstName and yourMomIsAHoe. Variable names should also be meaningful, avoid replacing 1/I 0/O, and avoid similar names.

    • A variable can be local/global, with local variables only being defined and used within a function block and global variables being defined on their own and reused. Local variables can only be used within the function it is defined it. To use a global variable inside a function rather than a local variable of the same name, the word ‘global’ must be put before it. Example: global total

    • Static variables are constants, typically global variables. They are given a capital letter. An example is P=3.1416

  • #

    • Allows for the person writing the code to make notes to others who may view the code

    • Has no effect when running the code

    • Notes, basically

    • Affects a single line

    • Use this symbol and then a space then the note

  • Parameters:

    • Can be used with a definition function def functionName(): and ran with functionName() which calls and invokes the function

    • All code after the def functionName(): will be indented and ran whenever the function is used

    • Used to rerun code

    • If a variable is put into the parenthesis of a declaration/definition function, it is known as the formal parameter. Anything put into the parenthesis when running the function is called an argument, and is stored by the parameter. If a string is entered, it is a string literal.
      def greeting(name):
      name=input(“What is your name?”)
      print(f“Good evening {name}! How is your day?”)

      greeting(“Emily”) #In the display, ‘Good evening Emily! How is your day?’ will print

    • One function can have multiple parameters, seperated by a comma in the definition function like

      def rectArea(x,y):

      print(f“The area of a rectangle that is {x} by {y} is {x*y}.”)

      rectArea(2,4) #In the display, this will show ‘The area of a rectangle that is 2 by 4 is 8.’

    • def main(): is used when multiple people are working on one large code with many smaller parts, typically containing multiple other user defined functions

Python!

  • Python is an interpreter, translating code line by line rather than as a whole. It translates the source code into machine code, which then is run through the CPU and output on a display

  • Python IDLE is what we use to run command line interface code. The python editor is just a blank text, where the python shell has text and goes line by code. The command line is shell, but the editor takes all of the code

  • Functions:

    • def__(): and __()

      • Variables can be stored in the (), like name, which may change over the course of a program. Every time the function is run, the variable will source the current data stored in the variable. The variable is called a formal parameter. Multiple variables can be put into the function.

      • If a function has a variable assigned in its definition, different things can be called to be used in it. The variable is the formal parameter, and the substitutions are value or actual parameters that get assigned to the variable automatically. If strings are assigned, they are called string literals.

      • Example
        def rectArea():
        x=int(input(“Enter the width: “))
        y=int(input(“Enter the length: “))
        print(“The area of the rectangle that is {} x {} is {}”.format(x,y,x*y) #Knowt won’t indent it, pretend
        rectArea() #This runs all of the previously defined code into the display

      • Example:
        def rectArea(x,y):  #Defines x and y, called parameters
        print(“The area of rectangle { } x { } is { }”.format(x,y,x*y))

        def main():
        rectArea(10, 5) #This assigns 10 to the variable x and 5 to the variable y
        rectArea(10, 20) #Calls the function again, with new variable values
        w=5
        l=10
        rectArea(w,l) #sends w which stores a value of 5 to x and l which stores a value of 10 to y
        main() #Runs the whole code

    • print()

      • Print code, which can be things like variables, strings, etc.

      • If doing math, it will use PEMDAS

      • Can be used with numbers and strings to repeat strings [print(“5'“*3) displays 555]

      • Concatenating strings means adding them, which this command can do. [print(‘10’+’5’) displays 105].

    • type()

      • Will check a data type that is put into the () and output what kind of data type it is

      • Can be put into a print function

    • input()

      • Stores an input from the display

      • Typically in the form of variable=input()

      • In the display, a used will be prompted to type and then finish when they hit enter the input

      • Any string inside of the input so that input(“text”) will print the string when the input command is run, eliminating the need for the print command.

      • Will store the imputed text as a string

    • int()

      • Turns strings into variables, or casts them

      • Useful for when an input, which is stored as a string, needs to be a variable

      • For an example
        xString=input(‘Enter a number’) #The number input is 5
        x=int(xString)
        print(type(xString)) #The display will show type=int

    • float()

      • Does the same thing as int() but casts into a float

    • str()

      • Converts other data types into a string

    • .format

      • Used to concatenate things that cannot be concatenated, like strings and numbers, without converting them

      • Things listed after {} symbols will be inserted sequentially

      • Example:
        x=2
        y=6
        sentence=”The sum of {} and {} is {}.”.format(x,y,x+y)
        print(sentence) #This will show ‘The sum of 2 and 6 is 8’ in the display as a string

      • When a specific variable is used multiple times in a given statement, it must be indexed rather than put after the command. The index starts at 0.

      • Example:
        print(“The sum of {1} and {0} is {2}. The difference of {0} and {1} is
        {3}'.format(x, y, x+y, x-y))

      • Can also be used as a f-string, like print(f”{name of variable} is a variable and so is {another variable}”).

    • round(x,#)

      • Rounds a given variable, x, to # decimal places

    • sep=” “

      • Will dictate what symbols will be used as a separator for a given command

      • The separator is a space

    • return

      • Sends the function’s result back to the function

      • Basically stores the result in the function like a variable stores values

      • Can store strings, integers, floats, other functions, etc.

      • Example:
        def add(a, b):

        sum = a+b #sum is a local variable

        return sum #return sum to the function call

        def main():

        x = int(input('Enter a number: '))

        y= int(input('Enter another number: '))

        sum = add(x, y)

      • Can return multiple variables

      • Example:

        def rectAP(w, l):
        area = w*l #w and l are local variables
        perimeter = 2*(w+l)
        return area, perimeter #stores area, perimeter in rectAP(w,l)
        def getWH():
        width = int(input('Enter the width: '))
        height = int(input('Enter the length: '))
        return width, height #stores inputted width and height in getWH()
        def main():
        w, h = getWH() #Assigns the values inputed from the display in the getWH() function to w,h which are local variables
        area, per = rectAP(w , h) #the values in w,h are put into the rectAP function
        print('The area of ', w , 'and' , h , 'is' , area, 'and perimeter is ', per)
        main()  # invoke main()

    • len(listName)

      • Used with lists

      • Stores the number of elements within the given list, listName

      • Example:
        numList=[5, 1, 9, 7, 6]
        n=len(numList) # This returns 5, and stores n as 5
        print(numList[n-1]) #This will output the last element, 6, since numList[n-1] is sourcing indexed elements, starting with 0, meaning the last one is indexed as 4 despite there being 5 elements

    • List specific functions:

      • listName.append()

        • Used with lists, to add items to the end. It will add whatever is in () to the end of a given list, all as one item

      • listName.extend()

        • Used like append, but can add multiple items to a list, by them being seperated by a comma

      • listName.clear()

        • Will clear all elements out of a list

      • listName.copy()

        • Copies the values within a list

      • listName.count()

        • Counts how many elements within a list have a given value

        • The value that the list is counting how many there are of is in ()

      • listName.index()

        • Will give the indexed value of something in ()

        • If the given value is used multiple times, it will only output the first instance it has that value

      • listName.insert(x,y)

        • Inserts a given value before a specified indexed value within a list

        • x is the indexed value for the data y to be inserted before

      • listName.pop(x)

        • This will delete a given indexed data from the list

        • The indexed value of the data wanting to be deleted from the list is x within the ()

      • listName.remove(x)

        • Similar to .pop, but instead of removing an indexed value, will remove the data given in () itself

        • x is the given data that is wanting to be removed, the indexed value doesn’t need to be known

      • listName.reverse()

        • This will completely reverse to order of the list

      • listName.sort()

        • Will sort a function, by default does so alphabetically

        • listName.sort(reverse=true) will sort alphabetically but in reverse order, starting with the last item. Essentially it sorts the list and then reverses it all

        • listName.sort(reverse=false,key=givenFunction) will sort a given list according to a function, givenFunction

    • is

      • Used to check if something is true or false, returns a boolean value

    • for, in

      • Used in iterations, or loops

      • Example:
        def sumList(nums):

        total=0 #local variable

        for num in nums:

        total=total+num

        return total

        numList = [5,2,4,7]

        total = sumList(numList)

        print(total) #This will display 18 in the console

    • range(x)

      • Will return a list of numbers from 0 to x-1

      • range(3) will return [0,1,2]

      • Example:
        a=range(3)

        print(a) #This will print range (0,3)

      • Can be used to create loops, example:
        colorList = ['red', 'green', 'blue','black']
        for idx in range(4): #range(4) is [0,1,2,3]
        print(colorList[idx], end=' ') #This uses the index values from the range function to print every element in the list( idk end=’ ‘)

      • It can also make loops with the len() function if the number of items is unknown. Example:
        colorList = ['red', 'green', 'blue', 'black']
        numList = range(len(colorList)) #Instead of range(4) like before
        for indexNum  in numList: #This assigns indexes from the previous line to different elements in a given list, in this case colorList
        print(colorList[indexNum], end=' ')

      • Can also be used to generate lists that count up like range(start, stop, step). For example,
        numList1=range(0,6,2) #This will store [0,2,4], as 0 is the starting number as the first argument in the function, 6 is the last number but it is exclusive so the last number is actually 5 (n-1, 6-1), and it is counting up by the third number, or 2.
        numList1 = range(0,6,2) #this generates a series = [0,2,4]

    • sorted(x)

      • Sorts x, which is typically a list, either alphabetically or numerically

      • To reverse the order, use sorted(x, reverse=true)

  • Operators:

    • + adds two things

    • - subtracts the second from the first

    • * Multiplies two things

    • / divides the first by the second

    • // divides the first by the second but gets rid of remainders (5//3 is 1)

    • % divides the two numbers and gives only the remainder (5%3 is 2)

    • ** is like an exponent (2**5 is 32)

  • Data types:

    • String:

      • Enclosed in either single, double, or triple (3 ‘) quotes

      • Contains text, can be any kind of symbol

      • Can be printed, stored in variables

      • Using multiple quotes is necessary when having quotes in the string itself (‘“Ur mom is a hoe,” I said to the little rat bitch who took my seat.’)

      • Putting numbers inside a string treats them as if they are strings, and no longer numbers.

    • Integer:

      • Numbers

      • Can have math done

    • Float:

      • Can be whole numbers

      • Can have decimals

      • More precise than integers

      • If math is done with a float and an integer, the output will be a float

    • Boolean:

      • Also known as ‘Bool’

      • True/False

    • List/Array:

      • An ordered sequence or arbitrary data objects, with each individual unit being called an element or item

      • Elements are automatically indexed, which allows elements to be used and called based on their index values. Indexing starts at 0

      • Elements can be other data types, like numbers, floats, strings, booleans, variables, or even other lists

      • To create a list, use factorsOfEight=[1,2,4,8]

      • To display the whole list, say factorsOfEight, use print(factorsOfEight) to display [1, 2, 4, 8]

      • Single elements can be changed within the list using their index value, like colorList[3]=’white’ will change the 4th element to the string ‘White’

      • Math can be used with elements in a list. Given that i=1, twoNum=numList[i]+numList[i+1] is the same as
        twoNum=numList[1]+numList[2] (since i stores the value of 1, and 1+1 is two). Say i=3, then twoNum=numList[i]+numList[i+1] is equal to numList[4]

      • A list can be empty, containing nothing, like emptyList=[]

      • Has a few built in functions, like len(listName) and others here https://www.w3schools.com/python/python_lists_methods.asp

  • Variables:

    • Store the value of something inside text

    • If price=2 using the command print(price) will output 2. Using print(type(price)) will output int for integer.

    • Can store strings, floats, integers, and Booleans

    • Can be used to do math, using the values of the variable if they store integers or floats

    • When naming one, they cannot contain any special characters other than _ and $

    • They may contain digits, so long as they are not the starting character

    • Case sensitive, price is not the same as Price

    • Common convention says when naming variables, the first word is lowercase and the first letter of the next words are capitalized i.e. firstName and yourMomIsAHoe. Variable names should also be meaningful, avoid replacing 1/I 0/O, and avoid similar names.

    • A variable can be local/global, with local variables only being defined and used within a function block and global variables being defined on their own and reused. Local variables can only be used within the function it is defined it. To use a global variable inside a function rather than a local variable of the same name, the word ‘global’ must be put before it. Example: global total

    • Static variables are constants, typically global variables. They are given a capital letter. An example is P=3.1416

  • #

    • Allows for the person writing the code to make notes to others who may view the code

    • Has no effect when running the code

    • Notes, basically

    • Affects a single line

    • Use this symbol and then a space then the note

  • Parameters:

    • Can be used with a definition function def functionName(): and ran with functionName() which calls and invokes the function

    • All code after the def functionName(): will be indented and ran whenever the function is used

    • Used to rerun code

    • If a variable is put into the parenthesis of a declaration/definition function, it is known as the formal parameter. Anything put into the parenthesis when running the function is called an argument, and is stored by the parameter. If a string is entered, it is a string literal.
      def greeting(name):
      name=input(“What is your name?”)
      print(f“Good evening {name}! How is your day?”)

      greeting(“Emily”) #In the display, ‘Good evening Emily! How is your day?’ will print

    • One function can have multiple parameters, seperated by a comma in the definition function like

      def rectArea(x,y):

      print(f“The area of a rectangle that is {x} by {y} is {x*y}.”)

      rectArea(2,4) #In the display, this will show ‘The area of a rectangle that is 2 by 4 is 8.’

    • def main(): is used when multiple people are working on one large code with many smaller parts, typically containing multiple other user defined functions