Tag: break

  • Python Reserved words

    Python Reserved words

    Reserved words in a language are words that have very special meaning to the language. If python sees any of it’s preserved words, it have only one and only one meaning to it.

    The words you will make by yourself as a programmer will be called variables. The words you create by yourself should never consists of any of the reserved words.

    Reserved words in python includes

    and

    and is a logical operator that matches the boolean logic AND that returns true if and only if two operands are true and false otherwise.

    as

    It is used to define a certain word with a different name which is usually referred as alias. It allow user to define a friendly name in programing activities. For example, consider an programmer that want to import a file called matplotlibray which will be used most of the time in a program.

    We can us the as to rename the file mat as as in:

    import matplotlibray as mat

    now we can be use mat instead of the word matplotlibray

    assert

    used in debugging where it allows one to test the correctness of a code by checking if some specific conditions remains true.

    Until there is a bug in the program, the assertion remains true. for example the statement assert number > 0 tests a condition where a number must be greater than 0 and if not, a debugger throws an AssertionError.

    break

    It allows you to exit a loop when an external condition is met and allows the program to resume the next statement after the loop.

    it terminates the loop that contains it and directs the program to flow to the statement that follows the block.

    It is used in for loops and while loops.

    For example:

    for x in numbers:
        if x =5:
           break

    continue

    It makes the code skip the current iteration and proceed to the next one

    It is useful where we need to skip part of the loop but remain in the same loop block.

    Continue skip the statements in the current iteration of the loop and moves the control back to the top of the loop.

    For example:

    In the above code, the if statement checks if the number is divisible by 2 and if it evaluates true, it skips to the next number which is odd. Hence the program print odd numbers between 30 and 50 as shown.

    class

    used to create a python class. class is a template for objects. Creating a new class creates a new type of object, allowing new instances of that type to be made.

    An object is a collection of variables and methods which acts as a blue print for that object.

    we use class to create a class in Python. for example

    The code snippet above shows a student class being created.

    An object of class student can be created from class as shown:

    def

    it is used to define a function in python. Every code you put between the def function name and it’s end with be considered as a single logical piece of code with statements that can be executed at once by invoking the name of the function.

    The following code defines a function called grade that calculates student grade based on marks passed to it:

    We can call the function and provide pass some marks to it as an argument as shown below:

    del

    used to delete object in python. It’s primary goal is to destroy objects in python code. When del is used against an object , the object is removed from the scope of the object.

    consider the student class we created earlier..

    When run, the program gives the following output:

    supposed now we delete the object student as in code below:

    running the code will cause an exception error that shows missing of an object student as shown

    The del keyword can also be used to delete objects like dictionaries, items in a list, tuples and even user-defined objects.

    elif

    Used to include multiple conditional expressions after the if condition or between the if and else conditions.

    else

    It is used in conditional statements like if statements and is used to decide what to do if a condition is false.

    try

    It is used in try-except block and it defines a block of code that is tested for errors, if nor errors is detected, the code in try block is executed, otherwise it is passed to the except block. Different error types can be defined in the except block.

    except

    used in try-except block and defines a block of code that should run if the try block raises an error. Except pairs with try where try block is executed where there is no exception error but when there is an error that prevents that block to execute, the control is transferred to except block.

    finally

    it defines a block which will always be executed after leaving a try-except statement if some exception was not handled by the except block. It helps in deallocating the system resources.

    for

    It is used to create a loop helping a program to iterate through sequence of items like a list, tuple and dictionary etc.

    from

    used to import a specified section of a python module. generally used with import, from is used to import particular functionality from the module imported. For instance the code code below will import sqrt method from the math module

    import math
    
    from math import sqrt
    myNumber = math.sqrt(80)
    print(myNumber)
    #120

    global

    It is used to allow programmer modify a variable outside of the current scope. consider the code below.

    x = 2000
    
    def reduce():
    while x<=0:
    x -=2
    print(x)
    reduce()

    When run, the code produces the error shown

    The error is because the x referenced in the while block is not defined as far as the python interpreter is concerned. The x defined outside the while block is out of reach of the while block, hence it is considered non-existence.

    we can rewrite x inside the loop with the word global to tell the block that it should use the x that was defined outside it. The modified code will now run

    if

    it is used to test a condition and if condition evaluates to true, the code in the if block is executed.

    If is usually referred to as a conditional statement because it is used to execute a block of code only when a specific condition is fulfilled. consider the code below:

    when the code above is run, nothing will happen and no output will be on the screen. This is because the condition that the number be fully divisible by two is not me.

    import

    used to refer a code from another module. For example we be referring a pow function which is in math module. To use the pow function which is defined somewhere else, we must import the module that has defined it. I have used the pow function to define a function that accept a single parameter and square it.

    in

    It is a word used in checking existence of a value in list, range or a string. It returns true if a certain element is present in a python object and false otherwise.

    is

    Used to test if two variables belong to the same object. It returns true if two objects are the same.

    output: True

    output: False

    lambda

    Used to create small anonymous functions that can take any number of arguments but can only have one expression. Anonymous functions means a function without a name.

    import math
    

    number = int(input("Enter a number: "))
    root = lambda number: math.sqrt(number)
    print(root(number))

    In the above code, we define a function which is assigned a variable name root. the lambda function calls the squareroot function of math class

    nonlocal

    In python, variables can be declared in three different scopes:

    • Local scope
    • global scope
    • nonlocal scope

    A function defined within a function and can only accessed within it is called a local variable.

    A variable declared outside of a function such that it can be accessed inside or outside of the function is referred to as a global variable.

    nonlocal keyword is used to work with variables inside nested functions where the variables should not belong to the inner function.

    Example code:

    def outsum():
    x=-2
    sum = 0
    while x <5:
    print(x)
    sum +=x
    x +=1
    print("sum is: ",sum)
    print("*********************")

    def innersum():
    x=0
    print("We are doing the inner thing now")
    nonlocal sum
    while x <=5:
    sum +=x *2
    x+=1
    print("The inner arithmetic is:",sum)
    innersum()

    not

    used in conditional statements or other Boolean expressions to invert the Boolean value or expression. not will convert the True evaluation to False and vise versa

    x=0
    print(x)
    print(not x)

    #0
    #True

    or

    It is a logical operator used to combine conditional statements returning true if one of the statements evaluates to True.

    Example:

    y = (2>-2 or -3 > 3)
    T = (-4 > 4 or -5 > -5)
    print(y)
    print(T)

    #True
    #False

    pass

    used as a placeholder for future code.

    def summation():
    pass

    raise

    It is used to raise an exceptions or errors where it stops the flow of the program.

    a=int(input("Enter numerator: "))
    b=int(input("Enter denominator: "))
    if (b==0):
    raise Exception("Division by zero is not accepted")

    return

    It used to end the function call and return the result to the caller. The function terminates on seeing the word return giving back whatever is after the return keyword.

    Example:

    def summation(x,y):
    sum=0
    for i in range(x,y):
    sum +=i
    print(sum)
    summation(20,55)
    #1295

    while

    It is used to create a while loop which defines a loop that executes a piece of code until a certain condition becomes false: Like in the code below, the code keep printing “Am staying here!” until when x is added up to 6

    x=1
    while x < 7:
    print("Am staying here!")
    x =x+1
    #Am staying here!
    #Am staying here!
    #Am staying here!
    #Am staying here!
    #Am staying here!
    #Am staying here!

    with

    It replaces a try-catch block with a concise shorthand. It is a replacement for the commonly used try/finally error handling statement.

    A common example of using with keyword is when reading or writing to a file

    with open("governmentStudents.txt","w") as file:
    file. Write(Name, DOB, AGE)

    yield

    controls the flow of a generator function. It is similar to a return statement used for returning values in python.

    when you call a function that has a yield statement, as soon as yield is encountered, the execution of the function halts and returns a generator iterator object instead of simply returning a value

    generators allows you handle large datasets with minimal consumption of memory and processing cycles.

    def buildList():
    EvenList = [2,4,6,8]
    for i in EvenList:
    yield i*2

    Related Topics


  • Need for a break

    Need for a break

    Do you need a break? From what?

    Along our lives, we collect things in our soul and spirit that acts like a baggage that can really weigh us down. This things we collect when we interact with others. When they hurt us we may develop bitterness, anger and resentments.

    Emotional burdens

    Because of difficulties we face in our growing up, we develop negative emotions that affects how we see the world. We stop seeing life as gift from God and we forget about what God says about us but instead develop the habits of murmuring, jealous and self doubt. People become jealous when they see others possessing what they have always wanted to have but failed. This stirs the feeling of inadequacy within self and creates anger and bitterness for oneself that is presented in one’s soul as jealous.

    people that has grown in poverty could have a distorted view about relationships. They are likely to see relationships and friendships in terms of material benefits and value people based on what they gain by relating to them. Such people can face danger of being corrupt, being dishonest and involve themselves in fraud, betray their friends to gain material possessions and any other evil to help them have control of wealth and material things. Such people can be mean and stingy because their bad experience with poverty causes them have a great fear for lack. Therefore they fear releasing anything they have possession of, they rarely give generously to others and will cheat if it can help them get money. They therefore, destroys relationships and connections that could have helped them attain great purpose in life because of greed which is often fueled by scarcity mindset that which directs people to amass for themselves as much resources as possible whenever such opportunities presents themselves. So if i have to break from something, it is fear that i will not have enough in future.

    All this things are learnt as we grow up and as we interact with our social environment and learn from it. Our environment can teach us negative things that we don’t need, it can destroy the faith we have in ourselves, nurturing self doubt and pessimism. A child who is always criticized by adults will eventually grow in self doubt and may let opportunities that comes their way pass by because they are afraid of stepping into the world and take them. As a parent , you should be very careful about how you communicate with your children as it can determine who they become in the word. People that are criticized by their parents find it difficult to lead because they have low self esteem and lacks confidence.

    Bad habits learned

    Sometimes our social environment has taught us bad habits that limits what we could have become. For instance because of poor policies, dictatorship and retrogressive cultures in some parts of the world, people in this communities learns helplessness.This people will always expect somebody else to solve their problem and when they are not helped, all they do is complain and curse.

    We have people that complains to government over issues they could find solutions because their socialization directed them to expect some other people from some other places to solve all their problems. Such societies are characterized by poor innovations, low quality of life, political manipulation, corruption and bribes, high late of employment, backwardness and alot of crime. When such people cannot find someone who can solve their problems, emotionally or economically, they vet their frustrations to other members of community by causing crime and terror.

    Complains about government

    In my community, the most common baggage people carry is complains and murmuring against the government. I have observed people complain about everything and they always have something negative thing to say against their government. But when you look at it carefully, you realize that they have a lot of capacity to solve the issues they are expecting the government to solve. For instance men fails to mentor their boys but complain about poor education. They complains about economy but they spend money on luxurious when they get money. They pay for expensive services far away from their residence which they could obtain cheaply in their locality

    Am breaking out

    If I have to break from something this week, am gonna break from complaining what life has not given me. I gonna break from doubting myself. I will break from self pity and worries. Everything negative my society has taught me, am leaving behind, to go for the life I have always wanted.

    I will break from thinking negatives and start seeing only positives.

    A lot of criticism in childhood causes fear of failure.

    Am breaking from fear of failing. Am gonna take risks and invest big. Am gonna quit jobs that does not cause growth if I must.

    Am gonna try something new and enter new relationships with abandon. I gonna stop hiding myself because of who is criticizing me. I will not hide my fear of relationship in saying I hate women because of that one selfish woman that hurt me neither will i say all men are dogs beacuse of one male in the universe that broke my heart.

    I gonna break from chains of rejection and meet new wonderful people in the world. I won’t mind those that rejected or disliked me.

    I will loose myself from chains of self pity, being reserved and extra cautious because of pains I have faced. Am becoming bold and daring and break those small chains of life that holds me down. After all, history is gone. What happened happened and will not allow it affect what should happen next.

    Stop wasting time

    It is pointless when one sinks into abyss of self pity and depression because of loosing a job yet some people discovered very successful businesses and great innovations only after abandoning jobs that were limiting them. People finds wonderful people after divorce or after rejection(though i don’t believe divorce is a good thing or even necessary in most of times).

    The world does not revolve around your ex or your job, neither does it revolve around family members that hated and mistreated you. You cannot always feel small because of child abuses that happened 40 years ago. You can do better than that. The world you are living in is much great. Move out of your prisons and go into the world, It is wide and extensive. A person called job in the holy scriptures said that God extends the earth from the north. A psalmist said that the earth is LORD’S and the fullness there in. It does not belong to your former company or anyone who rejected you. It does not even belong to your creditors. Please break from your prisons. Personally none of issues that happened in my life will affect me in anything and prevent me from progressing to where am supposed to be. Not even the fear of unknown. It is written that God did not give us the spirit of bondage as to fear. His breath resides in us, He is limitless, so we better start believing that we are not limited by circumstances around our lives. so we better break our chains.

    Yeah, am breaking from something .

    Related pages