#7 Conditional Statement in Python

Why Auto driver that python makes can make an adjustment to an unpredictable situation. For example, if a car faces another stopped car in front of it, the auto driver can also stop accordingly. That is amazing.

Python can do that, because python have conditional statement or If statement.

The conditional statement is useful for creating a decision structure. Decision depends on condition. This allows a program to create more than one scenario. The if statement has an instruction for one ,, and another different instruction for another condition.

If statement have component, boolean and relational expression to check condition. Beside that, this if statement also have instruction to execute if condition as request.

Boolean and Relational Expression

A Boolean value has two value, True or False. Statement that use this value is Check Statement. Check Statement is statement that evaluate whether the statement true or false. In English language, is A is same with B? in Python language, A==B. faces statement tests an expression to determine whether it is true or false.
Boolean value is named after George Boole formulate some rules for reasoning about and combining this binary value (True and False). It is suit for computer that have binary value, 0 and 1.

We can get list of boolean value in Python by type : dir(True).

>>> dir(True)
       ['abs', 'add', 'and', 'class', 'cmp', 'coerce', 'delattr', 'div', 'divmod', 'doc', 'float', 'floordiv', 'format', 'getattribute', 'getnewargs', 'hash', 'hex', 'index',
       'init', 'int', 'invert', 'long', 'lshift', 'mod', 'mul', 'neg', 'new', 'nonzero', 'oct', 'or', 'pos', 'pow', 'radd', 'rand', 'rdiv', 'rdivmod', 'reduce', 'reduce_ ex', 'repr', 'rfloordiv', 'rlshift', 'rmod', 'rmul', 'ror', 'rpow', 'rrshift', 'rshift', 'rsub', 'rtruediv', 'rxor', 'setattr', 'sizeof', 'str', 'sub', 'subclasshook', '_
       truediv_', 'trunc', 'xor', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real'] "

That is a list of several function related to boolean type data.

Another alternative, we can read the documentation by type “help(True) ” or “help(False) in python command line.

>>> help(True)
       Help on bool object:class bool(int)
  |  bool(x) -> bool
  |  Returns True when the argument x is true, False otherwise.
  |  The builtins True and False are the only two instances of the class bool.
  |  The class bool is a subclass of the class int, and cannot be subclassed.
  |  Method resolution order:
  |      bool
  |      int
  |      object"

Usually, Boolean operator use equal (==), greater(>) and less to determine whether a specific relationship True or False.

> Greater than
>= Greater than or equal to
< Less than
<=Less than or equal to
== Equal to
!=Not equal to

Boolean Value in Conditional Expression

How boolean value in conditional expression. In Python language, the syntax of Conditional is like this

>>> If condition :

Condition in the syntax is boolean statement. That is something that computer can evaluate whether that is True or False. True or False in the term of meet condition. That is not about morality or epistemology.

In flowchart, Conditional Statement use symbol like this.

Logical Operator

Python also accommodate more complicated expression in boolean mode. There are logical operator to combine simpler boolean operator. The logical operator is” and”, “or” and “not”.

“and” Operator

The and and or combine two boolean expression. “And” operator evaluate expression as true only if the both expression is true. The truth table is like this.

XYX and Y

“or” Operator

or operator evaluate two statement. Then if one or more statement is true, the or operator return to True.

XYX or Y

“not” Operator

not operator can apply to one statement or more.
if the not operator apply to True value, it flowcharts to False.

Xnot X

Conditional Execution

A conditional statement has a ability to check condition and execute instruction or statement based on condition.
The syntax is like below.

>>> if True: # This is always True,
        pass # so this is always executed, but it does nothing
>>>  else:

Chained conditionals/ nested decision

if we need more than two condition and more than two instruction, python also accommodate. Chained or nested decision structure check more than one condition.

Notation of chained conditional statement is like this.

That is the conditional statement inside another conditional statement.

# 6 Function in Python

Function is also the most used element in Python programming language. It is a sequence of statements. So, Function combine variable, data, and operator. The function is one of the most used element because it will reduce working time by reduce repeated statement and formula.

If we familiar about function in math and spreadsheet, you can understand easily.

The spreadsheet gives us a ready use function. For example average(A1:A10). This function will sum all numbers within A1:A10 cell, then divide it by count of numbers. Spreadsheet hide detail process of the average function. Only show name and its parameters. This will reduce complexity, and

In mathematics, a function show of how a varying quantity of variable depends on another quantity. … If the f is a name of function , the notation is y = f (x) (read f of x). Function will manipulate x based a formula.

Python has many functions. There are a built-in function in python, functions in modules, and we can make new Built-in.

