Python Basic

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 34

PYTHON_TUTORIAL

Suman Halder
Key features

Python has many reasons for being popular and in demand. A few of the
reasons are mentioned below.
• Emphasis on code readability, shorter codes, ease of writing.
• Programmers can express logical concepts in fewer lines of code in
comparison to languages such as C++ or Java.
• Python supports multiple programming paradigms, like object-oriented,
imperative and functional programming or procedural.
• It provides extensive support libraries(Django for web development, Pandas
for data analytics etc)
• Dynamically typed language(Data type is based on value assigned)
• Philosophy is “Simplicity is the best”.
                   Application Areas
1) Printing hello world-->      print("Hello World")    [no need of ;]
x = 5;y=6
print( "x =%d y=%d"%(x,y) )
2) Python Indentation--> 
Python uses indentation to highlight the blocks of code. Whitespace is used for indentation in Python. All statements
with the same distance to the right belong to the same block of code. If a block has to be more deeply nested, it is
simply indented further to the right. You can understand it better by looking at the following lines of code.

# Python program showing 


# indentation 
    home = 'hyd'
    
if home == 'hyd': 
    print('hyd has charminar')
    print("hyd has Goalkonda also")
else: 
    print('other city dont have charminar') 
print('All ok !') 
3) python_comments-->
Single line comments: Python single line comment starts with hashtag symbol
with no white spaces.
--->   # This is a comment
Multi-line string as comment: Python multi-line comment is a piece of text
enclosed in a delimiter (“””) on each end of the comment.
--> 
""" 
This would be a multiline comment in Python that 
spans several lines    
… 
"""
4) Variables
Variables in Python are not “statically typed”. We do not need to declare variables before using
them or declare their type. A variable is created the moment we first assign a value to it.
# An integer assignment
age = 45                   
# A floating point
salary = 1456.8           
# A string
name = "John"           
print(age)
print(salary)
print(name)
#ALTERNATIVE-->
age,salary,name = 45,1456.8,"John"               
print(age,salary,name)
Operators
Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations
on operands. These operators can be categorized based upon their different functionality:
• Arithmetic operators: Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication and division.
# Examples of Arithmetic Operator 
a=9
b=4
# Addition of numbers 
add = a + b 
# Subtraction of numbers 
sub = a - b 
# Multiplication of number 
mul = a * b 
# Division(float) of number 
div1 = a / b 
# Division(floor) of number 
div2 = a // b 
# Modulo of both number 
mod = a % b 
   # print results 
print(add,sub,mul,div1,div2,mod)
Alternatively--> print(a+b,a-b,a*b,a/b,a//b,a%b)
Relational Operators: Relational operators compares the values. It either returns True or False according
to the condition.
# Examples of Relational Operators 
a = 13
b = 33
# a > b is False 
print(a > b) 
# a < b is True 
print(a < b) 
# a == b is False 
print(a == b) 
# a != b is True 
print(a != b) 
# a >= b is False 
print(a >= b) 
# a <= b is True 
print(a <= b) 
Logical Operators: Logical operators perform Logical AND, Logical OR and
Logical NOT operations

# Examples of Logical Operator 


a = True
b = False
# Print a and b is False 
print(a and b) 
# Print a or b is True 
print(a or b) 
# Print not a is False 
print(not a)
Assignment operators: Assignment operators are used to assign values to the
variables.
Special operators: Special operators are of two types-
Identity operator that contains is and is not.
Membership operator that contains in and not in.

# Examples of Identity and 


# Membership operator 
a1 = 'Bitsilica'
b1 = 'Bitsilica'
# Identity operator 
print(a1 is not b1) 
print(a1 is b1) 
# Membership operator 
print("B" in a1) 
print("a" not in b1)
TAKING_INPUT
• raw_input(): This function works in older version (like Python 2.x). This function takes exactly what is typed from the keyboard, convert it
to string and then return it to the variable in which we want to store. For example:
filter_none
brightness_4
# Python program showing  
# a use of raw_input() 
    
g = raw_input("Enter your name : ")  
print g  
• input(): This function first takes the input from the user and then evaluates the expression, which means Python automatically identifies
whether the user entered a string or a number or list. For example:
filter_none
brightness_4
# Python program showing  
# a use of input() 
    
val = input("Enter your value: ")  
print(val)
                                  STRING 
Python has a set of built-in methods that you can use on strings.
Note: All string methods returns new values. They do not change the original
string.

1)capitalize-->
Upper case the first letter in this sentence:
txt = "hello, and welcome to my world."

x = txt.capitalize()

print (x)
2) casefold-->
#Make the string lower case:
txt = "Hello, And Welcome To My World!"
x = txt.casefold()
print(x)
3) center-->
#Print the word "banana", taking up the space of 20 characters, with "banana" in
the middle:
txt = "banana"
x = txt.center(20)
print(x)
4)count-->
#Return the number of times the value "apple" appears in the string:
txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple")
print(x)

