Tag: AI

  • Protected: Python Loop Examples

    This content is password protected. To view it please enter your password below:

  • Python Loops

    Let’s give a few looks, to see the pythoness of it all. Otherwise, the loops in python are pretty much the same at a core level as any number of other programming languages. I will assume you recognize their purpose and show them for syntax only.

    #set start value 
    i = 3
    Determine end of loop value,  
    notice : and indentation like the "if" and "case" statements learned before
    while i <= 0:
         la la la
         i = i - 1
         i =+ 1   is another option to add 1 to i if that was your want
    
    Notice the [ ] hard brackets for lists
    for i in [1,2,3]:
        la la la
    of course you might want to use a list more for not numerics
    for fruit in [apple,ban,pear]
        la la x = i la la
    of course, if you want numerics or a count
    for _ in range(3)
        la la la la
    does 0,1,2 but the _ is a not visible variable, meaning you  can not use it like i
    but the for logic is using it to help it loop 3 times with a 0 1 2.
    
    break from infinite loop, force an infinite loop until get what you want.
    continue mean continue to loop,  I know in English it can be used in a sentence to continue onwards but it means here go to start of loop again;   break here is break out of loop,  break out of jail,  not take a break or go to sleep or like the more complex break point to pause long programs.
    
    while True:
         n = int(input(please give me positive))
         if not_a_number():                   not a real function, to demonstrate continue
              continue
         if n > 0:
          break
    using len for length of list, or number of objects in a_list.
    for i in range(len(a_list))
          la la   x = i la la
  • Protected: Python Conditional Examples

    This content is password protected. To view it please enter your password below:

  • Python Conditionals

    One has your typical if statement; your pythoness is : and indent

    if x == "letter":
    1234y=written
    
    That is the Boolean, followed by a semicolon : and a <newline>
    indent 4 spaces,  if Boolean is true then assign written to variable y
    
    if x == "letter":
         y = written
    
    If boolean:
        # doing a thing
    elseif 2boolean:
        # doing a thing2;
    else:
        # mop up

    Typical Booleans that work in strings and numbers
    == !=
    And more Booleans for numeric or integers and floats are
    > < >= <=

    Typical operands that work on strings and numbers
    + *
    5 + 5 will be 55 if done on a string, dak * 3 will be dakdakdak.
    And more numeric operands
    – /

    You can google or search the Python Documentation for the word “operands” for actions to variables that match arithmetic

    x ** 2    for power of 2     or exponential.
    I am sure there is probably a logarithmic function for going the other way.
    
    x % 3     for remainder or modulus
    is 0 when x is 9 since it evenly divides with no remainder or is 2 when x is 11.

    You can google or search for the word “Boolean Conditional” or each word separately where you can get some additional choices to if statements like the case statement.

    and for the word “Operators”, we sort of looked only at single variables compared to values, there are also things like Logical Operators and, or, not.

    The world of lists, does a value appear in a list.

    "banana" in x if x was a string listing of fruit or "baker" in "bakermayfield" is True for a str. 
    
    A very common conditional functional "does file exist"; common if you like to write pre-checks in your script or like to write your own help or usage messages, if a file is required to for script to work. 

    There is whole bunch more, but this is a good start, very similar to ruby and bash, so python has anything you are used to using, just has its own unique syntax which I tried to touch on here to get moving in right direction.

    Below is great use of lists, it is always important to know how to split a list. And before we learn expression[2] is expression was dog would be g, which is location in a string.

    expression = input("Expression: ")
    x,y,z = expression.split(" ")

    Strings can be deciphered or taken apart with “in” or location in string express[3].

    Lists can be taken apart with split, default delimiter is space, could be a comma too.

    Numerics tend to be isolated variables, which I mean float(“x”, “y”) is sloppy, maybe y is a letter. Better to keep it nx = float(x), manipulate numbers similar to simple arithmetic IRL.

    Or always important to be able to pull things apart. In the future we will get to hashes and arrays where location is more important.

  • Protected: Python Functions Examples

    This content is password protected. To view it please enter your password below:

  • Python Functions

    Simple Examples

    Covert to lowercase
    ip = input()
    ip = ip.lower()
    print(ip)
    
    Replace spaces with three dots
    ip = input()
    print(ip.replace(' ','...'))
    
    Replace a text emoji with a picture emoji
    def main():
        msg = input()
        print(convert(msg))
    
    def convert(msg):
        msg1=msg.replace(":)","🙂")
        msg2=msg1.replace(":(","🙁")
    # does both,  if a single line contain happy and sad text emoji
    # replace does not return null if it finds nothing to replace, it does =
        return msg2
    main()

    How do I run or execute python ?

    You would have installed python before today on your PC or container or virtual machine.

    python newline

    >>>> interactive shell to run python functions, Python interpreter

    Say I want to save something more permanent, vi/VS code/atom, use an editor or IDE to create a file whatiwant.py, my python program.

    python whatiwant.py newline on command line, python to be run

    or add this as a top line of the file whatiwant.py, my python program.

    cat whatiwant.py | head -n 1 on command line to see first line

    #!/usr/bin/env python3

    whatiwant.py newline

    on command line, no need to tell it to use python on the command line.

    And so on, basic linux command line to tell it what to run, if it was a bash script use #! /bin/bash on a bash script whatiwant.sh, or ruby whatiwant.rb for a ruby program.

    What is a function ?

    It’s a task you want to do many times, say like print to screen, hence you have a function called print. Typically, functions are easy to use, alleviate writing that snippet of lower level code over and over again. You have your built-ins, came with the python distribution and therefore sit before your use of them. I only mean when you define your own functions, you need to define them prior to your use of them, you need to put some thought into where they sit. The built-ins already sit upstream always.

    A little precision on language, when you define the function, sep is the 2’nd parameter. Jerry is the 3’rd argument. An argument is the value assigned to the parameter during actual usage of the function. And to complete word use x = print(“Is that not perfect!”,”again”,sep=’ Jerry ‘), the x would be a variable in your main program.

    print(*objectssep=’ ‘end=’\n’file=Noneflush=False)

    print(“Is that not perfect!”,”again”,sep=’ Jerry ‘)

    Is that not perfect! Jerry again

    cat whatiwant.py print and input are built-in functions

    #! /usr/bin/env python3
    duck = input{"Give me some input? ")    enter space space sure gi
    print("Is this your input,", duck)   will return Is this your input,   sure gi
    duck = duck.strip().capitalize()  a print will return Sure gi remove spaces
    duck = duck.title()   a print will caps all words,    Sure Gi
    duck = input("Give me some input?").strip().title()     do it earlier
    print(duck)

    And you can learn functions in the doc, note strip only does trailing and preceding spaces on what you entered when prompted by input. To get rid of inside spaces between inputted words is another exercise.

    x = 1, y = 2, z = x + y; print(z) will return 12 or the default is string and concatenate. int.x = 1 or x = int(input(“enter number:”,)) will treat x as an integer. Remember whole number 0,1,2,3 for counting objects back in our barter system on farms, -3,-2,-1,0,1,2,3 are integers or no fractions for many uses and then floating where one usually chooses to what decimal place for precision in engineering.

    print(z) is normal

    print(f”{z}”) allows f or formatting and requires z in curly brackets

    print(f”{z:,}”) assume you defined z as a int prior, will put in the 1,000 instead of 1000. print(f”{z:.2f}”) will round say 3.4179 to 3.42 two decimals. Print with format has a lot of power, throwing it out there. Or you can deal with it earlier during variables, z = round(z, 2) will produce 3.42 to pass simply to print(z).

    Anyways, remember each built-in function may have more interesting aspect worth looking into, your default type is string for variables.

    Should the built-ins not be enough, create your own.

    Pretty simple, def is the keyword or the define function (a function to define other functions), you pass values in through parameters between the () on the line starting with def. You use return within the function to get values back up into main. So the function knows nothing of lego or variables in main, and main knows nothing of y inside the function. There is a word for it, Scope, meaning a variable only has use inside its scope.

    lego = "ripe apples"
    
    myfunction(nuts) bad line will not work, as it sits above its define
    
    def myfunction(lz="defaultvalue"):
           print("Is this correct,", lz)
           print(lego)       this line is a bad line
    
    nuts="Jerry"
    myfunction(nuts) will work as myfunction sits below its define

    Is this correct, Jerry.

    I gave a simple example showing passing a value INTO a function. Let’s do a slightly different example to show Scope and returned values OUT of a function.

    def myfunction():
        fil = "Jerry"
        x = 50
        y = 60
        return [fil, x]
    myfunction()
    verify = myfunction()
    print(verify)
    [ 'Jerry', 50]
    
    Let's add another line
    
    print(y)
    
    NameError: y y only exists locally inside myfunction(), not up in main.

    Ease in ordering

    When we open of whatiwant.py do I really want to scroll 200 lines past all my user defined functions, to presumable get back to editing and improving main. The answer is no. Since python interpreter goes line by line, I can not use something before defining it. And someday, possibly my function will reach superstar status and be worthy of being stored outside whatiwant.py, just not today. Here is a way to keep main at the top of whatiwant.py. Huge tangent, python is a byte interpreted language, meaning it is compiled then interpreted. The practical nature is a compiled language is completely translated into instruction machine code, therefore all is defined flatly. Most languages are interpreted, which means read line by line for our purposes here.

    globalvariable1="dan"
    def main()
    
          Do your code
           globalvariable1 is read,  can not alter or write
           global globalvariable1  will redefine it as modify not just read.
           act on globalvariable1="daniel"
           afunctionusedinmain()  
    
           Technically here we are def of main, using afunctionusedinmain() is still
            below afunctionusedinmain() define.
    
    def  afunctionusedinmain()
    
          define my function with code
          globalvariable1 can read also, same as main, any function
    
    main()

    Do not forget to use main after defining it. The last line is important, otherwise whatiwant.py is talking to itself and does nothing.