About Python
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built-in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy-to-learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms and can be freely distributed.
Data types in Python
There are different types of data types in Python. Some built-in Python data types are
Numeric data types: int, float, complex
String data types: str
Sequence types: list, tuple, range
Mapping data type: dict
Set data types: set, frozenset
Boolean type: bool
Binary types: bytes, bytearray, memoryview
Note:
In Python, we need not declare a datatype while declaring a variable like C or C++. We can simply just assign values in a variable. But if we want to see what type of numerical value is it holding right now, we can use type() function.
Python Numbers
Python numeric data type is used to hold numeric values like, Integers, floating point numbers and complex numbers falls under Python numbers category. They are defined as int, float and complex class in Python.
We can use the type() function to know which class a variable or a value belongs to and the isinstance() function to check if an object belongs to a particular class.
Ex1:
a = 5
print(a, "is of type", type(a))
o/p: 5 is of type <class 'int'>
float: A floating point number is accurate up to 15 decimal places. Integer and floating points are separated by decimal points. 1 is integer, 1.0 is floating point number.
Ex2:
a = 2.0
print(a, "is of type", type(a))
o/p: 2.0 is of type <class 'float'>
complex : Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part.
Ex3:
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
o/p: (1+2j) is complex number? True
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
o/p: (1+2j) is complex number? False
Note : Integers can be of any length, it is only limited by the memory available.
String
The string is a sequence of characters. Python supports Unicode characters. Generally, strings are represented by either single or double-quotes. Multi-line strings can be denoted using triple quotes, ''' or """. Strings are immutable(cannot be changed, they are constant.).
Ex:
a = "string in a double quote"
b= 'string in a single quote'
print(a)
o/p: string in a double quote
print(b)
o/p: string in a single quote
a='GURU'
b="NATH"
# comma (,) is used to concatenate two or more strings.
print(a,b)
o/p: GURU NATH
print(a,"concatenated with",b)
o/p: GURU concatenated with NATH
# '+' is also used to contact the two or more strings
o/p: GURU conconcatenated with NATH
Ex:
s = "This is a string"
print(s)
s = '''Now
it
is
a mul
til
ine'''
print(s)
o/p:
This is a string
Now
it
is
a mul
til
ine
Slicing Operator( []) with String
slicing operator [ ] can be used with string, it is also used with list and tuple.
Ex:
s = '$GOLDEN GATE$'
print("s[4] = ", s[4])
o/p: s[4] = D
print("s[8:12]= ",s[8:12])
o/p: s[8:12]= GATE
print("s[8:11]= ",s[8:11])
o/p: s[8:11]= GAT
print("s[3:12] = ", s[3:12])
o/p: s[3:12] = LDEN GATE
# Strings are immutable in Python
s[5] ='d'
o/p: TypeError: 'str' object does not support item assignment
Raw Strings
A raw string literal is preceded by r or R, which specifies that escape sequences in the associated string are not translated. The backslash character is left in the string.
Ex:
print('foo\nbar')
o/p:
foo
bar
print(r'foo\nbar')
o/p: foo\nbar
print('foo\\bar')
o/p: foo\bar
print(R'foo\\bar')
o/p: foo\\bar
List
The list is a versatile data type exclusive in Python. In a sense, it is the same as the array in C/C++. But it can simultaneously hold different types of data. Formally list is an ordered sequence of some data written using square brackets([]) and commas(,).
Ex:
#list of having only integers
a= [1,2,3,4,5,6]
print(a)
o/p: [1, 2, 3, 4, 5, 6]
#list of having only strings
b=["guru","nammu","suresh"]
print(b)
o/p: ['guru', 'nammu', 'suresh']
#list of having both integers and strings
c= ["nammu","you",1,2.7,"are",3+9j,"good"]
print(c)
o/p: ['nammu', 'you', 1, 2.7, 'are', (3+9j), 'good']
#index are 0 based. this will print a single character
Ex: print(c[1]) #this will print "you" in list c
o/p: you
a[3]=765
o/p: [1, 2, 3, 765, 5, 6]
Tuple
The tuple is another data type which is a sequence of data similar to a list. But it is immutable. That means data in a tuple is write-protected. Data in a tuple is written using parenthesis and commas. Its index starts with zero(0).
#tuple having only integer type of data.
a=(1,2,3,4)
print(a)
o/p: (1, 2, 3, 4)
#tuple having multiple type of data.
b=("hello", 1,2,3,"go")
print(b)
o/p: ('hello', 1, 2, 3, 'go')
print(b[4])
o/p: go
Dictionary
Python Dictionary is an unordered sequence of data of key-value pair form. It is similar to the hash table type. Dictionaries are written within curly braces in the form key: value. It is very useful to retrieve data in an optimized way among a large amount of data. Key and value can be of any type.
Ex:
#a sample dictionary variable
a = {1:"first name",2:"last name", "age":33}
#print value having key=1
print(a[1])
o/p: first name
#print value having key=2
print(a[2])
o/p: last name
#print value having key="age"
print(a["age"])
o/p: 19
Ex2:
d = {1:'value','key':2}
type(d)
o/p: <class 'dict'>
print(d)
o/p: {1: 'value', 'key': 2}
print("d[1] = ", d[1]);
o/p: d[1] = value
print("d['key'] = ",d['key']);
o/p: d['key'] = 2
# Generates error
print("d[2] = ", d[2]);
o/p: KeyError: 2
Range
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
Syntax:
range(start, stop, step)
Parameter Description
start Optional. An integer number specifying at which position to start. Default is 0
stop Required. An integer number specifying at which position to stop (not included).
step Optional. An integer number specifying the incrementation. Default is 1
Ex1:
Create a sequence of numbers from 0 to 5, and print each item in the sequence:
x = range(6)
for n in x:
print(n)
o/p:
0
1
2
3
4
5
Ex2:
Create a sequence of numbers from 3 to 5, and print each item in the sequence:
x = range(3, 6)
for n in x:
print(n)
o/p:
3
4
5
Ex3:
Create a sequence of numbers from 3 to 19, but increment by 2 instead of 1:
x = range(3, 20, 2)
for n in x:
print(n)
o/p:
3
5
7
9
11
13
15
17
19
Set
Set is an unordered collection of unique items. Set is defined by values separated by a comma inside braces { }. Items in a set are not ordered. We can perform set operations like union, intersection on two sets. Set has unique values. They eliminate duplicates. In set we cannot use []. Since set are unordered collections, indexing has no meaning. Hence the slicing operator [] does not work.
Ex:
a = {5,2,3,1,4}
b={34,66,8,99,4,33,34,99}
print("a = ", a)
print(type(a))
o/p:
a = {1, 2, 3, 4, 5}
<class 'set'>
print("b = ", b)
print(type(b))
o/p:
b = {33, 34, 99, 4, 66, 8}
<class 'set'>
Ex: Eliminating duplicate values
a = {1,2,2,3,3,3}
print(a)
o/p: {1, 2, 3}
Ex: slicing operator [] does not work.
print(a[1])
o/p: TypeError: 'set' object is not subscriptable
Boolean
Expressions in Python are often evaluated in a Boolean context, meaning they are interpreted to represent truth or falsehood. A value that is true in Boolean context is sometimes said to be “truthy,” and one that is false in Boolean context is said to be “falsy.”
Ex:
print(type(True))
o/p: <class 'bool'>
print(type(False))
o/p: <class 'bool'>
Built-In Functions
The Python interpreter supports many functions that are built-in: sixty-eight, as of Python 3.6.
Math
Function Description
abs() Returns absolute value of a number
divmod() Returns quotient and remainder of integer division
max() Returns the largest of the given arguments or items in an iterable
min() Returns the smallest of the given arguments or items in an iterable
pow() Raises a number to a power
round() Rounds a floating-point value
sum() Sums the items of an iterable
Type Conversion
Function Description
ascii() Returns a string containing a printable representation of an object
bin() Converts an integer to a binary string
bool() Converts an argument to a Boolean value
chr() Returns string representation of character given by integer argument
complex() Returns a complex number constructed from arguments
float() Returns a floating-point object constructed from a number or string
hex() Converts an integer to a hexadecimal string
int() Returns an integer object constructed from a number or string
oct() Converts an integer to an octal string
ord() Returns integer representation of a character
repr() Returns a string containing a printable representation of an object
str() Returns a string version of an object
type() Returns the type of an object or creates a new type object
Input/Output
Function Description
format() Converts a value to a formatted representation
input() Reads input from the console
open() Opens a file and returns a file object
print() Prints to a text stream or the console
No comments:
Post a Comment