Escolar Documentos
Profissional Documentos
Cultura Documentos
Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
n
Python Babjee
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties
Python 1.0 was released in November 1994. In 2000, Python 2.0 was released.
Python 2.7.11 is the latest edition of Python 2
n
Python Babjee
Python Features
Easy-to-learn: Python has few keywords, simple structure, and a clearly defined
Syntax
Easy-to-read: Python code is more clearly defined and visible to the eyes.
A broad standard library: Python's bulk of the library is very portable and crossplatform
compatible on UNIX, Windows, and Macintosh
Interactive Mode: Python has support for an interactive mode, which allows
interactive testing and debugging of snippets of code
Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
$python # Unix/Linux
or
python% # Unix/Linux
or
C:>python # Windows/DOS
C:>python script.py
n
Python Babjee
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object.
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
n
Python Babjee
Reserved words
reserved words cannot use them as constants or variables or any other identifier names
n
Python Babjee
Lines and Indentation
Python does not use braces({}) to indicate blocks of code for class and function definitions
or flow control. Blocks of code are denoted by line indentation
n
Python Babjee
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals
The triple quotes are used to span the string across multiple lines
Comments in Python
A hash sign (#) that is not inside a string literal is the beginning of a comment
# First comment
print ("Hello, Python!") # second comment
n
Python Babjee
Command Line Arguments
Many programs can be run to provide you with some basic information about how they
should be run.
The Python sys module provides access to any command-line arguments via
the sys.argv. This serves two purposes-
n
Python Babjee
Example
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))
Output
n
Python Babjee
Python 3 – Variable
Variables are nothing but reserved memory locations to store values. It means that when
you create a variable, you reserve some space in the memory
n
Python Babjee
Multiple Assignment
Example
a= b = c = 1
Here, an integer object is created with the value 1, and all the three variables are assigned
to the same memory location
Example
a,b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to the variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.
n
Python Babjee
Standard Data Types
Python Numbers
Number data types store numeric values. Number objects are created when you assign a
value to them.
For example
var1= 1
var2 = 10
n
Python Babjee
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation Marks
n
Python Babjee
Python Lists
A list contains items separated by commas and enclosed within square
brackets ([]). To some extent, lists are similar to arrays in C.
n
Python Babjee
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. Tuples are read-only lists
n
Python Babjee
Python Dictionary
Python's dictionaries are kind of hash-table type. They consit of key-value pairs
n
Python Babjee
Python 3 – Basic Operators
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
n
Python Babjee
n
Python Babjee
Decision-making
Decision-making is the anticipation of conditions occurring during the execution of a
program and specified actions taken according to the conditions.
n
Python Babjee
If Statement
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed
n
Python Babjee
IF...ELIF...ELSE Statements
An else statement can be combined with an if statement. An else statement contains a
block of code that executes if the conditional expression in the if statement resolves to 0
or a FALSE value
n
Python Babjee
The elif Statement
The elif statement allows you to check multiple expressions for TRUE and execute a block
of code as soon as one of the conditions evaluates to TRUE
n
Python Babjee
Nested IF Statements
There may be a situation when you want to check for another condition after a condition
resolves to true.
n
Python Babjee
Loop
A loop statement allows us to execute a statement or group of statements multiple times
n
Python Babjee
while loop
n
Python Babjee
for Loop Statements
n
Python Babjee
n
Python Babjee
Example
for i in range(1,11):
for j in range(1,11):
k=i*j
print (k, end=' ')
print()
n
Python Babjee
continue Statement
The continue statement in Python returns the control to the beginning of the current loop
pass Statement
It is used when a statement is required syntactically but you do not want any command
or code to execute
n
Python Babjee
Mathematical Functions
n
Python Babjee
n
Python Babjee
n
Python Babjee
Python string
Strings are amongst the most popular types in Python. We can create them simply by
enclosing characters in quotes. Python treats single quotes the same as double quotes
Accessing Strings
Updating Strings
n
Python Babjee
String Special Operators
n
Python Babjee
String capitalize() Method
n
Python Babjee
String find() Method
n
Python Babjee
String isnumeric() Method
#!/usr/bin/python3
str = "this2016"
print (str.isnumeric())
str = "23443434“
print (str.isnumeric())
n
Python Babjee
String join() Method
s = "-"
seq = ("a", "b", "c“)
print (s.join( seq ))
n
Python Babjee
String replace() Method
n
Python Babjee
Date & Time
>>>import time
>>> print (time.localtime())
Formated date
localtime = time.asctime( time.localtime(time.time()) )
print ("Local current time :", localtime)
import calendar
cal = calendar.month(2018, 6)
print ("Here is the calendar:")
print (cal)
n
Python Babjee
The time Module
import time
t = time.localtime()
print ("asctime : ",time.asctime(t))
import time
print ("ctime : ", time.ctime())
import time
print ("time.localtime() :" , time.localtime())
n
Python Babjee
Function
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of
code reusing
n
Python Babjee
def changeme( mylist ):
print ("Values inside the function before change: ", mylist)
mylist[2]=50
print ("Values inside the function after change: ", mylist)
return
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
n
Python Babjee
Function Arguments
You can call a function by using the following types of formal arguments-
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Required arguments
n
Python Babjee
Keyword Arguments
n
Python Babjee
Default Arguments
n
Python Babjee
The return Statement
The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return None.
n
Python Babjee
Python anonymous function
example
double = lambda x: x * 2
Print(double(5))
x = lambda a : a + 10
print(x(5))
n
Python Babjee
A lambda function with multiple aurguments:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
mydoubler = myfunc(2)
print(mydoubler(11))
n
Python Babjee
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
n
Python Babjee
the most basic usage is to insert values into a string with the %s placeholder
insert values into a string with the %s placeholder
class MyClass:
var1=10
n
Python Babjee
Class with Function
class MyClass:
var1="Test"
def MyFunction(self):
print("inside function")
obj =MyClass()
obj.MyFunction()
n
Python Babjee
if we were to define another object with the "MyClass" class and then change the string
in the variable above:
n
Python Babjee
class Vehicle:
name = ""
kind = "car"
color = ""
value = 100.00
def description(self):
desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)
return desc_str
car1 = Vehicle()
car1.name = "Fer"
car1.color = "red"
car1.kind = "convertible"
car1.value = 60000.00
car2 = Vehicle()
car2.name = "Jump"
car2.color = "blue"
car2.kind = "van"
car2.value = 10000.00
print(car1.description())
print(car2.description())
n
Python Babjee
Sub Classes
class parentClass:
var1="i am var1"
var2="i am var2"
class childClass(parentClass):
pass
childobj =childClass()
print("value of var1",childobj.var1)
print("value of var2",childobj.var2)
n
Python Babjee
A constructor in python is a block of code similar to a method that's
called when an instance of an object is created
class MyClass:
def MyFunction(self):
print("hellow")
myObj =MyClass()
myObj.MyFunction()
class MyClass:
def __init__(self):
print("This is Constractor")
print("This also Print")
myObj =MyClass()
n
Python Babjee
What is a Module?
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
def MyFunction():
print("My Function")
import mymodule
mymodule.MyFunction()
n
Python Babjee
Files I/O
>>> x=input("something:")
something:10
>>> x
Inport os
os.mkdir("test")
n
Python Babjee
n
Python Babjee
n
Python Babjee
Reading and Writing Files
fo = open("foo.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")
fo.close()
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print ("Read String is : ", str)
# Close opened file
fo.close()
n
Python Babjee
The rename() Method
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
import os
# Delete file test2.txt
os.remove("text2.txt")
n
Python Babjee
NumPy
NumPy is the fundamental package for scientific computing with Python
it provides a high performance multidimensional array object,and tools working with these array
n
Python Babjee