DEV Community

Chowdhury Sayeb Islam
Chowdhury Sayeb Islam

Posted on

Python 0.1

Hello, everyone! If you are reading this then I am really grateful that you are reading my write-up. Thank you. Let's start our very first lecture upon Python. Previous lecture- Python 0.0 was just a head start and now we will try to cover every topics related to Python Language Basics in the next few blogs. Here I will discuss about Variable and Basic operations and precedence. For coding I always use Google Colab but you can use anything, all are almost same.

Variable

In mathematics variables are usually expressed as x, y or z and the variables can have different values at a time. In Python, variable does not work like that. One have to express variable names by following the Variable Naming Conventions- https://www.python.org/dev/peps/pep-0008/#prescriptive-naming-conventions, and also they have to be sincere that they did not choose any Python reserved keywords- True, False, del, def, try, raise, None, return, if, else, elif, in, is, and, while, as, except, with, lambda, assert, finally, global, yield, break, for, not, class, from, pass, async, await, import, or, nonlocal, continue.
Variables are just like a container for storing different types of data as value.

stu_name = 'Sayeb'
print(stu_name)
print(type(stu_name)

Here the output will be Sayeb and .["stu_name" is the variable name and "'Sayeb'" is the value of that variable] But if I again write like this

stu_name = 123
print(stu_name)
print(type(stu_name)

Now the output will be 123 and . This makes clear that a similar variable can hold only one data type. If one uses the same variable name twice then the value will be changed. Python is also very case sensitive as it will detect stu_name
and Stu_name different variable names.
Values are always stored from the right side of the assignment(=) to the variable on the left side. Unlike other languages, in Python, we do not need to declare data types manually. The data type is decided by the interpreter during the run-time. If we follow the rules our code will become more understandable by the Human Readers (us).

Basic operations and precedence

You can use different operators in Python. Below the math operators precedence is given.

  Math Operators from Highest to Lowest Precedence

  Operator     Operation            Example      Evaluates to....

  **           Exponent               2 ** 3          8                            

  %            Modulus/remainder      22 % 8          6             

  //           Integer division/
             floored quotient       22 // 8         2

  /            Division               22 / 8          2.75

  *            Multiplication         3 * 5           15

  -            Subtraction            5 - 2           3

  +            Addition               5 + 2           7
Enter fullscreen mode Exit fullscreen mode

The order of operations (also called precedence) of Python math operators is similar to that of mathematics. The ** operator is evaluated first; the *, /, // and % operators are evaluated next, from left to right; and the + and - operators are evaluated last (also from left to right). You can use parentheses to override the usual precedence if you need to. Whitespace in between the operators and values doesn't matter for Python except for the indentation at the beginning of the line, but a single space is convention.

A programming language uses ‘operations’ to manipulate the
data stored in variables to achieve the desired results. Basic operations in Python is divided into two parts: Unary (meaning it is done with one variable) and Binary (meaning it is done using two variables or one variable and a single value of data).
Note: You cannot do any operation with None type.

Let’s explore each type of operation and understand what they do.

Unary operations

  1. Unary + (plus): We use unary + (plus) operation by adding a ‘+’ before a variable or data. It does not change the data. (Works with int, float, complex, and boolean. For booleans, True and False will be valued as 1 and 0 respectively.) For example:
 unary_p_1 = 1
 print(+unary_1)
 unary_p_2 = True
 print(+unary_2) 
Enter fullscreen mode Exit fullscreen mode
  1. Unary - (minus): We use unary - (minus) operation by adding a ‘-’ before a variable or data. It produces the negative value of the input (equivalent to the multiplication with -1). (Works with int, float, complex, and boolean. For booleans, True and False will be valued as 1 and 0 respectively.) For example:

unary_m_1 = 1.01
print(-unary_m_1)
unary_m_2 = False
print(-unary_m_2)

  1. Unary ~ (invert): We use unary - (invert) operation by adding a ‘~’ before a variable or data. It produces a bitwise inverse of a given data. Simply, for any data x, a bitwise inverse is defined in python as -(x+1). (Works with int, and boolean. For booleans, True and False will be valued as 1 and 0 respectively.) For example:

unary_i_1 = 9
print(~unary_1)
unary_i_2 = -10
print(~unary_i_2)
unary_i_3 = True
print(~unary_i_3)

Binary operation:

Operators are symbols that represent any kind of computation such as addition, subtraction, and etc.
The values or the variables the operator works on are called Operands.
1 + 2
Here, 1 and 2 are operands, and + is the operator computing addition.

1. Arithmetic operation

    a. + (addition)
    b. - (subtraction)
    c. * (multiplication)
Enter fullscreen mode Exit fullscreen mode

add = 6 + 1
add_1 = 6 + 2.0
subtrac = 6 - 1
subtrac_1 = 6 - 1.0
multi = 6 * 8
multi_1 = 6 * 8.0
print(add)
print(add_1)
print(subtrac)
print(subtrac_1)
print(multi)
print(multi_1)

d. / (division)
Division of numbers(float, int) yields a float results in float.

div_1 = 4 / 2
div_2 = -2 / 1
div_3 = 4 / 4.0
div_4 = -9.0 / 1
print( div_1 )
print( div_2 )
print( div_3 )
print( div_4 )

f. % (modulus)

g. ** (Exponentiation)
Basically it's the power operator (X**Y) = X^Y

1. Assignment operator
a. = (assign): It is used for putting value from the right
side of the equal sign(=) to a variable on the left side
of the equal sign(=).
For example: number = 123
print ( number )
.
b. Compound Assignment Operators:
i. += (add and assign)
ii. -= (subtract and assign)
iii. = (multiply and assign)
iv. /= (divide and assign)
v. %= (modulus and assign)
vi. *
= (exponent and assign)
vii. //= (floor division and assign)

2. Logical operator
a. and (logical AND)
b. or (logical OR)
c. not (Logical NOT)
Note: Details will be discussed in Branching.

3. Comparison or Relational operator

    a. == (equal)
    b. != (not equal)
    c. > (greater than)
    d. < (less than)
    e. >= (greater than or equal)
    f. <= (less than or equal)
       Note: Details will be discussed in _Branching_. 
Enter fullscreen mode Exit fullscreen mode

4. Membership Operator
a. in: Returns True if the first value is in the second.
Otherwise, returns False.
b. not in: Returns True if the first value is not in the
second. Otherwise, returns False.
Example:

print('t' in 'cat')
print('t' in 'caT')
print('t' not in 'caT')
print( 4 in [345, 7, 89, 4 ])

5. Identity Operators
Identity operators check whether two values are identical or
not.
a. is: Returns True if the first value is identical or the
same as the second value.Otherwise, returns False.
b. is not: Returns False if the first value is identical or
the same as the second value. Otherwise, returns
True.
Example:

print( '123' is 123 )
print( '456' is '456' )
print( 234 is not '234' )
print( 1 is 1.0 )
print( 4 is not 4.0 )

7. Bitwise Operators

     a. & (Bitwise and)
     b. | (Bitwise or)
     c. ^ (Bitwise xor)
     d. ~ (Bitwise 1’s complement)
     e. << (Bitwise left-shift)
     f. >> (Bitwise right-shift)
Enter fullscreen mode Exit fullscreen mode

Compound expression:

When we write an expression with two or more operations, it is called a compound expression. For example, we may write 7+9*3 where we have both addition and multiplication operations in a single expression. Determining the result of a compound expression is a little tricky. We need to think about what operation will be executed first. To determine that the computer follows Operator precedence, a set of rules that dictates the
computer should be done first. For our example, 7+9*3 the multiplication operation will have higher precedence and will be executed first. So the program will first calculate 9*3 which results in 27. Then it will calculate 7+27, which will result in 34.
Try the following examples and see what results in it shows:

5*3+2-1*2
1+7/7*7

Operator precedence:

In the table below precedence has been shown in descending order- highest to lowest. Highest precedence at the top, lowest at the bottom. Operators in the same precedence are evaluated from left to right.

 Operator                    Name of the operator/ Operation

   ()                           Parentheses (Grouping)

 f( args.... )                  Function call

 x[ index:index ]               Slicing

 x [ index ]                    Subscription

 x.attribute                    Attribute Reference

   **                           Exponentiation

   ~x                           Bitwise Not

  +x, -x                        Unary Plus, Unary Minus

  *, /, %, //                   Multiplication, Division, 
                                Modulus/ Remainder, Floor 
                                Quotient/ Integer Division 

  +, -                          Addition, Subtraction

  <<, >>                        Bitwise Shifts

   &                            Bitwise AND

   ^                            Bitwise XOR

   |                            Bitwise OR

  in, not in, is,               Comparisons, Membership,
  is not, <, <=,                Identity
  >, >=, <>, !=,
   ==

  not                           Boolean NOT

  and                           Boolean AND

  or                            Boolean OR

  lambda                        Lambda expression
Enter fullscreen mode Exit fullscreen mode

Type Conversion:

Data types can be modified in two ways: Implicit (when the compiler changes the type of a data for you(user)) and Explicit (when you ( the user) change the type of a data using type changing functions, it is called “ Type-casting” )

Note: What is the compiler will be explained later. Assume it ( the compiler ) to be like a teacher who checks your code for any kind of mistakes and shows the problems/ errors and sometimes does type conversion
for you ( the user ) according to the computation need of a statement.

1. Implicit Type Conversion:
   If any of the operands are floating-point, then arithmetic 
   operation yields a floating-point value. If the result was 
   integer instead of floating-point, then removal of the 
   fractional part would lead to the loss of information.

2. Explicit Type Conversion:
   Conversion among different data types are possible by 
   using type conversion functions, though there are few 
   restrictions. Python has several functions for this 
   purpose among them below 3 are most used:
     a. str() : constructs a string from various data types 
        such as strings, integer numbers and float-point 
        numbers. 
        For example:
            `var = 12.4
             var_string = str(var)
             print(var_string)
             print(type(var))
             print(type(var_string))`

     b. int(): constructs an integer number from various data 
        types such as strings ( the input string has to 
        consist of numbers without any decimal points, 
        basically whole numbers), and float-point numbers ( 
        by rounding up to a whole number, basically it 
        truncates the decimal part). 
        For example:
            `var_str = '12'
             var_int = int(var_str)
             print(var_int)
             print(type(var_str))
             print(type(var_int))`

     c. float(): constructs a floating-point number from 
        various data types such as integer
        numbers, and strings (the input string has to be a 
        whole number or a floating point number). 
        For example:
            `var_str = '12'
             var_float = float(var_str)
             print(var_float)
             print(type(var_str))
             print(type(var_float))`
Enter fullscreen mode Exit fullscreen mode

Input

For taking input from the user directly, Python has a special 
built-in function, input(). It takes a String as a prompt 
argument and it is optional. It is used to display 
information or messages to the user regarding the input. For 
example, “Please enter a number” is a prompt. After typing 
the data/input in the designated inbox box provided by the 
IDE ( Integrated Development Environment), the user needs to 
press the ENTER key, otherwise the program will be waiting 
for the user input indefinitely. The input() function 
converts it to a string and then returns the string to be 
assigned to the target variable.

             `val = input()
              print(val)
              print(type(val))`
Enter fullscreen mode Exit fullscreen mode

Okay, that is the end of our today's lesson. In the next lesson, we will discuss about three data types integer, float and string.

Top comments (0)