Built-in Function

A built-in function is a function that Python already provides if we install it. We can see the built-in function here.

Then, to call built-in function is simple. Syntax of built-in function is functionname(parameter). Example, we use the sum function below.

>>> x =[2,4,5,6]
>>> sum(x)
>>> len(x)

len(parameter)” is also built-in function in python. It mean quantity of data series.

Function in Standard Library

Python also has a hidden function at modules in the standard library folder. We have to call its modules to use it. This is example to use random modules

>>> import random
>>> random.randint(0, 20)
>>> random.randint(500, 50000)

We can read the notation is randit function of (0,20) in the ‘random’ modules. Random module have randint function, or random integer.

This is list of modules standard libray.

  • os
  • shutil
  • glob
  • sys
  • re
  • math
  • urllib2
  • smtplib
  • date
  • zlib
  • Timer
  • unittest

Third Party Library

As I talk in the introduction, Python have big community. They create tons of library and always growing. We can use their modules by install them previously. It is website that store library by community: https://pypi.org. To install them, we can go to command prompt or terminal.

pip install modulename

After install third party modules successfully, we can import to use it.

import modulename

modulename is name of modules that you want to install. Dont type module name. If you install BeautifulSoup modules, you can type pip install BeautifulSoup

pip install BeautifulSoup

User Defined Function

If we want to make our own function, we can make it in python.

Syntax to create our create from scratch function is:


For example, if we want to create average function. We can make function like in code below.

>>>def average(xx):
       av = sum(xx)/len(xx)
       return av
y = [1,2,3,4,5]
print average(y)

That is example of user-defined function.

# 5 Data Type in Python Language

Python programmers often have problem with their script. Their script cannot run well, often because of the incorrect data type. Some of the different data types can not work in one operation and python give error result.

In this article, we will show 5 data type in python. Python has five standard Data Types.

