Python Introduction
Why should you learn python
• Easiest programming language to start with
• Operates at a higher abstraction level
• Syntax rules are very simple
• Takes one-fifth development time compared to C programming language
• Python is expressive, giving commands is simpler
• Python is more readable than other languages
• Python is cross-platform
• Python is complete
• Python is free
Downsides of Python
• Python isn’t the fastest programming language
• Python doesn’t have the most libraries
• Python doesn’t check variable types at compile time
• Python doesn’t have much mobile support
• Python doesn’t use multiple processors well
Python Applications
• Python can make games
• Python has a wide range of libraries such as numeric processing,
image manipulation, user interfaces and web scripting
Programming Environment for
Python
1. Python 3.?? (Direct install has IDLE as python program writing
application, otherwise known as Integrated Development
environment)
2. Anaconda 3 (has Spyder (a more advanced IDE), and other
advanced libraries for data processing)
Simplest program
• Print(“Hello World!”)
• Prints “Hello World!” in a console window
Python – Built-in Data types
What is a data type?
- Computers save every information/data in memory
- There is a certain method of storing different types of data
- To differentiate the type of data, like text, number, decimal point
number/fraction, Datatypes are defined in every programming
language to assist the programmer.
- Efficient use of Datatypes results in error free code with good
execution results and time.
Different Data Types in Python
1. Numbers
2. Lists
3. Tuples
4. Strings
5. Dictionaries
6. Sets
7. File Objects
DataTypes - Numbers
Python can store:
1. Integers 0,1,2,3, …… -3,-2,-1,0…. ,8888888888,
777777777
2. Floats 3.0, 31e12, -6e-4,
3. Complex Numbers 3+2j, -4-2j, 4.2 + 6.3j
4. Booleans True, False
You can manipulate numbers by using the arithmetic operators: +, -,
*, /, **, %
Lists
• Python has a powerful built-in list data type:
[]
[1]
[1, 2, 3, 4, 5, 6, 7, 8, 12]
[1, "two", 3, 4.0, ["a", "b"], (5,6)]
• A list can contain a mixture of other types as its elements, including
strings, tuples, lists, dictionaries, functions, file objects, and any type
of number
Lists
• Programmers can use list built-in functions to alter or get information
about the list, such as
1. Len: Tells the length of the list
2. append: adds an element at the end of list
3. Count: tells about number of specific element in a list
List can be declared as:
Thislist = list((1,2,3,4,5))
Print(Thislist)
Tuples
• Tuples are same as lists, but they cannot be changed once they are
created
• The operators (in, + and *) and built in functions (len,max and min)
operate on them the same way but they do not modify the original
• A tuple, like the list can contain mixture of data type
• X = (1,2,3,4,5)
• A list can be converted to tuple:
tuple(X)
Strings
• String processing is one of Python’s strengths.
• There are many options for delimiting strings
• A string in double quotes can contain 'single quote' characters."
• 'A string in single quotes can contain "double quote" characters.'
• '''\tA string which starts with a tab; ends with a newline character.\n'''
• """This is a triple double quoted string, the only kind that can
• contain real newlines."""
Strings
• Strings once defined cannot be changed, they are immutable
• The operators and functions that work with them return new strings derived from the
original
>>> x = "live and let \t \tlive"
>>> x.split()
['live', 'and', 'let', 'live']
>>> x.replace(" let \t \tlive", "enjoy life")
'live and enjoy life'
>>> import re 1
>>> regexpr = re.compile(r"[\t ]+")
>>> regexpr.sub(" ", x)
'live and let live'
Dictionaries
• Dictionary provides way to store key, value pairs
• Dictionary has its own methods such as del, clear, copy, get, items, keys, update and values):
>>> x = {1: "one", 2: "two"}
>>> x["first"] = "one" 1
>>> x[("Delorme", "Ryan", 1995)] = (1, 2, 3) 2
>>> list(x.keys())
['first', 2, 1, ('Delorme', 'Ryan', 1995)]
>>> x[1]
'one'
>>> x.get(1, "not available")
'one'
>>> x.get(4, "not available") 3
'not available'
Sets
• A set in python is an unordered collection of objects, used where membership and
uniqueness are the main things you need to know about objects
• Sets behave as collections of dictionary keys without any associated values:
>>> x = set([1, 2, 3, 1, 3, 5]) 1
>>> x
{1, 2, 3, 5} 2
>>> 1 in x 3
True
>>> 4 in x 3
False
>>>
File Objects
• A file is accessed through a python file object:]
• File object helps writing or reading from a saved or new file
• Programmer can save output of a program in a text file
Control Flow Structures
• Python has a full range of structures to control code execution and
program flow, including common branching and looping structures
Boolean values and Expressions:
- Boolean values are either True or False.
- Values such as False, 0, None, “ “, [] are all taken as False
- Comparison expressions can be made by using the comparison
operators (<, <=, ==, >, >=, !=, is, is not, in, not in) and the logical
operators (and, not, or) which all return True or False
Comparison Expressions
True or False!
x=5
x>6 ;?
X<6 ;?
x == 5 ;
Comparison Expressions
True or False!
x=5
x >= 6 ;?
X =< 6 ;?
x >= 5 ;
The If-elif-else Statement
• x = 5
• if x >= 5:
• y = -1
• elif x < 5:
• y = 1
• else:
• y = 0
• print(x, y)
• The block of code after first True condition (of an if or an elif) is executed.
• If none of the statements is True, then block of code after else is executed
The If-elif-else Statement
• print("Enter your age:")
• age = int(input())
• print('You are ' + str(age) + 'years old!')
•
if age>=18:
• print("You are eligible for drivers license")
• elif age>=60:
• print("You are too old for driver's license")
• else:
• print("You are too young for driver's license")
While Loop
• The while loop is executed as long as the condition (which could be x
> y) is True
# Comments are good for programmers to understand the code
x = 0 # this is a counter variable
while(x<101):
print('Current value of counter is ' + str(x))
x = x +1 # counts upto hundred (100)
For Loop
# This programs checks for even and odd numbers
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in list:
if i % 2 == 0:
print(i, "is an even number")
else:
print(i, "is an odd number")
Functions
• Functions are defined with keyword def
• Must end with “:”
• Function declaration must contain input variables in brackets
• Example: def square(x):
• return x * x
• Example: def exp_power(x,n):
• return x**n
functions
• Functions are later called with their names
• Examples:
print(square(2)) # Prints resulting value of square
print(cube(2)) # Prints resulting value of cube
print(exp_power(2,3)) # Prints resulting value of Exponential
Power