5) endswith-->
#Check if the string ends with a punctuation sign (.):
txt = "Hello, welcome to my world."
x = txt.endswith(".")
print(x)
6) find-->
#Where in the text is the word "welcome"?:
txt = "Hello, welcome to my world."
x = txt.find("welcome")
print(x)
[throws –1 not found case]
7)index--> 
#Where in the text is the word "welcome"?:
txt = "Hello, welcome to my world."
x = txt.index("welcome")
print(x)
[throws exception not found case ]
8)format-->
#Using different placeholder values:
print("My name is {fname}, I'am {age}".format(fname = "John", age = 36))
print("My name is {0}, I'am {1}".format("John",36))
print("My name is {}, I'am {}".format("John",36))
9) isalnum--> 
#Check if all the characters in the text are alphanumeric:
txt = "Company12"
x = txt.isalnum()
print(x)
10) isalpha-->
#Check if all the characters in the text are letters:
txt = "CompanyX"
x = txt.isalpha()
print(x)

11) isdigit-->
#Check if all the characters in the text are digits:
txt = "50800"
x = txt.isdigit()
print(x)
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric


isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title


isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string


20) join-->
#Join all items in a tuple into a string, using a hash character as separator:
myTuple = ("John", "Peter", "Vicky")
x = "|".join(myTuple)
print(x)
21) partition--> 
#Search for the word "bananas", and return a tuple with three elements:
#1 - everything before the "match"
#2 - the "match"
#3 - everything after the "match"
txt = "I could eat bananas all day"
x = txt.partition("bananas")
print(x)
22) replace()-->
#Replace the word "bananas":
txt = "I like bananas"
x = txt.replace("bananas", "apples")
print(x)
23) rindex() --> 
#Where in the text is the last occurrence of the string "casa"?:
txt = "Mi casa, su casa."
x = txt.rindex("casa")
print(x)
24) rsplit() --> 
#Split a string into a list, using comma, followed by a space (, ) as the separator:
txt = "apple, banana, cherry"
x = txt.rsplit(", ")
print(x)
25) split-->
#Split a string into a list where each word is a list item:
txt = "welcome to the jungle"
x = txt.split()
print(x) [[little faster]]
26) splitlines()-->
#Split a string into a list where each line is a list item:
txt = "Thank you for the music\nWelcome to the jungle"
x = txt.splitlines()
print(x)
27) startswith()-->
#Check if the string starts with "Hello":
txt = "Hello, welcome to my world."
x = txt.startswith("Hello")
print(x)
28) strip--> 
#Remove spaces at the beginning and at the end of
swapcase() Swaps cases, lower case the string:
becomes upper case and vice txt = "     banana     "
versa x = txt.strip()
print("of all fruits", x, "is my favorite")
29) zfill-->
title() Converts the first character of #Fill the string with zeros until it is 10 characters long:
each word to upper case txt = "50"
x = txt.zfill(10)
translate() Returns a translated string print(x)

upper() Converts a string into upper case


                           If-else-elif && loop
1) The elif keyword is pythons way of saying "if the previous conditions were
not true, then try this condition"
2) if statements cannot be empty, but if you for some reason have
an if statement with no content, put in the pass statement to avoid getting
an error.
3) print("A") if a > b else print("=") if a == b else print("B")
4) i = 0
while i < value:     --> format
5) for x in range(start, end, increament):
Python Collections (Arrays)

There are four collection data types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate
members.
• Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
• Set is a collection which is unordered and unindexed. No duplicate
members.
• Dictionary is a collection which is unordered, changeable and indexed. No
duplicate members.
When choosing a collection type, it is useful to understand the properties
of that type. Choosing the right type for a particular data set could mean
retention of meaning, and, it could mean an increase in efficiency or
security.
                                       LISTS
thislist = ["apple", "banana", "cherry"]
print(thislist[1]) --> print 2nd item
2) print(thislist[-1]) --> print last item
3) thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5]) --> Return the third, fourth, and fifth item
4) print(thislist[:4]) --> This example returns the items from the beginning to "orange"
5) print(thislist[2:]) --> This example returns the items from "cherry" and to the end:
6) print(thislist[-4:-1])--> This example returns the items from index -4 (included) to index
-1 (excluded)
7) thislist[1] = "blackcurrant"
8) print(len(thislist)) --> Print the number of items in the list:
9) thislist.append("orange")--> Using the append() method to append an item
10) thislist.insert(1, "orange") --> To add an item at the specified index, use
the insert() method:
11) thislist.remove("banana") 
12) thislist.pop() --> The pop() method removes the specified index, (or the last
item if index is not specified):
13) del thislist[0]--> The del keyword removes the specified index:
14) list1.extend(list2) --> Use the extend() method to add list2 at the end of list1:
15) fruits.reverse() --> Reverse the order of the list:
16) sorted(iterable, key=key, reverse=reverse)
a = ("h", "b","c","g", "a", "c", "f", "d", "e", "g","g")
x = sorted(a, key=a.count,reverse=True)
print(x[:1])
17) list.sort(reverse=True|False, key=myFunc)
# A function that returns the length of the value:
def myFunc(e):
  return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(reverse=True, key=myFunc)
                                           FILE
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists

