Вы находитесь на странице: 1из 28

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)