DEV Community

Cover image for PYTHON BASICS
ssenyonga yasin
ssenyonga yasin

Posted on

PYTHON BASICS

Python is an interpreted high-level general-purpose programming language. Python's design philosophy emphasizes code readability with its notable use of significant indentation.

python

Enter fullscreen mode Exit fullscreen mode

Common Feature Provided By python

Simplicity-> Think less of the syntax of the language and more of the code.

Open Source-> A powerful language and it is free for everyone to use and alter as needed.

Portability->Python code can be shared and it would work the same way it was intended to. Seamless and hassle-free.

Applications of Python.

Artificial Intelligence
Desktop Application
Automation
Web Development

Python Hello World.
Launch the VS code ,create a new python file, let say hello.py file and enter the following code and save the file:

print('Hello, World!')
Enter fullscreen mode Exit fullscreen mode

The print() is a built-in function that displays a message on the screen. In our case, it’ll show the message 'Hello, Word!'.

Executing the Python program.

To execute the file we created above, you launch the Command Prompt or Terminal on vascode.

After that, type the following command,
Python3 hello.py

output


Hello, World!

Enter fullscreen mode Exit fullscreen mode

Comments

A comment is text in a program's code, script, or another file that is not meant to be seen by the user .

Comments help make code easier to understand by explaining what is happening in the code

single line comment

'''
multiline comment

Using docstring
'''

