Basics of Python Programming
Basics of Python Programming
Basics of Python Programming
Python Programming
What is Python?
● Python is a popular programming language.
● Its implementation was started in December 1989 by Guido van
Rossum, and released in 1991.
● It is used for:
– web development (server-side),
– software development,
– mathematics,
– system scripting.
Python
● Python is Interpreted: Python is processed at runtime by the interpreter.
You do not need to compile your program before executing it. This is similar
to PERL and PHP.
● Python is Interactive: You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
● Python is Object-Oriented: Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
● Python is a Beginner's Language: Python is a great language for the
beginner-level programmers and supports the development of a wide range
of applications from simple text processing to WWW browsers to games.
Note
● The most recent major version of Python is Python 3, which we
shall be using. However, Python 2, although not being updated
with anything other than security updates, is still quite popular.
● Python program can be written in a text editor. It is possible to
write Python in an Integrated Development Environment, such
as Thonny, Pycharm, Netbeans or Eclipse which are particularly
useful when managing larger collections of Python files.
Naming conventions for Python identifiers
● Class names start with an uppercase letter. All other identifiers
start with a lowercase letter.
● Starting an identifier with a single leading underscore indicates
that the identifier is private.
● Starting an identifier with two leading underscores indicates a
strong private identifier.
● If the identifier also ends with two trailing underscores, the
identifier is a language-defined special name.
Python Variables
● Variables are containers for storing data values.
● Unlike other programming languages, Python has no command for declaring
a variable.
● A variable is created the moment you first assign a value to it.
● A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).
● Rules for Python variables:
– A variable name must start with a letter or the underscore character
– A variable name cannot start with a number
– A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
– Variable names are case-sensitive (age, Age and AGE are three different variables)
Reserved Words
Input and output in Python
● print ("Hello World")
● print(x)
● print(x, end=" ")
● x=input('Enter value of X:')
Lines and Indentation
● Quotation in Python: Python accepts single ('), double (") and
triple (''' or """) quotes to denote string literals.
● Comments in Python: hash sign (#)
● Multiple Statements on a Single Line: The semicolon ( ; )
allows multiple statements on a single line.
● Multiple Statement Groups as Suites: Groups of individual
statements, which make a single code block are called suites in
Python, and starts with a header line.
● Assigning Values to Variables: Python variables do not need
explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable.
● Multiple Assignment: Python allows you to assign a single
value to several variables simultaneously. e.g.,
a=b=c=1 “OR”
a, b, c = 1, 2, "john"
Standard Data Types
● Python has five standard data types-
– Text Type: str
– Numeric Types: int, float, complex
– Sequence Types: list, tuple
– Mapping Type: dictionary
– Set Types: set, frozenset
Text Type: Python Strings
● Strings in Python are identified as a contiguous set of characters represented
in the quotation marks.
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
Numeric Types: Python Numbers
● Number data types store numeric values.
● Number objects are created when you assign a value to them.
● Python supports three different numerical types:
1. int (signed integers)
2. float (floating point real values)
3. complex (complex numbers)
Python Lists
● A list contains items separated by commas and enclosed within
square brackets ([ ]).
● To some extent, lists are similar to arrays in C.
● One of the differences between them is that all the items
belonging to a list can be of different data type.
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
Python Tuples
● A tuple is another sequence data type that is similar to the list.
● A tuple consists of a number of values separated by commas.
● Unlike lists, however, tuples are enclosed within parenthesis.
● The main difference between lists and tuples is- Lists are
enclosed in brackets ( [ ] ) and their elements and size can be
changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated.
● Tuples can be thought of as read-only lists.
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2)
tinytuple = (123, 'john')
print (tuple) # Prints complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints tuple two times
print (tuple + tinytuple) # Prints concatenated tuple
Python Dictionary
● Python's dictionaries are kind of hash-table type.
● They work like associative arrays or hashes and consist of key-
value pairs.
● A dictionary key can be almost any Python type, but are usually
numbers or strings.
● Values, on the other hand, can be any arbitrary Python object.
● Dictionaries are enclosed by curly braces ({ }) and values can
be assigned and accessed using square braces ([ ]).
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values
● del dict['Name'] # remove entry with key 'Name'
● dict.clear() # remove all entries in dict
● del dict # delete entire dictionary
Set
● A Set is an unordered collection data type that is iterable,
mutable, and has no duplicate elements.
● Python’s set class represents the mathematical notion of a set.
● The major advantage of using a set, as opposed to a list, is
that it has a highly optimized method for checking whether a
specific element is contained in the set.
● This is based on a data structure known as a hash table.
– normal_set = set(["a", "b","c"])
– # Same as {"a", "b","c"}
Frozen Sets
● Frozen set is just an immutable version of a Python set object.
While elements of a set can be modified at any time, elements
of frozen set remains the same after creation.
– frozen_set = frozenset(["e", "f", "g"])
● For example, to import the function fibonacci from the module fib, use the following
statement-
def fib(n):
result = [ ]
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
●
>>> from fib import fib
●
>>> fib(100)
●
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Packages in Python
● A package is a hierarchical file directory structure that defines a
single Python application environment that consists of modules
and subpackages and sub-subpackages, and so on.