1) f = open("demofile.txt", "rt")--> read mode text file


2) f1=open("file2.txt","w") --> write mode
3) for x in f: --> accessing line by line
4) f.close() --> for closing file
5) f.write("Now the file has more content!") --> to write in a file.
6) with open("file2.txt","w") as f1:
    for (n1,n2,n3) in zip(nstr1,nstr2,nstr3):
        f1.write("{0}{1}{2}\n".format(n1,n2,n3))
                                       regex
1) Python has a built-in package called re, which can be used to work with
Regular Expressions.
Import the re module:
2) x = re.search("^Begin.*End$", txt)--> match begin and end
3) x = re.search("match_word", txt) --> it will throw the span also
4) x = re.split("spilt_character", txt) --> spilt char stored in a list 
5) x = re.sub("replaced_string", "replacing_string", txt)
6) pattern2=re.compile(r'(.*) (.*)')
mo2 = pattern2.search(x)
mo2.group(2))],mo2.group(1)
DICTIONARY
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
1) dict.get(key, default = None) --> Python dictionary method get() returns a
value for the given key. If key is not available then returns default value None.
2) dict.items()--> Returns a list of dict's (key, value) tuple pairs
3) dict.keys()--> Returns list of dictionary dict's keys
4) dict.update(dict2)--> Python dictionary method update() adds dictionary dict2's
key-values pairs in to dict. This function does not return anything.
5) dict.values()--> Python dictionary method values() returns a list of all the values
available in a given dictionary. 
                               NumPy
1) import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
2) To create an ndarray, we can pass a list, tuple or any array-like object into
the array() method, and it will be converted into an ndarray
3)NumPy Arrays provides the ndim attribute that returns an integer that tells us how
many dimensions the array have.
4) import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])
5) print('Last element from 2nd dim: ', arr[1, -1])
6) print(arr[1:5])--> We can also define the step, like this: [start:end:step].
7) arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 2])  --> From both elements, return index 2:
8) arr = np.array(['apple', 'banana', 'cherry'])
print(arr.dtype) --> Get the data type of an array containing strings:
9) arr = np.array([1, 2, 3, 4], dtype='i4')
print(arr)
print(arr.dtype) --> Create an array with data type 4 bytes integer:
10) arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype('i') --> Change data type from float to integer by using int as
parameter value:
11) arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
arr[0] = 42
print(arr)
print(x)--> Make a copy, change the original array, and display both arrays:
12) arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(arr.shape) --> The example above returns (2, 4), which means that the array
has 2 dimensions, and each dimension has 4 elements.
13) arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(4, 3) --> The outermost dimension will have 4 arrays, each with
3 elements:
14) arr = np.array([[1, 2, 3], [4, 5, 6]])
newarr = arr.reshape(-1) --> Flattening array means converting a multidimensional
array into a 1D array.
15) for x in np.nditer(arr, flags=['buffered'], op_dtypes=['S']): --> We can
use op_dtypes argument and pass it the expected datatype to change the datatype
of elements while iterating.
NumPy does not change the data type of the element in-place (where the element is
in array) so it needs some other space to perform this action, that extra space is
called buffer, and in order to enable it in nditer() we
pass flags=['buffered'].
16) arr = np.concatenate((arr1, arr2)) --> We pass a sequence of arrays that we want to join to
the concatenate() function, along with the axis. If axis is not explicitly passed, it is taken as
0.
17) arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
arr = np.concatenate((arr1, arr2), axis=1)--> [1 2 5 6] [3 4 7 8]
18) arr = np.hstack((arr1, arr2))--> NumPy provides a helper function: hstack() to stack
along rows.
19) newarr = np.array_split(arr, 3)-->We use array_split() for splitting arrays, we pass it
the array we want to split and the number of splits
20) arr = np.array([1, 2, 3, 4, 5, 4, 4])
x = np.where(arr == 4) --> Find the indexes where the value is 4:
21) x = np.where(arr%2 == 0) --> Find the indexes where the values are even:
22) arr = np.array([6, 7, 8, 9])
x = np.searchsorted(arr, 9)--> There is a method called searchsorted() which performs a
binary search in the array, and returns the index where the specified value would be inserted
to maintain the search order.
23) arr = np.array([3, 2, 0, 1])
print(np.sort(arr)) --> 
24) z = np.add(x, y) --> 

You might also like