Basics of Python
Getting Started with Python
Python is a broadly used programming language for universally useful programming, made by Guido van Rossum and first delivered in 1991. Python includes a dynamic type system and automatic memory management and supports different programming standards, including object-oriented programming, basic, functional, and procedural styles. It has an enormous and comprehensive standard library.
You can install python from here.
Hello, World in Python using IDLE
IDLE is a simple editor for python that comes bundled with python.
Open IDLE on your system, it will open a shell with options along at the top.
- In the shell, there is a prompt of three right angle brackets:
- Now write the following code in the prompt:
print(“Hello, World”)
- Hit Enter
Creating variables and assigning values
<variable name> = <value>
Python utilizes = to relegate value to variables. There is no need to declare a variable in advance, or to relegate a data type of it. Relegating a value to a variable itself proclaims and introduces the variable with that value. It is basically impossible to proclaims a variable without relegating it an initial value.
# Integer
a = 2
print(a)
# Output: 2
# Floating Point pi = 3.14 print(pi) # Output: 3.14
# String
name = "Shakshi Tripathi" print(name) # Output: Shakshi Tripathi # Boolean a = True print(a) # Output: True Variable assignment works from left to right. So, the code will give you an error. 0 = x print(x) SyntaxError: can't assign to literal
Datatypes
Numbers:
Int: Integer a = 2 b = 25 c = 100
Float: Floating Point
a = 2.0 b = 500.e0 c = 1245687979.e1
Complex: a = 2 + 10j b = 100 + 100j
Strings a = "Shakshi" b = "Tripathi" c = "Shakshi Tripathi"
Sequences and Collections:
Tuple: An ordered collection of n values of any type (n >= 0). a = (1, 2, 3) b = ('a', 1, (1,2)) List: An ordered collection of n values (n >=0) a = [1, 2, 3] b = ['a', 1, [1, 2, 3], [3, 2, 'd']]
Set: An unordered collection of unique values. Items must be hashable. a = {1, 2, 'a'} Dict: An unordered collection of unique key-value pairs, keys must be hashable. a = {1 : 'one', 2 : 'two'} b = {'a' : 'apple', 'b' : 'book'}
Simple Mathematical Operators
Mathematical Operators for Programming
Division
a, b, c, d, e = 3, 2, 2.0, -3, 10 a/b # = 1 a/c # = 1.5 d/b # = -2 b/a # = 0 d/e # = -1
Addition
a, b = 1, 2 a + b # = 3
Exponentiation
a, b = 2, 3 (a ** b) # = 8 pow(a,b) # = 8
Trigonometric Functions
a, b = 1, 2 import math math.sin(a) # returns the sine of 'a' in radians math.cosh(b) # returns the inverse hyperbolic cosine of 'b' in radians math.atan(math.pi) # returns the arc tangent of 'pi' in radians math.hypot(a, b) # returns the Euclidean norm
Inplace Operations
a += 1 # means a = a + 1 a *= 2 # means a = a * 2
Subtraction
a, b = 1, 2 b - a # = 1
Multiplication
a, b = 2, 3 a * b # = 6
Modulus
(3 % 4) # = 3 (10 % 2) # = 0
Conditionals
Conditional expressions, involving keywords such as if, elif, and else, provide Python programs with the ability to perform different actions depending on a Boolean condition: True or False.
Conditional Expression
n = 10 print("Greater than 5") if n > 5 else print("smaller than 5") # output: Greater than 5
if, elif, and else
n = 5 if n > 2: print("n is greater than 2") elif n < 2: print("n is smaller than 2") else: print("n = 2") # output: n is greater than 2
Loops
Loops in Python.
For Loops
for loops emphasize over a collection of items, like as list or dict and run a block of code with every element from the collection.
for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: print(i) # Output: 0 1 2 3 4 5 6 7 8 9
Range Function
range function – range is a function that returns a series of numbers under an iterable structure, so it can be utilized in for loops:
for i in range(10): print(i) #output: 0 1 2 3 4 5 6 7 8 9
gives precisely the same outcome as before. Note that 10 isn’t printed as the range function excludes the number entered (known as the last number), range function has 3 parameters:
range(x) # one parameter means last number will be x(excluded) range(x, y) # two parameters means 1st number will be x(included), last number will be y(excluded) range(x, y, z) # three parameters means x will be first number(included), y will be the last number(excluded) and z will be the steps to the next number. for i in range(10, 20): print(i) # Output 10 11 12 13 14 15 16 17 18 19
for i in range(10, 30, 2): print(i) #output: 10 12 14 16 18 20 22 24 26 28
While Loop
A while loop will cause the loop statements to be executed until the loop condition is false. This code will execute the loop statements a sum of 10 times.
i = 0 # assigning value to a variable while i 10: # giving the condition where to terminate the loop print(i) i = i + 2 # giving the condition to increase the value of i after every step
There are more operations of loops, We will comprehend those later, at the present time you need to grasp a lot before plunging into advance level loops.
Dictionary
A dictionary is a collection of a key value store. It permits you to store and recover elements by referring a key. As word references are referred by key, they have very quick lookup.
Key : The ideal key to lookup, Value : The value to set or return.
Creating a Dictionary
d = {'key': 'value'} print(d) #Output {'key': 'value'}
# To create a dictionary and populating it with values stock = {'eggs': 5, 'milk': 10, 'bread': 5} print(stock) #Output {'eggs': 5, 'milk': 10, 'bread': 5}
# To create a dictionary and populating it with values stock = {'eggs': 5, 'milk': 10, 'bread': 5} print(stock) #Output {'eggs': 5, 'milk': 10, 'bread': 5}
Accessing values of dictionary
# To access by elements print(stock['milk']) print(stock['bread']) #Output 10 7 # To access by keys print(stock.keys()) #Output dict_keys(['eggs', 'milk', 'bread']) # To access by values print(stock.values()) #Output dict_values([5, 10, 7])
Merging Dictionaries
To merge dictionaries update() function is used-
# Merging Dictionaries shop = {'stock': 100, 'staff': 2} market = {'shops': 100, 'employees': 200} marketshop = {} marketshop.update(shop) marketshop.update(market) print(marketshop) #Output {'stock': 100, 'staff': 2, 'shops': 100, 'employees': 200}
Iterating over a Dictionary
for i in marketshop: print(i) #Output stock staff shops employees #By default loop works in keys of a dictionary.
To use loop in both keys and values-
for i in marketshop: print(i, marketshop[i]) #Output stock 100 staff 2 shops 100 employees 200
Python List
The Python list is a general data structure generally utilized in python programs. They are both mutable and sequence data type that permits them to be indexed and sliced. The list can contain various kinds of objects , including other list objects.
Working with List
# creating a list a = [10, 20, 30, 40, 50] print(a) #Output [10, 20, 30, 40, 50]
# to add a new element in the list append method is used a.append(60) a.append(70) a.append(80) print(a) #Output [10, 20, 30, 40, 50, 60, 70, 80]
# to append another list b = [90, 100] c = ['Aman', 'Kharwal'] a.append(c) a.append(b) print(a) #Output [10, 20, 30, 40, 50, 60, 70, 80, ['Aman', 'Kharwal'], [90, 100]]
# to add elements of one list to another list a = [10, 20, 30, 40, 50] print(a) b = [60, 70] a.extend(b) print(a) #Output [10, 20, 30, 40, 50, 60, 70]
Insert Function
insert(index, value)- Inserts value just before the specified index. You must know that the index in programming starts from 0 and not 1.
#insert 0 at position 0 a.insert(0, 0) print(a) #Output [0, 10, 20, 30, 40, 50, 60, 70] # insert 15 at position 2 a.insert(2, 15) print(a) #Output [0, 10, 15, 20, 30, 40, 50, 60, 70]
Pop function
pop(index)-It removes the item at index. With no argument it removes the last element of the list.
# removing 2nd element from list a.pop(2) print(a) #Output [0, 10, 15, 20, 30, 40, 50, 60, 70] [0, 10, 20, 30, 40, 50, 60, 70] # removing last element from list a.pop() print(a) #Output [0, 10, 20, 30, 40, 50, 60, 70] [0, 10, 20, 30, 40, 50, 60]
Remove Function
remove(value)- removes the specified value. It do not work on the index, it works on the value.
# remove a.remove(30) print(a) #Output [0, 10, 20, 40, 50, 60]
Reverse Function
reverse()- Reverses the list.
# reverse a.reverse() print(a) #Output [60, 50, 40, 20, 10, 0]
Count Function
count(value)- Counts the number of occurrences of some value in the list.
# count a = ["John", "Aman", "John", 23, "John"] print(a.count("John")) #Output 3
Creating a list with Range function
# range a = list(range(10)) print(a) #Output [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Accessing list values
Python lists are 0-indexed, and act like arrays in other languages
a = [10, 20, 30, 40, 50] print(a[2]) print(a[0]) print(a[-1]) # gives last item #Output 30 10 50
User Input
To get input from the user, we need to use the input function.
a = input("Enter your first name: ") b = input ("Enter your last name: ") print(a, b) #Output Enter your first name: Shakshi Enter your last name: Tripathi Shakshi Tripathi
To add two numbers by taking user input:
a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) print(a + b) #Output Enter first number: 25 Enter second number: 20 45
I used int before the input in light of the fact that to add two integers we need to proclaim the data type or else, it would have joint the two numbers rather than adding, for example:
a = input("Enter first number: ") b = input("Enter second number: ") print(a + b) #Output Enter first number: 25 Enter second number: 20 2520 # as you can see without being declared as int, it took the output as a string and concatenated(joint) the output rather than adding.
To add two floats:
a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) print(a + b) #Output Enter first number: 4.92 Enter second number: 3.65 8.57
Functions
Functions in python give organised, reusable and modular code to perform a set of certain actions. Functions clarify the coding process, prevent unnecessary logic, and make the code more straightforward to follow. This tutorial depicts the declaration and utilization of functions in Python.
Python has many built-in functions like print(), input(), len(). Besides built-ins you can also make your own functions to do more particular jobs – these are known as user-defined functions.
Defining and calling Functions
Using the def statement is the most common way to define a function in python. This statement is a so called clause compound statement with the following syntax:
def functionName(parameters): statement(s)
functionName is known as the recognizer of the function. Since a function definition is an executable assertion its execution binds the function name to the function object which can be called later on utilizing identifier.
statement(s) -also known as function body, are non-empty sequence of statements executed every time the function is called.
Here’s an example of a simple function whose motive is to add two numbers every time when it’s called:
# defining function as add_two and giving x and y as parameters def add_two(x, y): print(x+y) # body assigned to add x and y add_two(2, 4) # calling the function # output 6
Now lets make a function to divide two numbers:
# defining function as divide and giving dividend and divisor as parameters def divide(dividend, divisor): print(dividend/divisor) # body assigned to divide dividend and divisor divide(20, 5) # calling the function #Output 4.0
Now lets define a function as multiply with 4 parameters:
def multiply(a, b, c, d): print(a*b*c*d) multiply(4,7,9,6) #Output 1512
Now lets define a function to print greatest number:
def greatest(x,y,z): if (x>y)and(x>z): print(x,"is greatest") elif (y>x)and (y>z): print(y,"is greatest") else: print(z,"is greatest") greatest(43, 78, 5) #Output 78 is greatest
Tuple
A tuple is an immutable list of values. Tuples are one of Python’s simplest and most common collection types, and can be created with the comma operator(tup = 1, 2, 3, 4)
A tuple is a comma-separated list of values:
tup = 'a','b', 'c','d','e','f' print(tup) #Output ('a', 'b', 'c', 'd', 'e', 'f')
Although not necessary, it is common to close tuples in parentheses:
tup = ('a','b','c','d','e','f) print(tup) #Output ('a', 'b', 'c', 'd', 'e', 'f')
To create a tuple with single value, you have to include a final comma:
tup = 'Book', print(tup) print(type(tup)) #Output ('Book',) class 'tuple'
Tuples are Immutable
One of the main differences between Lists and tuples in python is that tuples are immutable, that is, one cannot add or modify items once the tuple is initialized. for example:
t = (1, 4, 5, 6) #to change value at 0 1st position t[0]= 2 print(t) #Output gives error Traceback (most recent call last): t[0]= 2 TypeError: 'tuple' object does not support item assignment
Similarly, tuples does not have .append and .extend methods as list does.
Classes
Python offers itself not only as a scripting language, yet additionally upholds object oriented programming. Classes depicts data and provide methods to control that data, all encompassed under a single object.
Introduction to Classes
# Creating a class class Person(object): species = "Homo Sapiens" #Class attribute def __init__(self, name): # special method self.name = name def __str__(self): # special method return self.name def rename(self, renamed): # regular method self.name = renamed print("Now My name is {}".format(self.name))
Now lets make few instances of our class
#Instances Aman = Person("Shakshi") Kharwal = Person("Tripathi")
# Attributes print(Shakshi.species) print(Shakshi.name) #Output Homo Sapiens Shakshi
We can execute the methods of the class using the same dot operator:
# Methods print(Shakshi.__str__()) print(Shakshi.rename("Shakshi Tripathi")) #Output Aman Now My name is Shakshi Tripathi
Basic Inheritance
Inheritance in python is depends on comparative ideas utilized in other object oriented languages like java, C++, etc. Another class can be driven from an existing class as follows:
class Rectangle(): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height
The rectangle class can be used as a base class for determining s square class, as square is a special case rectangle:
class square(Rectangle): def __init__(self, side): # call parent constructor, width and height are both sides super(square, self).__init__(side, side) self.side = side
r = Rectangle(3, 4) print(r.area()) #Output 12
s = square(4) print(s.area()) #Output 16
String Methods
Changing the capitalization of a string
Python’s string provides many functions that act on the capitalization of a string. These include:
- str.upper
- str.lower
- str.capitalize
- str.swapcase
str.upper()
str.upper takes every character in a string and converts it into its uppercase equivalent, for example:
print("HackerintheHouse".upper()) #Output HACKERINTHEHOUSE
str.lower()
str.lower does the opposite , it takes every character in a string and converts it to its lowercase equivalent:
a = "HackerintheHouse" print(a.lower()) #Output hackerinthehouse
str.capitalize()
str.capitalize returns a capitalized version of the string, that is , it makes the first character have upper case and the rest lower:
a = "Hacker iN ThE hOuse" print(a.capitalize()) #Output Hacker in the house
str.title()
str.title returns the title cased version of the string, that is every letter in the beginning of a word is made upper case and all others are made lower case:
a = "Hacker iN ThE hOuse" print(a.title()) #Output Hacker In The House
str.swapcase()
str.swapcase() returns a new string object in which all lower case characters are swapped to upper case and all upper case characters to lower:
a = "Hacker iN ThE hOuse" print(a.swapcase()) #Output hACKER In tHe HoUSE
Striping unwanted characters from a string
Three methods are provided that offer the ability to strip leading and trailing from a string:
- str.strip()
- str.rstrip()
- str.lstrip()
str.strip()
str.strip acts on a given string and removes any leading or trailing characters contained in the argument characters, if characters is not supplied or is None, all white space characters are removed by default, for example:
print(" hacker in the house ".strip()) #Output hacker in the house
print(">>> hacker in the house".strip('>')) #Output hacker in the house
str.rstrip() and str.lstrip()
These techniques have comparative semantics and arguments with str.strip(), their difference lies in the direction from which they start.
str.rstrip() starts from the end of the string but str.lstrip() splits from the start of the string.
for example:
print(">>> hacker in the house >>>".rstrip('>')) #Output >>> hacker in the house print(">>> hacker in the house >>>".lstrip('>')) #Output hacker in the house >>>
Tricks of List slicing
Some basic stratagem in python to access list items.
Python lists are 0 listed, and act like arrays in other programming languages.
list1 = list(range(0, 10)) print(list1) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(list1[0]) #0 print(list1[1]) #1
print(list1[-1]) #9 print(list1[-2]) #8 #To display all elements from index 1 print(list1[1:]) #[1, 2, 3, 4, 5, 6, 7, 8, 9] #To display first 3 elements print(list1[:3]) #[0, 1, 2] #To display all elements stepping by 2 print(list1[::2]) #[0, 2, 4, 6, 8] #To display all elements in reverse order print(list1[::-1]) #[9, 8, 7, 6, 5, 4, 3, 2, 1, 0] #To display all elements in reverse order excluding the last item(which is at 0 index in inverse order) print(list1[-1:0:-1]) #[9, 8, 7, 6, 5, 4, 3, 2, 1] #To display elements between index 5 and 8 print(list1[5:8]) #[5, 6, 7] #To display elements between index 1 and 10 print(list1[1:10]) #[1, 2, 3, 4, 5, 6, 7, 8, 9]