Introduction To Python
Introduction To Python
Introduction To Python
PYTHON
Introduction
Introduction
• Python is an easy to learn, powerful programming language. It
has efficient high-level data structures and a simple but
effective approach to object-oriented programming.
• Python’s elegant syntax and dynamic typing, together with its
interpreted nature, make it an ideal language for scripting and
rapid application development in many areas on most
platforms.
• The Python interpreter and the extensive standard library are
freely available in source or binary form for all major
platforms from the Python Web site,
https://www.python.org/, and may be freely distributed.
• The Python interpreter is easily extended with new functions
and data types implemented in C or C++ (or other languages
callable from C).
What is Python (Programming)? - The Basics
• Create a constant.py
PI = 3.14
GRAVITY = 9.8
• Create a main.py
import constant
print(constant.PI)
print(constant.GRAVITY)
• When you run the program, the output will be:
3.14
9.8
• Note: In reality, we don't use constants in Python. The globals or
constants module is used throughout the Python programs.
Rules and Naming convention for variables
and constants
• Create a name that makes sense. Suppose, vowel makes more sense
than v.
• Use camelCase notation to declare a variable. It starts with lowercase
letter. For example:
myName myAge myAddress
• Use capital letters where possible to declare a constant. For example:
PI G MASS TEMP
• Never use special symbols like !, @, #, $, %, etc.
• Don't start name with a digit.
• Constants are put into Python modules and meant not be changed.
• Constant and variable names should have combination of letters in
lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore
(_). For example:
snake_case MACRO_CASE camelCase CapWords
Literals
• Literal is a raw data given in a variable or constant. In Python, there are
various types of literals they are as follows:
• Numeric Literals
• Numeric Literals are immutable (unchangeable). Numeric literals can
belong to 3 different numerical types Integer, Float and Complex.
• For e.g.
a = 0b1010 #Binary Literals
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal
#Float Literal
float_1 = 10.5
float_2 = 1.5e2
#Complex Literal
x = 3.14j
print(a, b, c, d)
print(float_1, float_2)
print(x, x.imag, x.real)
def menu(x):
if x == drink:
print(drink)
else:
print(food)
menu(drink)
menu(food)
• When you run the program, the output will be:
Available
None
Literal Collections
• There are four different literal collections List literals, Tuple
literals, Dict literals, and Set literals.
• Example: How to use literals collections in Python?
fruits = ["apple", "mango", "orange"] #list
numbers = (1, 2, 3) #tuple
alphabets = {'a':'apple', 'b':'ball', 'c':'cat'} #dictionary
vowels = {'a', 'e', 'i' , 'o', 'u'} #set
print(fruits)
print(numbers)
print(alphabets)
print(vowels)
• When you run the program, the output will be:
• ['apple', 'mango', 'orange']
• (1, 2, 3)
• {'a': 'apple', 'b': 'ball', 'c': 'cat'}
• {'e', 'a', 'o', 'i', 'u'}
• In the above program, we created a list of fruits, tuple
of numbers, dictionary dict having values with keys
designated to each value and set of vowels.
Python Data Types
Data types in Python
• Every value in Python has a datatype. Since everything is an
object in Python programming, data types are actually classes
and variables are instance (object) of these classes.
• There are various data types in Python. Some of the
important types are listed below.
Python Numbers
• 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.
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
• Integers can be of any length, it is only limited by the memory
available.
• 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.
• Complex numbers are written in the form, x + yj, where x is the
real part and y is the imaginary part. Here are some examples.
• >>> a = 1234567890123456789
• >>> a 1234567890123456789
• >>> b = 0.1234567890123456789
• >>> b 0.12345678901234568
• >>> c = 1+2j
• >>> c (1+2j)
Boolean
• Data with one of two built-in values True or False.
• Notice that 'T' and 'F' are capital. true and false are not valid
booleans and Python will throw an error for them.
Sequence Type
• A sequence is an ordered collection of similar or different data
types. Python has the following built-in sequence data types:
• String: A string value is a collection of one or more characters
put in single, double or triple quotes.
• List : A list object is an ordered collection of one or more data
items, not necessarily of the same type, put in square
brackets.
• Tuple: A Tuple object is an ordered collection of one or more
data items, not necessarily of the same type, put in
parentheses.
Python List
• List is an ordered sequence of items. It is one of the most used
datatype in Python and is very flexible. All the items in a list do not
need to be of the same type.
• Declaring a list is pretty straight forward. Items separated by
commas are enclosed within brackets [ ].
• >>> a = [1, 2.2, 'python']
• We can use the slicing operator [ ] to extract an item or a range of
items from a list. Index starts form 0 in Python.
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])
# a[0:3] = [5, 10, 15]
print("a[0:3] = ", a[0:3])
# a[5:] = [30, 35, 40]
print("a[5:] = ", a[5:])
• Lists are mutable, meaning, value of elements of a list can be
altered.
>>> a = [1,2,3]
>>> a[2]=4
>>> a [1, 2, 4]
Python Tuple
• Tuple is an ordered sequence of items same as list. The only
difference is that tuples are immutable. Tuples once created
cannot be modified.
• Tuples are used to write-protect data and are usually faster
than list as it cannot change dynamically.
• It is defined within parentheses () where items are separated
by commas.
• >>> t = (5,'program', 1+3j)
t = (5,'program', 1+3j)
# t[1] = 'program‘
print("t[1] = ", t[1])
# t[0:3] = (5, 'program', (1+3j))
print("t[0:3] = ", t[0:3])
# Generates error
# Tuples are immutable
t[0] = 10
Python Strings
• String is sequence of Unicode characters. We can use single quotes
or double quotes to represent strings. Multi-line strings can be
denoted using triple quotes, ''' or """.
• >>> s = "This is a string"
• >>> s = '''a multiline
• Like list and tuple, slicing operator [ ] can be used with string.
Strings are immutable.
s = 'Hello world!‘
# s[4] = 'o‘
print("s[4] = ", s[4])
# s[6:11] = 'world‘
print("s[6:11] = ", s[6:11])
# Generates error
# Strings are immutable in Python
s[5] ='d'
Python Set
• Set is an unordered collection of unique items. Set is defined
by values separated by comma inside braces { }. Items in a set
are not ordered.
a = {5,2,3,1,4}
# printing set variable
print("a = ", a)
# data type of variable a
print(type(a))
• We can perform set operations like union, intersection on two
sets. Set have unique values. They eliminate duplicates.
• >>> a = {1,2,2,3,3,3}
• >>> a {1, 2, 3}
• Since, set are unordered collection, indexing has no meaning.
Hence the slicing operator [] does not work.
• >>> a = {1,2,3}
• >>> a[1]
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
TypeError: 'set' object does not support indexing
Python Dictionary
• Dictionary is an unordered collection of key-value pairs.
• It is generally used when we have a huge amount of data.
Dictionaries are optimized for retrieving data. We must know
the key to retrieve the value.
• In Python, dictionaries are defined within braces {} with each
item being a pair in the form key:value. Key and value can be
of any type.
• >>> d = {1:'value','key':2}
• >>> type(d)
• <class 'dict'>
• We use key to retrieve the respective value. But not the other
way around.
d = {1:'value','key':2}
print(type(d))
print("d[1] = ", d[1]);
print("d['key'] = ", d['key']);
# Generates error
print("d[2] = ", d[2]);
Conversion between data types
• We can convert between different data types by using different type conversion
functions like int(), float(), str() etc.
• >>> float(5)
• 5.0
• Conversion from float to int will truncate the value (make it closer to zero).
• >>> int(10.6) 10
• >>> int(-10.6) -10
• Conversion to and from string must contain compatible values.
>>> float('2.5')
2.5
>>> str(25)
'25'
>>> int('1p')
Taceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1p'
• We can even convert one sequence to another.
>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
• To convert to dictionary, each element must be a pair
>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}
Python Type Conversion and Type Casting
• Type Conversion:
• The process of converting the value of one data type (integer,
string, float, etc.) to another data type is called type
conversion. Python has two types of type conversion.
• Implicit Type Conversion
• Explicit Type Conversion
Implicit Type Conversion:
• In Implicit type conversion, Python automatically converts one data
type to another data type. This process doesn't need any user
involvement.
• Let's see an example where Python promotes conversion of lower
datatype (integer) to higher data type (float) to avoid data loss.
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)`
print("datatype of num_new:",type(num_new))
• When we run the above program, the output will be
datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>
• In the above program,
• We add two variables num_int and num_flo, storing the value
in num_new.
• We will look at the data type of all three objects respectively.
• In the output we can see the datatype of num_int is an integer,
datatype of num_flo is a float.
• Also, we can see the num_new has float data type because Python
always converts smaller data type to larger data type to avoid the
loss of data.
Example: Addition of string(higher) data
type and integer(lower) datatype
num_int = 123
num_str = "456“
print("Data type of num_int:",type(num_int))
print("Data type of num_str:",type(num_str))
print(num_int+num_str)
• When we run the above program, the output will be
Data type of num_int: <class 'int'>
Data type of num_str: <class 'str'>
Traceback (most recent call last):
File "python", line 7, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
• In the above program,
• We add two variable num_int and num_str.
• As we can see from the output, we got typeerror. Python is
not able use Implicit Conversion in such condition.
• However Python has the solution for this type of situation
which is know as Explicit Conversion.
Explicit Type Conversion:
• In Explicit Type Conversion, users convert the data type of an
object to required data type. We use the predefined functions
like int(), float(), str(), etc to perform explicit type conversion.
• This type conversion is also called typecasting because the
user casts (change) the data type of the objects.
• Syntax :
• (required_datatype)(expression)
• Typecasting can be done by assigning the required data type
function to the expression.
Example: Addition of string and integer
using explicit conversion
num_int = 123
num_str = "456“
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))