The Python data types are: numbers, strings, list, tuple, and dictionary.

  1. Numbers
    1. Integer
      1. Float Point Number
        1. Complex Number
        2. Strings
          1. List
            1. Tuple
              1. Dictionary

                This is something that every programmer need to know. It help us to prevent error and make dream program into reality.
                After reading this article, you can prevent error that stop program. You can also imagine more about what program can do. There
                First, let’s talk about numbers


                “The most used number data type is integer and floating. But that is not the only number data type in python. Python has another number data type. There is complex, decimals and fractions.


                Integer is the whole number without fractional number. It includes positive, negative and zero number. But it does not include 1.5, because that is a fractional number. 50% is not an integer because it is a fractional number. Example of integer is -60, 31, 0, 50 38. and so on.
                If we assign integer number to a variable, python automatically defines its number and variable as an integer.
                In Python programming language, declaration data as number is simple. Write a variable and assign a number without punctuation.
                This is an example. Var1 = 23. This is make var1 as number integer data type. Yo can check the type of variable by writing “type(var)” in python.

                >>> var = 34
                >>> type(var)
                <type 'int'>

                Float Point Number

                Float point number is fractional number or decimal number. The fractional part or decimal part of a non‚Äźnegative real number is the excess beyond that number’s integer part. For example 0.1, 5.1.
                In python, to define that some variable as float type, we just assign float point number to a variable. For example, we have variable C and data float point, 1.3.

                >>> c= 1.3 # dot in this number is sign of decimal number after dot.
                >>> type(c)
                <type 'float'>

                It is possible in python to make mathematic operatation between float and integer. For example

                >>> c= 1.3
                >>> type(c)
                <type 'float'>
                >>> d = 29
                >>> type(d)
                <type 'int'>
                >>> w = c+d
                >>> w
                >>> type(w)
                <type 'float'>       

                Python support operand type(s) for float and integer.

                Complex Number

                Complex number is a combination of real number and imaginative number. The syntax of complex number is , + j. We has to add “j” to imaginary part. Example

                >>> 3+6j


                strings are sequences of alphabet, text, or number data. It is character data. Number as character data different than gives integer. If we assign number as character data, we can not make mathematic operation correctly.

                To make python understand, that some data is strings is by add quote or double quote befor and after data. The data is include

                This is example number as character data.

                >>> x = '9'  #
                >>> type(x)
                <type 'str'>
                >>> x *5

                The example show that ‘9’ * 5 (‘9’ multiply 5) is not 45, but ‘99999’. Because, the ‘9’ is not integer, but string.

                If the between string and integer is allowed, python cannot do the addition for them. It is example. Python give error message.

                >>> x = '8'
                >>> x*4
                >>> x +5
                Traceback (most recent call last):
                  File "<stdin>", line 1, in <module>
                TypeError: cannot concatenate 'str' and 'int' objects


                A variable can have more than one data or lists. Python have 3 distinct lists. There are: list, tuple, and dictionary. In this section we talk about list.

                List is a collection of values. It is series of values. Data type of values can be number or strings. List variables are declared by using brackets  “[” and “]” following the variable name. See distinct of {}, (), and [] carefully.

                Tuple is also collection of values. Unique feature of list compare to tuple is mutable. We change the member of list easily.

                your_list = [2,3,4,5,6]
                my_list = ["we', "are", "champion"]
                empty_list = []

                Python give index of every member of list. The index is start with 0. There are 0,1,2,3 and so on. So we can also retrieve the list by its index number. For example.

                >>> ere = ["yes", 90, "wow"]
                >>> ere[0]
                >>> ere[2]

                List can be member of another list.

                >>> ere = ["yes", 90, "wow"]
                >>> newlist = [ere, [3,5,"5"]]
                >>> newlist
                [['yes', 90, 'wow'], [3, 5, '5']]

                We can retrieve list in the list by two bracket square.

                >>> newlist
                [['yes', 90, 'wow'], [3, 5, '5']]
                >>> newlist[0][1]


                Tuple is also collection of value. Different than list data type, tuple data type immutable. We can not change its member easily.

                It is simple to create a tuple. We can type colletion of value within parenthesis ().

                >>> mytuple=(1,2,"three")
                >>> type(mytuple)
                <type 'tuple'>


                Dictionary is also a collection of value. But different than list and tuple, dictionary, the values of dictionary are pair of key and value. Imagine about an english german dictionary. The list have pair of english word and its meaning in germany language.

                 eng2g = {"one": "eins", "two": "zwei", "three": "drei"}

                To declare a variable as dictionary is simple. If list have bracket square [], tuple have parenthesis (), dictionary have {}. The pair of value have :

                >>> gg ={}
                >>> type(gg)
                <type 'dict'>

                #4 Python Glossary: Operator

                Operators in python is symbol that can perform value or variable. Operator can execute math, logic, assignment, comparison et cetera operation and give result. Without operator, variable only, python is only store value. But, python have operators so it can make calculate and imitate human mind.

                There are various operators in python.

                • Arithmetic operator
                • comparison/ relational operator
                • assignment operator
                • logical operator
                • membership operator
                • Identity operator
                • presedence operator

                Arithmetic Operator

                Arithmetic operator takes two value or variable then performs a calculation on them. The math operation is for example : addition (+), subtraction (-), multiplication (*) , division (/), %modulus , exponentiation(**). There are basic mathematical operations.

                >>> #this is addition or plus
                >>> 3+5
                >>> #this is substraction or minus
                >>> 10 - 3
                >>> #this is multiply two operand (value or variable)  either side of the operator
                >>> 4 * 5
                >>> #division divide first operand by second operand
                >>> 10 / 2
                >>> # modulus divides and returns the value of the remainder.
                >>> 10%3

                Comparison/ Relational Operator

                Comparison/ relational operators compare the values on two sides of the value or variable. For example, 4 < 2 (output = False). After we write a comparison between value /variable/operand, then Python program in run mode will tell whether an operand is greater than the other, lesser, equal, or a combination of those. Various comparison operators are ( ==, != , <>, >,<=, etc)

                >>> #Equal to (==) check whether first operand equal to the second
                >>> 5 == 5
                >>> x = 10
                >>> x == 11
                >>> # Not equal to (!=) will check whether first is not equal to the second
                >>> 3 != 1
                >>> 5 != 5

                Assignment Operator

                Assignment operators in Python assign the value to a variable. Assign variable that already has value to a variable is allowed. But we can not assign a variable that has no value to a variable. There are several assignment operators used in Python (=, +=, – = , *=, /= , etc.)

                Logical Operator

                Logical operators consist 3 operator: or, and, not. That are used for combined conditional statements are true or false. The ‘and’ operator return to True only if two side are True. The ‘or’ operator return to True if one or two side are True. The ‘not’ for True is False. The ‘not’ for False is True.

                Membership Operator

                Membership operator check whether some value is membership of lists. There are two membership operator in Python: ‘in’ and ‘not in’

                Identity Operator

                Identity operator check whether two object is same. There are two identity operator. There are ‘is’ and ‘not is’.

                Precedence operator

                Precedence operator avoids ambiguity. It determines which operators need to be evaluated first. Precedence operator consists of parenthesis or (). Then multiplication has a higher precedence than addition.