Arithmetic Operators.
print(46 + 2) # 48 (addition)
print(10 - 9) # 1 (subtraction)
print(3 * 3) # 9 (multiplication)
print(84 / 2) # 42.0 (division)
print(2 ** 8) # 256 (exponent)
print(11 % 2) # 1 (remainder of the division)
print(11 // 2) # 5 (floor division)

Variables

What is a Variable in Python?

A Python variable is a reserved memory location to store values. In other words, a variable in a python program gives data to the computer for processing.

Python Variable Types

Every value in Python has a datatype. Different data types in Python are Numbers, List, Tuple, Strings, Dictionary, etc. Variables in Python can be declared by any name or even alphabets like a, aa, abc, etc.

How to Declare and use a Variable

Let see an example. We will define variable in Python and declare it as "a" and print it.


a=100 
print (a)
Enter fullscreen mode Exit fullscreen mode

Re-declare a Variable

You can re-declare Python variables even after you have declared once.

Here we have Python declare variable initialized to f=0.

Later, we re-assign the variable f to any value

Python 2 Example

# Declare a variable and initialize it

f = 0
print f
# re-declaring the variable works
f = 'new'
print f
Enter fullscreen mode Exit fullscreen mode

Python 3 Example

# Declare a variable and initialize it
f = 0
print(f)
# re-declaring the variable works
f = 'new'
print(f)
Enter fullscreen mode Exit fullscreen mode

Python String Concatenation and Variable

Let's see whether you can concatenate different data types like string and number together. For example, we will concatenate "new" with the number "version".

For the following code, you will get undefined output -

a="new"
b = "version"
print a+b
Enter fullscreen mode Exit fullscreen mode

Once the integer is declared as string, it can concatenate both

a="new"
b = "version"
print(a+str(b))
Enter fullscreen mode Exit fullscreen mode

Python Variable Types: Local & Global

There are two types of variables in Python, Global variable and Local variable. When you want to use the same variable for rest of your program or module you declare it as a global variable, while if you want to use the variable in a specific function or method, you use a local variable while Python variable declaration.

Let's understand this Python variable types with the difference between local and global variables in the below program.

Let us define variable in Python where the variable "f" is global in scope and is assigned value 101 which is printed in output
Variable f is again declared in function and assumes local scope. It is assigned value "I am learning Python." which is printed out as an output. This Python declare variable is different from the global variable "f" defined earlier
Once the function call is over, the local variable f is destroyed.

What are Logical Operators in Python?

Logical Operators in Python are used to perform logical operations on the values of variables. The value is either true or false. We can figure out the conditions by the result of the truth values. There are mainly three types of logical operators in python : logical AND, logical OR and logical NOT. Operators are represented by keywords or special characters.

Arithmetic Operators
Comparison Operators
Python Assignment Operators
Logical Operators or Bitwise Operators
Membership Operators
Identity Operators
Operator precedence

Arithmetic Operators

Arithmetic Operators perform various arithmetic calculations like addition, subtraction, multiplication, division, %modulus, exponent, etc. There are various methods for arithmetic calculation in Python like you can use the eval function, declare variable & calculate, or call functions.

Example: For arithmetic operators we will take simple example of addition where we will add two-digit 4+5=9

x= 4    
y= 5
print(x + y)
Enter fullscreen mode Exit fullscreen mode

Similarly, you can use other arithmetic operators like for multiplication(*), division (/), substraction (-), etc.

Comparison Operators

Comparison Operators In Python compares the values on either side of the operand and determines the relation between them. It is also referred to as relational operators. Various comparison operators in python are ( ==, != , <>, >,<=, etc.)

Example: For comparison operators we will compare the value of x to the value of y and print the result in true or false. Here in example, our value of x = 4 which is smaller than y = 5, so when we print the value as x>y, it actually compares the value of x to y and since it is not correct, it returns false.

x = 4
y = 5
print(('x > y  is',x>y))
Enter fullscreen mode Exit fullscreen mode

Likewise, you can try other comparison operators (x < y, x==y, x!=y, etc.)

Python Assignment Operators

Assignment Operators in Python are used for assigning the value of the right operand to the left operand. Various assignment operators used in Python are (+=, - = , *=, /= , etc.).

Example: Python assignment operators is simply to assign the value, for example

num1 = 4
num2 = 5
print(("Line 1 - Value of num1 : ", num1))
print(("Line 2 - Value of num2 : ", num2))
Enter fullscreen mode Exit fullscreen mode

Example of compound assignment operator

We can also use a compound assignment operator, where you can add, subtract, multiply right operand to left and assign addition (or any other arithmetic function) to the left operand.

Step 1: Assign value to num1 and num2
Step 2: Add value of num1 and num2 (4+5=9)
Step 3: To this result add num1 to the output of Step 2 ( 9+4)
Step 4: It will print the final result as 13

num1 = 4
num2 = 5
res = num1 + num2
res += num1
print(("Line 1 - Result of + is ", res))
Enter fullscreen mode Exit fullscreen mode

Logical Operators

Logical operators in Python are used for conditional statements are true or false. Logical operators in Python are AND, OR and NOT. For logical operators following condition are applied.

For AND operator – It returns TRUE if both the operands (right side and left side) are true
For OR operator- It returns TRUE if either of the operand (right side or left side) is true
For NOT operator- returns TRUE if operand is false
Example: Here in example we get true or false based on the value of a and b

a = True
b = False
print(('a and b is',a and b))
print(('a or b is',a or b))
print(('not a is',not a))
Enter fullscreen mode Exit fullscreen mode

Membership Operators

These operators test for membership in a sequence such as lists, strings or tuples. There are two membership operators that are used in Python. (in, not in). It gives the result based on the variable present in specified sequence or string

Example: For example here we check whether the value of x=4 and value of y=8 is available in list or not, by using in and not in operators.

x = 4
y = 8
list = [1, 2, 3, 4, 5 ];
if ( x in list ):
   print("Line 1 - x is available in the given list")
else:
   print("Line 1 - x is not available in the given list")
if ( y not in list ):
   print("Line 2 - y is not available in the given list")
else:
   print("Line 2 - y is available in the given list")
Enter fullscreen mode Exit fullscreen mode

Declare the value for x and y
Declare the value of list
Use the "in" operator in code with if statement to check the value of x existing in the list and print the result accordingly
Use the "not in" operator in code with if statement to check the value of y exist in the list and print the result accordingly
Run the code- When the code run it gives the desired output

Identity Operators

Identity Operators in Python are used to compare the memory location of two objects. The two identity operators used in Python are (is, is not).

Operator is: It returns true if two variables point the same object and false otherwise
Operator is not: It returns false if two variables point the same object and true otherwise
Following operands are in decreasing order of precedence.

Operators in the same box evaluate left to right

Operators (Decreasing order of precedence) Meaning
** Exponent
, /, //, % Multiplication, Division, Floor division, Modulus
+, - Addition, Subtraction
<= < > >= Comparison operators
= %= /= //= -= += *= *
= Assignment Operators
is is not Identity operators
in not in Membership operators
not or and Logical operators
Example:

x = 20
y = 20
if ( x is y ): 
    print("x & y  SAME identity")
y=30
if ( x is not y ):
    print("x & y have DIFFERENT identity")
Enter fullscreen mode Exit fullscreen mode

Declare the value for variable x and y
Use the operator "is" in code to check if value of x is same as y
Next we use the operator "is not" in code if value of x is not same as y
Run the code- The output of the result is as expected
Operator precedence
The operator precedence determines which operators need to be evaluated first. To avoid ambiguity in values, precedence operators are necessary. Just like in normal multiplication method, multiplication has a higher precedence than addition. For example in 3+ 4*5, the answer is 23, to change the order of precedence we use a parentheses (3+4)5, now the answer is 35. Precedence operator used in Python are (unary + - ~, *, * / %, + - , &) etc.

v = 4
w = 5
x = 8
y = 2
z = 0
z = (v+w) * x / y;   
print("Value of (v+w) * x/ y is ",  z)
Enter fullscreen mode Exit fullscreen mode

Declare the value of variable v,w…z
Now apply the formula and run the code
The code will execute and calculate the variable with higher precedence and will give the output
Python 2 Example
Above examples are Python 3 codes, if you want to use Python 2, please consider following codes

#Arithmetic Operators
x= 4    
y= 5
print x + y

#Comparison Operators
x = 4
y = 5
print('x > y  is',x>y)

#Assignment Operators
num1 = 4
num2 = 5
print ("Line 1 - Value of num1 : ", num1)
print ("Line 2 - Value of num2 : ", num2)

#compound assignment operator
num1 = 4
num2 = 5
res = num1 + num2
res += num1
print ("Line 1 - Result of + is ", res)

#Logical Operators
a = True
b = False
print('a and b is',a and b)
print('a or b is',a or b)
print('not a is',not a)

#Membership Operators
x = 4
y = 8
list = [1, 2, 3, 4, 5 ];
if ( x in list ):
   print "Line 1 - x is available in the given list"
else:
   print "Line 1 - x is not available in the given list"
if ( y not in list ):
   print "Line 2 - y is not available in the given list"
else:
   print "Line 2 - y is available in the given list"

#Identity Operators
x = 20
y = 20
if ( x is y ):
    print "x & y  SAME identity"
y=30
if ( x is not y ):
    print "x & y have DIFFERENT identity"

#Operator precedence
v = 4
w = 5
x = 8
y = 2
z = 0
z = (v+w) * x / y;   
print "Value of (v+w) * x/ y is
pi = 3.14 # float
total = age + pi # float
print(type(age), type(pi), type(total)) # <class 'int'> <class 'float'> <class 'float'>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)