Você está na página 1de 67

Python is a high-level, interpreted, interactive and object-oriented scripting language

Python is Interpreted: Python is processed at runtime by the interpreter. You do


not need to compile your program before executing it.

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

Python is a Beginner's Language: Python is a great language for the beginnerlevel


programmers and supports the development of a wide range of applications from simple text
processing to WWW browsers to games.

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

Python 3.0 was released in 2008. Python 3 is not backward compatible


with 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.

Databases: Python provides interfaces to all major commercial databases.


n
Python Babjee
Example
print ("Hello, Python!")

$python # Unix/Linux
or
python% # Unix/Linux
or
C:>python # Windows/DOS

Script Mode execution

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.

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

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-

sys.argv is the list of command-line arguments.

len(sys.argv) is the number of command-line arguments

n
Python Babjee
Example
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))

Running script file


python test.py arg1 arg2 arg3

Output

Number of arguments: 4 arguments.


Argument List: ['test.py', 'arg1', 'arg2', 'arg3']

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 has five standard data types-


Numbers
String
List
Tuple
Dictionary

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

While with else statement

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

String center() Method

str = "this is string example....wow!!!“

print ("str.center(40, 'a') : ", str.center(40, 'a'))

String count() Method

str="this is string example....wow!!!"


sub='i'
print ("str.count('i') : ", str.count(sub))

n
Python Babjee
String find() Method

str1 = "this is string example....wow!!!"


str2 = "exam";
print (str1.find(str2))
print (str1.find(str2, 10))
print (str1.find(str2, 40))

String islower() Method

str = "THIS is string example....wow!!!"


print (str.islower())
str = "this is string example....wow!!!"
print (str.islower())

n
Python Babjee
String isnumeric() Method

#!/usr/bin/python3
str = "this2016"
print (str.isnumeric())
str = "23443434“
print (str.isnumeric())

String isupper() Method

str = "THIS IS STRING EXAMPLE....WOW!!!"


print (str.isupper())
str = "THIS is string example....wow!!!"
print (str.isupper())

n
Python Babjee
String join() Method

s = "-"
seq = ("a", "b", "c“)
print (s.join( seq ))

String len() Method

str = "this is string example....wow!!!"


print ("Length of the string: ", len(str))

String lower() Method

str = "THIS IS STRING EXAMPLE....WOW!!!"


print (str.lower())

n
Python Babjee
String replace() Method

str = "this is string example....wow!!! this is really string"


print (str.replace("is", "was"))

String title() Method

str = "this is string example....wow!!!"


print (str.title())

String upper() Method

str = "this is string example....wow!!!"


print ("str.upper : ",str.upper())

n
Python Babjee
Date & Time

>>>import time
>>> print (time.localtime())

Formated date
localtime = time.asctime( time.localtime(time.time()) )
print ("Local current time :", localtime)

Getting calendar for a month

import calendar
cal = calendar.month(2018, 6)
print ("Here is the calendar:")
print (cal)
n
Python Babjee
The time Module

Time asctime() Method

import time
t = time.localtime()
print ("asctime : ",time.asctime(t))

Time ctime() Method

import time
print ("ctime : ", time.ctime())

Time localtime() Method

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

def functionname( parameters ):


"function_docstring"
function_suite
return [expression]

def printme( str ):


print (str)
return
printme("This is first call to the user defined function!")
printme("Again second call to the same function")

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

Note that the order of parameters does not matter.

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

In Python, anonymous function is a function that is defined without a name.


While normal functions are defined using the def keyword,
in Python anonymous functions are defined using the lambda keyword.
Hence, anonymous functions are also called lambda functions.
Use lambda functions when an anonymous function is required for a short period of time.

lambda arguments: expression

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))

Lambda function inside user defind function


def myfunc(n):
return lambda a : a * n

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

>>> uid = "sa"


>>> pwd = "secret“
>>> print pwd + " is not a good password for " + uid

>>>print "%s is not a good password for %s" % (pwd, uid)

print "Today's stock price: %f" % 50.4625

Todays stock price: 50.462500

print "Today's stock price: %.2f" % 50.4625

Todays stock price: 50.46


n
Python Babjee
Python Classes/Objects
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like a "blueprint" for creating objects.

class MyClass:
var1=10

p1 =MyClass() #creating a object of class


print(p1.var1)

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")

Save the file as mymodule.py

import mymodule
mymodule.MyFunction()

n
Python Babjee
Files I/O

Printing to the Screen

print ("Python is really a great language,", "isn't it")

The input Function

>>> x=input("something:")
something:10
>>> x

The open Function


Before you can read or write a file, you have to open it using Python's built-in
open() function.

file object = open(file_name [, access_mode][, buffering])


n
Python Babjee
n
Python Babjee
The mkdir() Method

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" )

The remove() Method

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

Você também pode gostar