Understanding Basic Python with Some Examples.

Abu Kaisar
Analytics Vidhya
8 min readNov 26, 2019

--

Python is a high-level, interpreted and dynamic programming language. It was first created by Guido van Rossum in 1991. This language is easier than any other programming language. Most of the AI-based application and Scientific applications are implemented by this programing language. Because its less cost, availability, training, and efficiency are high from other programming languages. The powerful library is a big advantage of this language, which very helpful for machine learning and deep learning problem solve easily.

Why Python?

  1. Beginner Friendly
  2. Easy to understand
  3. Very Flexible
  4. Dynamic
  5. Object-oriented
  6. Portable
  7. Extensive Support Library
  8. Productivity

Use of Python Language

  • Machine learning
  • Data Science
  • Artificial Intelligence
  • Deep Learning
  • Natural Language Processing
  • Computer Vision
  • Image processing
  • Pattern Recognition

Install Python 3: https://www.python.org/downloads/

Anaconda3 Install https://www.anaconda.com/distribution/

Python Comments and Docstrings

1. Comment start with a single #.

2. Document capability of python is called docstring. docstring can be one line or multiline. Docstring also is a comment.

#this is a comment. Single line comment"""this is                     //Multiline comment 
a multiline docstring
"""

1. Print Function

print() function is used to shows the output of a specific text message on the screen.

print("Hello word!")
the output of a print function

2. Creating Variables

Python has no command for declaring a variable. Type of a variable is not to required define. It can understand the type of variable is automatically. This is different from other programming languages.

a=10             #a is int type
b=12.45567 #b is float type
c="Kaisar" #c is string type
print(a)
print(b)
print(c)

type() is a built-in function which is used to check the type of a variable.

print(type(a))  # type is a built in function 
print(type(b))
print(type(c))
the output of the type function

3. Operators

In python, the operators are divided into many parts based on their operation.

Arithmatic operators: +,-,*,/,%,**,//
Comparison operastors: ==,!=,>,<,>=,<=
Boolean operators: True,False
Assignment operators: =,+=,-=,*=,/=
Logical operators: and,or,not
Membership operators: in, not in
Identity operators: is, not is

Arithmetic Operation

print(2-3)
print(2*3)
print(4/2)
print(100%25)
print(2**3)# ** 2 base 3 or 2^3
print(5//2) #floor division

Comparison Operator

print(2==2)
print(2!=2)
print(2>2)
print(2<2)
print(2>=2)
print(2<=2)

Logical Operator

print(2==2 and 2==3)
print(2==2 or 2==3)
print(not 2==3)

Membership Operator

a="Bangladesh"
b="Bangla"
print(b in b)
print(b not in a)

Identity Operator

print(b is a)
print(b is not a)

4. Taking Input from User

Before taking user input variables need to define the type. for taking the input from user input() is used. But variable with input function contains a string variable.

a=int(input("enter a int value:"))#take integer value  b=float(input("enter a flaot value:"))#take flaot value  c=input("enter a string:")#take string  
print(a)
print(b)
print(c)

5. Math Operation

print((1+1)*(15-3)/2)#following PEMDAS rulesoutput:   12.0s1="ash"
print(s1*3) #String s1 multiplied by 3 times
n=10.020233
print(n/3) # Division function
print(n//3) # Floor divisin
output: ashashas
3.3400776666666663
3.0

a=3
print(a**3) # ** means the power of the variable
ouput: 27print(eval("1 + 2 * 3 + 155"))
#eval() build in fuction for evaluate expression
output: 162

6. String

String literals in python are encompassed by either single quotes or twofold quotes.

String index number working as s[0],s[1],s[2]….s[n] and reverse order are start from s[-1]…s[-n]

s1="Bangladesh is my country" 
print(s1)
output: Bangladesh is my countryprint(s1[1])#print the string index number working as s[0],s[1],s[2]....s[n]output: aprint(s1[-1])#print the string as reverse order start with s[-1]...s[-n]output: yprint(s1[2:10])#print the character from position 2 to 10
output: ngladesh
print(s1[10::])#print the character after index 10 to end od string
output:
is my country
print(s1[:3])#print start to index3 stringoutput: Ban

For find out the length of a string use len() function.

print(len(s1))output: 24

Case conversion such as upper and lower case conversion will be using lower() and upper() function

print(s1.lower())#convert the srting in lower case 
print(s1.upper())#convert the srting in Upper case

Split text is important to divide a sentence into a word, split() function are used to do that.

print(s1.split())#split the sentence to a single wor

replace() function is used to replace a character in text data.

print(s1.replace("m","M"))

concatenate two string using only “+” operator.

s1="My name is " 
s2=input()
print(s1+s2)

7. List

A list is an assortment which is requested and variable. In Python, records are composed of square sections. Variable type of items does not need to define in a list. Each value is separated by a comma.

l1=["kaisar","rakib","imran"]
print(l1)

List index starts form zero, one, two and so on. Reverse order starts from minus one, minus two and so forth.

print(l1[2])
print(l1[0:2])#print before index2 value

some example of built-in list functions & methods.

l1.append("ashraful")
output:
['kaisar', 'rakib', 'imran', 'ashraful']
l1.insert(4,"shakil")#intsert with position print(l1)
output:
['kaisar', 'rakib', 'imran', 'ashraful', 'shakil']
del(l1[4])#delete list in specific position
output:
['kaisar', 'rakib', 'imran', 'ashraful']
l1.reverse()
output:
['ashraful', 'imran', 'kaisar', 'rakib']

l1.sort()
output:
['ashraful', 'imran', 'kaisar', 'rakib']
#some method as like pop(),remove(),clear()...etc

8. Tuples

A tuple is an arrangement of unchanging Python objects. Tuples are arrangements, much the same as records. The contrasts among tuples and records are, the tuples can’t be changed not normal for records and tuples use enclosures, though records utilize square sections.

Tuple = ("apple", "banana", "cherry")
print(Tuple)
output: ('apple', 'banana', 'cherry')Tuple = ("apple", "banana", "cherry")
print(Tuple[1])
output: bananaprint(len(Tuple))output: 3

9. Sets

A set is a collection which is unordered and unindexed. In python, sets are written with curly brackets.

thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)output:
{'cherry', 'orange', 'banana', 'apple'}
thisset.update(["orange", "mango", "grapes"])#update the value of set
print(thisset)
output:
{'banana', 'apple', 'cherry', 'mango', 'grapes', 'orange'}

10. Dictionary

A dictionary is a collection which is unordered, changeable and indexed. written with curly brackets, and they have keys and values.

thisdict =	{
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
x = thisdict["model"] 
print(x)
output: Mustangx = thisdict.get("model")#get the value of key
print(x)
output: Mustang

In a dictionary, the list is also used to carrying multiple values.

d={6759:["kaisar","Student","CSE"],
7100:"ash"
}
print(d[6759])

11. If … Else

An else proclamation can be joined with an if articulation. An else proclamation contains the square of code that executes if the restrictive articulation in the if explanation sets out to 0 or a FALSE worth. The else explanation is a discretionary proclamation and there could be all things considered only one else articulation following if.

if expression:
statement(s)
else:
statement(s)
Example of one line if and else
If else example for binary value

12. For Loop

A for loop is utilized for repeating over a succession (that is either a list, a tuple, a dictionary, a set, or a string).

range(start,stop,step)

start: Starting a number of the sequence.

stop: Generate numbers up to, but not including this number.

step: Difference between each number in the sequence.

print value in 1 to 10 which is increment by 2
Odd and Even number using for loop
Print list value using for loop
Break condition in a loop
Continue condition in a loop

13. While Loop

The formation of a simple while loop is demonstrated as follows.

while expr:
statement(s)
Example of a while loop

14. Functions

In python, a function is a gathering of related articulations that play out a particular undertaking. Capacities help break the program into littler and particular pieces. As the program develops bigger and bigger, functions make it progressively sorted out and sensible. Moreover, it maintains a strategic distance from reiteration and makes code reusable.

def function_name(parameters): # formate of define a function
statement(s)
Example of a simple function
Parameter pass in a function
Return statement of a function
User input with a function

15. Lambda

A lambda function is a small anonymous function. It can take any number of contentions, yet can just have one articulation.

Syntex = lambda arguments : expression

Example of a lambda function

16. Files

File handling is an important part of any programing language. Python has several functions for creating, reading, updating, and deleting files.

"r" = Read - Opens a file for reading.

"a" = Append - Opens a file for appending.

"w" = Write - Opens a file for writing.

"x" -= Create - Creates the specified file.

Example of an open file
Example of write file with a string
Read the inserted string form created file

Github: https://github.com/AbuKaisar24/Basic-Python-Code/blob/master/Python%20Basic%20.ipynb

--

--