This document provides an introduction and overview of the Python programming language. It outlines the key topics that will be covered in the tutorial, including basic data types, control structures, functions, classes and objects, modules and packages, and exceptions. The tutorial encourages attendees to follow along by downloading and using Python on their laptops. It also demonstrates some basic Python concepts through examples in the interactive shell.
This document provides an introduction and overview of the Python programming language. It outlines the key topics that will be covered in the tutorial, including basic data types, variables, control structures, functions, classes, modules, exceptions, and the standard library. The presentation encourages attendees to follow along by downloading and using Python on their laptops. It also demonstrates some basic Python concepts through examples in the interactive shell.
The document provides an introduction and overview of the Python programming language. It outlines that the tutorial will cover Python's interactive shell, basic data types like numbers and strings, container types like lists and dictionaries, variables, control structures, functions, classes, modules, exceptions, files and the standard library. It encourages attendees to try out Python on their laptops during the session.
This document provides an overview of the Python programming language. It begins with an introduction to why Python is a good choice. It then outlines a tutorial on Python's basic types like numbers, strings, lists, dictionaries, variables, control structures, functions, classes, modules, exceptions, and files. It encourages downloading the latest Python version and using the interactive shell or IDLE to experiment. The bulk of the document then provides details on Python's core concepts like numbers, strings, lists, dictionaries, tuples, variables, control structures, functions, classes, modules, exceptions, and files. It concludes by discussing new features in Python 2.0 and 2.1.
An introduction to the elixir language and the otp framework. A workshop was done and the code can be found here: https://github.com/mendrugory/elixir_and_otp_apps_presentation_1
PythonÓÚWeb 2.0ÍøÕ¾µÄÓ¦Óà - QCon Beijing 2010Qiangning Hong
?
This document discusses Python and web frameworks. It begins with an introduction to Python and its advantages for web development. It then discusses several popular Python web frameworks including web.py, Flask, and Django. It also covers related topics like WSGI, templating with Jinja2, asynchronous programming, and deployment with virtualenv.
This document provides an introduction and overview of the Python programming language. It discusses Python's origins and philosophy of being coherent, powerful, and easy to read and maintain. Key features of Python mentioned include rapid development, object orientation, embedding in C, dynamic typing, exceptions, and built-in interfaces to external services. The document also outlines some common uses of Python and examples of basic Python code structure, variables, operations, control flow, functions, and data types like lists, tuples, and dictionaries.
An object oriented concept in python is detailed for the students or anyone who aspire to learn more powerful concept that helps in developing software or any web development to the persons who work in a tech filed
This document discusses classes and objects in Python. It introduces defining a class with fields and methods, using a class by creating objects and calling methods, constructors, the __init__ method, the __str__ method for string representation, operator overloading, inheritance between classes, and calling superclass methods from a subclass. Examples of a Point class are provided throughout to demonstrate various object-oriented programming concepts in Python.
This document discusses classes and objects in Python. It introduces defining a class with fields and methods, using a class by creating objects and calling methods, constructors, the self parameter, overriding methods like __str__ and adding operator overloading. It also covers inheritance, calling superclass methods, and generating exceptions. The document uses the Point class as a running example and includes exercises to write methods for it.
This document provides an overview of the Python programming language. It begins with an introduction to running Python code and output. It then covers Python's basic data types like integers, floats, strings, lists, tuples and dictionaries. The document explains input and file I/O in Python as well as common control structures like if/else statements, while loops and for loops. It also discusses functions as first-class objects in Python that can be defined and passed as parameters. The document provides examples of higher-order functions like map, filter and reduce. Finally, it notes that functions can be defined inside other functions in Python.
This document provides an overview of the Python programming language. It discusses Python's history and origins, philosophy of being readable and powerful, features like dynamic typing and automatic memory management, uses for shell tools, prototyping, GUIs and more. It also covers Python syntax, modules, functions, control flow, objects and data types like lists, dictionaries and tuples.
Python advanced 3.the python std lib by example ¨C system related modulesJohn(Qiang) Zhang
?
The document provides an overview of several Python standard library modules for working with dates, times, files, directories, and system-related tasks. It describes the time and datetime modules for manipulating dates and times. The os, glob, shutil, and tempfile modules are covered for performing file system operations like opening, reading, writing, copying, and deleting files and directories. The sys module is also summarized for working with command line arguments, modules, and standard input/output streams.
Elixir is a functional programming language that is well-suited for building scalable and fault-tolerant applications. The document provides an introduction to Elixir by discussing its roots in Erlang and how it builds upon Erlang's strengths like concurrency, distribution, and fault tolerance. It also demonstrates some basic Elixir concepts like functions, pattern matching, recursion, and the BEAM virtual machine. Finally, it provides examples of real-world applications of Elixir like building Phoenix web applications and developing embedded hardware projects with Nerves.
Python's "batteries included" philosophy means that it comes with an astonishing amount of great stuff. On top of that, there's a vibrant world of third-party libraries that help make Python even more wonderful. We'll go on a breezy, example-filled tour through some of my favorites, from treasures in the standard library to great third-party packages that I don't think I could live without, and we'll touch on some of the fuzzier aspects of the Python culture that make it such a joy to be part of.
This document provides an overview of the Python programming language. It discusses that Python is a popular, object-oriented scripting language that emphasizes code readability. The document summarizes key Python features such as rapid development, automatic memory management, object-oriented programming, and embedding/extending with C. It also outlines common uses of Python and when it may not be suitable.
This document provides an introduction to the Python programming language. It covers basic Python concepts like data types, strings, data structures, classes, methods, exceptions, iterations, generators, and scopes. Python is described as an easy to learn, read, and use dynamic language with a large selection of stable libraries. It is presented as being much easier than bash scripts for building and maintaining complex system infrastructure.
"JavaScript in 2016" by Eduard Tom¨¤s
Some years ago in a far far away company, Brendan Eich created JavaScript. A lot of things happened since then. Times changed, the web grown, the language itself was updated, and we as a developers need to adapt too. Last year the last standard of the language arose: ECMAScript 2015 is here, and has some new and interesting features. In this talk we will show the most relevant ones, and also we will introduce some interesting patterns that you can use in JavaScript: you'll learn how to master the language and made JavaScript your best ally to conquest the world!
The document summarizes new features in Ruby 2, including lazy enumerators that allow infinite enumerations to be cut off, the Module#prepend method that puts modules before classes in the method lookup path, String methods like #bytes now returning arrays instead of enumerators, keyword arguments that allow default parameters, and various other minor changes.
Digital images are represented as multidimensional arrays of numbers, with each number representing the intensity or color value of a pixel. An image is converted to a digital form through sampling and quantization. Sampling involves digitizing the spatial coordinates, while quantization involves digitizing the pixel intensity values. The spatial and intensity resolution of a digital image determine the amount of detail that can be represented. Higher resolution means more pixels and more intensity levels, allowing finer detail to be captured.
Support Vector Machines aim to find an optimal decision boundary that maximizes the margin between different classes of data points. This is achieved by formulating the problem as a constrained optimization problem that seeks to minimize training error while maximizing the margin. The dual formulation results in a quadratic programming problem that can be solved using algorithms like sequential minimal optimization. Kernels allow the data to be implicitly mapped to a higher dimensional feature space, enabling non-linear decision boundaries to be learned. This "kernel trick" avoids explicitly computing coordinates in the higher dimensional space.
digital image processing chapter two, fundamentalsKNaveenKumarECE
?
The document discusses key concepts in digital image processing including:
1) Elements of visual perception such as the structure of the eye, rods and cones, and brightness discrimination.
2) How digital images are formed including image sensing, sampling, quantization, and the relationship between pixels in an image such as neighborhoods and adjacency.
3) Common operations and transformations that can be performed on digital images including arithmetic, set, logical, and affine transformations as well as image transforms like the Fourier transform.
Augastiny_VANET advantages and disadvantages.pptxKNaveenKumarECE
?
The document summarizes research on quality of service (QoS) enhancement in software defined networking (SDN) based vehicular ad hoc networks (VANETs). It first introduces VANETs and discusses their services, technologies, and issues. It then explains how SDN can provide a global view and centralized control to address VANET issues. The SDN architecture separates the control plane and data plane. Issues in applying SDN to VANETs include privacy concerns due to centralized control and single point of failure risks. The document reviews several papers on improving VANET QoS through various routing algorithms, clustering, bio-inspired methods, and fog/edge computing approaches integrated with SDN and 5G
More Related Content
Similar to introduction to python, fundamentals and basics (16)
This document discusses classes and objects in Python. It introduces defining a class with fields and methods, using a class by creating objects and calling methods, constructors, the __init__ method, the __str__ method for string representation, operator overloading, inheritance between classes, and calling superclass methods from a subclass. Examples of a Point class are provided throughout to demonstrate various object-oriented programming concepts in Python.
This document discusses classes and objects in Python. It introduces defining a class with fields and methods, using a class by creating objects and calling methods, constructors, the self parameter, overriding methods like __str__ and adding operator overloading. It also covers inheritance, calling superclass methods, and generating exceptions. The document uses the Point class as a running example and includes exercises to write methods for it.
This document provides an overview of the Python programming language. It begins with an introduction to running Python code and output. It then covers Python's basic data types like integers, floats, strings, lists, tuples and dictionaries. The document explains input and file I/O in Python as well as common control structures like if/else statements, while loops and for loops. It also discusses functions as first-class objects in Python that can be defined and passed as parameters. The document provides examples of higher-order functions like map, filter and reduce. Finally, it notes that functions can be defined inside other functions in Python.
This document provides an overview of the Python programming language. It discusses Python's history and origins, philosophy of being readable and powerful, features like dynamic typing and automatic memory management, uses for shell tools, prototyping, GUIs and more. It also covers Python syntax, modules, functions, control flow, objects and data types like lists, dictionaries and tuples.
Python advanced 3.the python std lib by example ¨C system related modulesJohn(Qiang) Zhang
?
The document provides an overview of several Python standard library modules for working with dates, times, files, directories, and system-related tasks. It describes the time and datetime modules for manipulating dates and times. The os, glob, shutil, and tempfile modules are covered for performing file system operations like opening, reading, writing, copying, and deleting files and directories. The sys module is also summarized for working with command line arguments, modules, and standard input/output streams.
Elixir is a functional programming language that is well-suited for building scalable and fault-tolerant applications. The document provides an introduction to Elixir by discussing its roots in Erlang and how it builds upon Erlang's strengths like concurrency, distribution, and fault tolerance. It also demonstrates some basic Elixir concepts like functions, pattern matching, recursion, and the BEAM virtual machine. Finally, it provides examples of real-world applications of Elixir like building Phoenix web applications and developing embedded hardware projects with Nerves.
Python's "batteries included" philosophy means that it comes with an astonishing amount of great stuff. On top of that, there's a vibrant world of third-party libraries that help make Python even more wonderful. We'll go on a breezy, example-filled tour through some of my favorites, from treasures in the standard library to great third-party packages that I don't think I could live without, and we'll touch on some of the fuzzier aspects of the Python culture that make it such a joy to be part of.
This document provides an overview of the Python programming language. It discusses that Python is a popular, object-oriented scripting language that emphasizes code readability. The document summarizes key Python features such as rapid development, automatic memory management, object-oriented programming, and embedding/extending with C. It also outlines common uses of Python and when it may not be suitable.
This document provides an introduction to the Python programming language. It covers basic Python concepts like data types, strings, data structures, classes, methods, exceptions, iterations, generators, and scopes. Python is described as an easy to learn, read, and use dynamic language with a large selection of stable libraries. It is presented as being much easier than bash scripts for building and maintaining complex system infrastructure.
"JavaScript in 2016" by Eduard Tom¨¤s
Some years ago in a far far away company, Brendan Eich created JavaScript. A lot of things happened since then. Times changed, the web grown, the language itself was updated, and we as a developers need to adapt too. Last year the last standard of the language arose: ECMAScript 2015 is here, and has some new and interesting features. In this talk we will show the most relevant ones, and also we will introduce some interesting patterns that you can use in JavaScript: you'll learn how to master the language and made JavaScript your best ally to conquest the world!
The document summarizes new features in Ruby 2, including lazy enumerators that allow infinite enumerations to be cut off, the Module#prepend method that puts modules before classes in the method lookup path, String methods like #bytes now returning arrays instead of enumerators, keyword arguments that allow default parameters, and various other minor changes.
Digital images are represented as multidimensional arrays of numbers, with each number representing the intensity or color value of a pixel. An image is converted to a digital form through sampling and quantization. Sampling involves digitizing the spatial coordinates, while quantization involves digitizing the pixel intensity values. The spatial and intensity resolution of a digital image determine the amount of detail that can be represented. Higher resolution means more pixels and more intensity levels, allowing finer detail to be captured.
Support Vector Machines aim to find an optimal decision boundary that maximizes the margin between different classes of data points. This is achieved by formulating the problem as a constrained optimization problem that seeks to minimize training error while maximizing the margin. The dual formulation results in a quadratic programming problem that can be solved using algorithms like sequential minimal optimization. Kernels allow the data to be implicitly mapped to a higher dimensional feature space, enabling non-linear decision boundaries to be learned. This "kernel trick" avoids explicitly computing coordinates in the higher dimensional space.
digital image processing chapter two, fundamentalsKNaveenKumarECE
?
The document discusses key concepts in digital image processing including:
1) Elements of visual perception such as the structure of the eye, rods and cones, and brightness discrimination.
2) How digital images are formed including image sensing, sampling, quantization, and the relationship between pixels in an image such as neighborhoods and adjacency.
3) Common operations and transformations that can be performed on digital images including arithmetic, set, logical, and affine transformations as well as image transforms like the Fourier transform.
Augastiny_VANET advantages and disadvantages.pptxKNaveenKumarECE
?
The document summarizes research on quality of service (QoS) enhancement in software defined networking (SDN) based vehicular ad hoc networks (VANETs). It first introduces VANETs and discusses their services, technologies, and issues. It then explains how SDN can provide a global view and centralized control to address VANET issues. The SDN architecture separates the control plane and data plane. Issues in applying SDN to VANETs include privacy concerns due to centralized control and single point of failure risks. The document reviews several papers on improving VANET QoS through various routing algorithms, clustering, bio-inspired methods, and fog/edge computing approaches integrated with SDN and 5G
This document provides biographies of the authors of the book "ARM System Developer's Guide". It introduces Andrew N. Sloss, Dominic Symes, Chris Wright, and John Rayfield. It provides details on each author's background, qualifications, work experience, and current roles relevant to ARM system development.
Preface: The ReGenX Generator innovation operates with a US Patented Frequency Dependent Load
Current Delay which delays the creation and storage of created Electromagnetic Field Energy around
the exterior of the generator coil. The result is the created and Time Delayed Electromagnetic Field
Energy performs any magnitude of Positive Electro-Mechanical Work at infinite efficiency on the
generator's Rotating Magnetic Field, increasing its Kinetic Energy and increasing the Kinetic Energy of
an EV or ICE Vehicle to any magnitude without requiring any Externally Supplied Input Energy. In
Electricity Generation applications the ReGenX Generator innovation now allows all electricity to be
generated at infinite efficiency requiring zero Input Energy, zero Input Energy Cost, while producing
zero Greenhouse Gas Emissions, zero Air Pollution and zero Nuclear Waste during the Electricity
Generation Phase. In Electric Motor operation the ReGen-X Quantum Motor now allows any
magnitude of Work to be performed with zero Electric Input Energy.
Demonstration Protocol: The demonstration protocol involves three prototypes;
1. Protytpe #1, demonstrates the ReGenX Generator's Load Current Time Delay when compared
to the instantaneous Load Current Sine Wave for a Conventional Generator Coil.
2. In the Conventional Faraday Generator operation the created Electromagnetic Field Energy
performs Negative Work at infinite efficiency and it reduces the Kinetic Energy of the system.
3. The Magnitude of the Negative Work / System Kinetic Energy Reduction (in Joules) is equal to
the Magnitude of the created Electromagnetic Field Energy (also in Joules).
4. When the Conventional Faraday Generator is placed On-Load, Negative Work is performed and
the speed of the system decreases according to Lenz's Law of Induction.
5. In order to maintain the System Speed and the Electric Power magnitude to the Loads,
additional Input Power must be supplied to the Prime Mover and additional Mechanical Input
Power must be supplied to the Generator's Drive Shaft.
6. For example, if 100 Watts of Electric Power is delivered to the Load by the Faraday Generator,
an additional >100 Watts of Mechanical Input Power must be supplied to the Generator's Drive
Shaft by the Prime Mover.
7. If 1 MW of Electric Power is delivered to the Load by the Faraday Generator, an additional >1
MW Watts of Mechanical Input Power must be supplied to the Generator's Drive Shaft by the
Prime Mover.
8. Generally speaking the ratio is 2 Watts of Mechanical Input Power to every 1 Watt of Electric
Output Power generated.
9. The increase in Drive Shaft Mechanical Input Power is provided by the Prime Mover and the
Input Energy Source which powers the Prime Mover.
10. In the Heins ReGenX Generator operation the created and Time Delayed Electromagnetic Field
Energy performs Positive Work at infinite efficiency and it increases the Kinetic Energy of the
system.
This PDF highlights how engineering model making helps turn designs into functional prototypes, aiding in visualization, testing, and refinement. It covers different types of models used in industries like architecture, automotive, and aerospace, emphasizing cost and time efficiency.
Welcome to the March 2025 issue of WIPAC Monthly the magazine brought to you by the LinkedIn Group WIPAC Monthly.
In this month's edition, on top of the month's news from the water industry we cover subjects from the intelligent use of wastewater networks, the use of machine learning in water quality as well as how, we as an industry, need to develop the skills base in developing areas such as Machine Learning and Artificial Intelligence.
Enjoy the latest edition
Integration of Additive Manufacturing (AM) with IoT : A Smart Manufacturing A...ASHISHDESAI85
?
Combining 3D printing with Internet of Things (IoT) enables the creation of smart, connected, and customizable objects that can monitor, control, and optimize their performance, potentially revolutionizing various industries. oT-enabled 3D printers can use sensors to monitor the quality of prints during the printing process. If any defects or deviations from the desired specifications are detected, the printer can adjust its parameters in real time to ensure that the final product meets the required standards.
Lecture -3 Cold water supply system.pptxrabiaatif2
?
The presentation on Cold Water Supply explored the fundamental principles of water distribution in buildings. It covered sources of cold water, including municipal supply, wells, and rainwater harvesting. Key components such as storage tanks, pipes, valves, and pumps were discussed for efficient water delivery. Various distribution systems, including direct and indirect supply methods, were analyzed for residential and commercial applications. The presentation emphasized water quality, pressure regulation, and contamination prevention. Common issues like pipe corrosion, leaks, and pressure drops were addressed along with maintenance strategies. Diagrams and case studies illustrated system layouts and best practices for optimal performance.
¦Ñ. ¦ª?¦Ò¦Ó¦Á? ¦²¦Á¦Ö¦Ð?¦Æ¦Ç?: Foundation Analysis and Design: Single Piles
Welcome to this comprehensive presentation on "Foundation Analysis and Design," focusing on Single Piles¡ªStatic Capacity, Lateral Loads, and Pile/Pole Buckling. This presentation will explore the fundamental concepts, equations, and practical considerations for designing and analyzing pile foundations.
We'll examine different pile types, their characteristics, load transfer mechanisms, and the complex interactions between piles and surrounding soil. Throughout this presentation, we'll highlight key equations and methodologies for calculating pile capacities under various conditions.
Frankfurt University of Applied Science urkundeLisa Emerson
?
introduction to python, fundamentals and basics
1. Introduction to Python
LinuxWorld - New York City - January 2002
Guido van Rossum
Director of PythonLabs at Zope Corporation
guido@python.org
guido@zope.com
2. ºÝºÝߣ 2 ?2001, 2002 Guido van Rossum
Why Python?
? Have your cake and eat it, too:
Productivity and readable code
? VHLLs will gain on system languages
(John Ousterhout)
? "Life's better without braces"
(Bruce Eckel)
3. ºÝºÝߣ 3 ?2001, 2002 Guido van Rossum
Tutorial Outline
? interactive "shell"
? basic types: numbers, strings
? container types: lists, dictionaries, tuples
? variables
? control structures
? functions & procedures
? classes & instances
? modules & packages
? exceptions
? files & standard library
? what's new in Python 2.0 and beyond
4. ºÝºÝߣ 4 ?2001, 2002 Guido van Rossum
Try It Out!
? If you brought a laptop into the classroom,
feel free to play along
? Download Python from www.python.org
? Any version will do for this class
¨C By and large they are all mutually compatible
¨C Recommended version: 2.1.1 or 2.2
¨C Oldest version still in widespread use: 1.5.2
¨C Avoid 1.6/1.6.1 if you can
¨C When using 2.0 or 2.1, upgrade to 2.0.1 / 2.1.1
¨C 2.1.2 is coming soon!
? Use IDLE if you can
5. ºÝºÝߣ 5 ?2001, 2002 Guido van Rossum
Interactive ¡°Shell¡±
? Great for learning the language
? Great for experimenting with the library
? Great for testing your own modules
? Two variations: IDLE (GUI),
python (command line)
? Type statements or expressions at prompt:
>>> print "Hello, world"
Hello, world
>>> x = 12**2
>>> x/2
72
>>> # this is a comment
6. ºÝºÝߣ 6 ?2001, 2002 Guido van Rossum
Numbers
? The usual suspects
? 12, 3.14, 0xFF, 0377, (-1+2)*3/4**5, abs(x), 0<x<=5
? C-style shifting & masking
? 1<<16, x&0xff, x|1, ~x, x^y
? Integer division truncates :-(
? 1/2 -> 0 # 1./2. -> 0.5, float(1)/2 -> 0.5
? Will be fixed in the future
? Long (arbitrary precision), complex
? 2L**100 -> 1267650600228229401496703205376L
¨C In Python 2.2 and beyond, 2**100 does the same thing
? 1j**2 -> (-1+0j)
11. ºÝºÝߣ 11 ?2001, 2002 Guido van Rossum
More Dictionary Ops
? Keys, values, items:
? d.keys() -> ["duck", "back"]
? d.values() -> ["duik", "rug"]
? d.items() -> [("duck","duik"), ("back","rug")]
? Presence check:
? d.has_key("duck") -> 1; d.has_key("spam") -> 0
? Values of any type; keys almost any
? {"name":"Guido", "age":43, ("hello","world"):1,
42:"yes", "flag": ["red","white","blue"]}
12. ºÝºÝߣ 12 ?2001, 2002 Guido van Rossum
Dictionary Details
? Keys must be immutable:
¨C numbers, strings, tuples of immutables
? these cannot be changed after creation
¨C reason is hashing (fast lookup technique)
¨C not lists or other dictionaries
? these types of objects can be changed "in place"
¨C no restrictions on values
? Keys will be listed in arbitrary order
¨C again, because of hashing
13. ºÝºÝߣ 13 ?2001, 2002 Guido van Rossum
Tuples
? key = (lastname, firstname)
? point = x, y, z # parentheses optional
? x, y, z = point # unpack
? lastname = key[0]
? singleton = (1,) # trailing comma!!!
? empty = () # parentheses!
? tuples vs. lists; tuples immutable
14. ºÝºÝߣ 14 ?2001, 2002 Guido van Rossum
Variables
? No need to declare
? Need to assign (initialize)
? use of uninitialized variable raises exception
? Not typed
if friendly: greeting = "hello world"
else: greeting = 12**2
print greeting
? Everything is a "variable":
? Even functions, classes, modules
15. ºÝºÝߣ 15 ?2001, 2002 Guido van Rossum
Reference Semantics
? Assignment manipulates references
? x = y does not make a copy of y
? x = y makes x reference the object y references
? Very useful; but beware!
? Example:
>>> a = [1, 2, 3]
>>> b = a
>>> a.append(4)
>>> print b
[1, 2, 3, 4]
16. ºÝºÝߣ 16 ?2001, 2002 Guido van Rossum
a
1 2 3
b
a
1 2 3
b
4
a = [1, 2, 3]
a.append(4)
b = a
a 1 2 3
Changing a Shared List
17. ºÝºÝߣ 17 ?2001, 2002 Guido van Rossum
a
1
b
a
1
b
a = 1
a = a+1
b = a
a 1
2
Changing an Integer
old reference deleted
by assignment (a=...)
new int object created
by add operator (1+1)
18. ºÝºÝߣ 18 ?2001, 2002 Guido van Rossum
Control Structures
if condition:
statements
[elif condition:
statements] ...
else:
statements
while condition:
statements
for var in sequence:
statements
break
continue
19. ºÝºÝߣ 19 ?2001, 2002 Guido van Rossum
Grouping Indentation
In Python:
for i in range(20):
if i%3 == 0:
print i
if i%5 == 0:
print "Bingo!"
print "---"
In C:
for (i = 0; i < 20; i++)
{
if (i%3 == 0) {
printf("%dn", i);
if (i%5 == 0) {
printf("Bingo!n"); }
}
printf("---n");
}
0
Bingo!
---
---
---
3
---
---
---
6
---
---
---
9
---
---
---
12
---
---
---
15
Bingo!
---
---
---
18
---
---
20. ºÝºÝߣ 20 ?2001, 2002 Guido van Rossum
Functions, Procedures
def name(arg1, arg2, ...):
"""documentation""" # optional doc string
statements
return # from procedure
return expression # from function
21. ºÝºÝߣ 21 ?2001, 2002 Guido van Rossum
Example Function
def gcd(a, b):
"greatest common divisor"
while a != 0:
a, b = b%a, a # parallel assignment
return b
>>> gcd.__doc__
'greatest common divisor'
>>> gcd(12, 20)
4
22. ºÝºÝߣ 22 ?2001, 2002 Guido van Rossum
Classes
class name:
"documentation"
statements
-or-
class name(base1, base2, ...):
...
Most, statements are method definitions:
def name(self, arg1, arg2, ...):
...
May also be class variable assignments
23. ºÝºÝߣ 23 ?2001, 2002 Guido van Rossum
Example Class
class Stack:
"A well-known data structure¡"
def __init__(self): # constructor
self.items = []
def push(self, x):
self.items.append(x) # the sky is the limit
def pop(self):
x = self.items[-1] # what happens if it¡¯s
empty?
del self.items[-1]
return x
def empty(self):
return len(self.items) == 0 # Boolean result
24. ºÝºÝߣ 24 ?2001, 2002 Guido van Rossum
Using Classes
? To create an instance, simply call the class object:
x = Stack() # no 'new' operator!
? To use methods of the instance, call using dot
notation:
x.empty() # -> 1
x.push(1) # [1]
x.empty() # -> 0
x.push("hello") # [1, "hello"]
x.pop() # -> "hello" # [1]
? To inspect instance variables, use dot notation:
x.items # -> [1]
25. ºÝºÝߣ 25 ?2001, 2002 Guido van Rossum
Subclassing
class FancyStack(Stack):
"stack with added ability to inspect inferior stack items"
def peek(self, n):
"peek(0) returns top; peek(-1) returns item below that; etc."
size = len(self.items)
assert 0 <= n < size # test precondition
return self.items[size-1-n]
26. ºÝºÝߣ 26 ?2001, 2002 Guido van Rossum
Subclassing (2)
class LimitedStack(FancyStack):
"fancy stack with limit on stack size"
def __init__(self, limit):
self.limit = limit
FancyStack.__init__(self) # base class
constructor
def push(self, x):
assert len(self.items) < self.limit
FancyStack.push(self, x) # "super" method call
27. ºÝºÝߣ 27 ?2001, 2002 Guido van Rossum
Class / Instance Variables
class Connection:
verbose = 0 # class variable
def __init__(self, host):
self.host = host # instance variable
def debug(self, v):
self.verbose = v # make instance variable!
def connect(self):
if self.verbose: # class or instance variable?
print "connecting to", self.host
28. ºÝºÝߣ 28 ?2001, 2002 Guido van Rossum
Instance Variable Rules
? On use via instance (self.x), search order:
¨C (1) instance, (2) class, (3) base classes
¨C this also works for method lookup
? On assignment via instance (self.x = ...):
¨C always makes an instance variable
? Class variables "default" for instance
variables
? But...!
¨C mutable class variable: one copy shared by all
¨C mutable instance variable: each instance its own
29. ºÝºÝߣ 29 ?2001, 2002 Guido van Rossum
Modules
? Collection of stuff in foo.py file
¨C functions, classes, variables
? Importing modules:
¨C import re; print re.match("[a-z]+", s)
¨C from re import match; print match("[a-z]+", s)
? Import with rename:
¨C import re as regex
¨C from re import match as m
¨C Before Python 2.0:
? import re; regex = re; del re
30. ºÝºÝߣ 30 ?2001, 2002 Guido van Rossum
Packages
? Collection of modules in directory
? Must have __init__.py file
? May contain subpackages
? Import syntax:
¨C from P.Q.M import foo; print foo()
¨C from P.Q import M; print M.foo()
¨C import P.Q.M; print P.Q.M.foo()
¨C import P.Q.M as M; print M.foo() # new
32. ºÝºÝߣ 32 ?2001, 2002 Guido van Rossum
Try-finally: Cleanup
f = open(file)
try:
process_file(f)
finally:
f.close() # always executed
print "OK" # executed on success only
33. ºÝºÝߣ 33 ?2001, 2002 Guido van Rossum
Raising Exceptions
? raise IndexError
? raise IndexError("k out of range")
? raise IndexError, "k out of range"
? try:
something
except: # catch everything
print "Oops"
raise # reraise
34. ºÝºÝߣ 34 ?2001, 2002 Guido van Rossum
More on Exceptions
? User-defined exceptions
¨C subclass Exception or any other standard exception
? Old Python: exceptions can be strings
¨C WATCH OUT: compared by object identity, not ==
? Last caught exception info:
¨C sys.exc_info() == (exc_type, exc_value, exc_traceback)
? Last uncaught exception (traceback printed):
¨C sys.last_type, sys.last_value, sys.last_traceback
? Printing exceptions: traceback module
35. ºÝºÝߣ 35 ?2001, 2002 Guido van Rossum
File Objects
? f = open(filename[, mode[, buffersize])
¨C mode can be "r", "w", "a" (like C stdio); default "r"
¨C append "b" for text translation mode
¨C append "+" for read/write open
¨C buffersize: 0=unbuffered; 1=line-buffered; buffered
? methods:
¨C read([nbytes]), readline(), readlines()
¨C write(string), writelines(list)
¨C seek(pos[, how]), tell()
¨C flush(), close()
¨C fileno()
37. ºÝºÝߣ 37 ?2001, 2002 Guido van Rossum
Python 2.0: What's New
? Augmented assignment: x += y
? List comprehensions:
[s.strip() for s in f.readlines()]
? Extended print: print >>sys.stderr, "Hello!"
? Extended import: import foo as bar
? Unicode strings: u"u1234"
? New re implementation (faster, Unicode)
? Collection of cyclic garbage
? XML, distutils
39. ºÝºÝߣ 39 ?2001, 2002 Guido van Rossum
Python 2.2: What's New
? Iterators and Generators
? from __future__ import generators
def inorder(tree):
if tree:
for x in inorder(tree.left): yield x
yield tree.label
for x in inorder(tree.right): yield x
? Type/class unification
¨C class mydict(dict): ¡
? Fix division operator so 1/2 == 0.5; 1//2
== 0
¨C Requires __future__ statement in Python 2.x
¨C Change will be permanent in Python 3.0
40. ºÝºÝߣ 40 ?2001, 2002 Guido van Rossum
URLs
? http://www.python.org
¨C official site
? http://starship.python.net
¨C Community
? http://www.python.org/psa/bookstore/
¨C (alias for http://www.amk.ca/bookstore/)
¨C Python Bookstore
41. ºÝºÝߣ 41 ?2001, 2002 Guido van Rossum
Further Reading
? Learning Python: Lutz, Ascher (O'Reilly '98)
? Python Essential Reference: Beazley (New Riders '99)
? Programming Python, 2nd Ed.: Lutz (O'Reilly '01)
? Core Python Programming: Chun (Prentice-Hall '00)
? The Quick Python Book: Harms, McDonald (Manning '99)
? The Standard Python Library: Lundh (O'Reilly '01)
? Python and Tkinter Programming: Grayson (Manning '00)
? Python Programming on Win32:
Hammond, Robinson (O'Reilly '00)
? Learn to Program Using Python: Gauld (Addison-W. '00)
? And many more titles...