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.
This document provides an introduction to Python programming through a series of exercises. It begins with definitions of Python and why it is useful. It then covers basic Python concepts like strings, lists, loops, functions and modules. The latter half provides 5 exercises to practice these concepts, such as printing messages, removing characters, using for loops and if/else statements, writing data to a JSON file, and generating stock data from an online API. The document aims to cover Python fundamentals in 90 minutes through hands-on learning.
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
The document provides information about various Python concepts like print statement, variables, data types, operators, conditional statements, loops, functions, modules, exceptions, files and packages. It explains print statement syntax, how variables work in Python, built-in data types like numbers, strings, lists, dictionaries and tuples. It also discusses conditional statements like if-else, loops like while and for, functions, modules, exceptions, file handling operations and packages in Python.
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.
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
This document provides an introduction to learning Python. It discusses prerequisites for Python, basic Python concepts like variables, data types, operators, conditionals and loops. It also covers functions, files, classes and exceptions handling in Python. The document demonstrates these concepts through examples and exercises learners to practice char frequency counting and Caesar cipher encoding/decoding in Python. It encourages learners to practice more to master the language and provides additional learning resources.
The document provides an introduction and comparison of Python and C programming languages. Some key points:
- Python is an interpreted language while C needs compilation. Python makes program development faster.
- Variables, input/output, arrays, control structures like if/else, for loops work differently in Python compared to C.
- Python uses lists instead of arrays. Lists are mutable and support slicing.
- Strings are treated as character lists in Python.
- Functions are defined using def keyword in Python.
- The document also introduces sequences (strings, tuples, lists), dictionaries, and sets in Python - their usage and operations.
The document provides an introduction to Python including:
- Starting the Python interpreter and basic calculations
- Variables, expressions, statements, functions, modules, comments
- Strings, lists, tuples, dictionaries
- Common list, string, and dictionary methods
It covers the basic Python syntax and many common data structures and their associated methods in less than 3 sentences.
This document provides an introduction to Python programming through a series of exercises. It begins with definitions of Python and why it is useful. It then covers basic Python concepts like strings, lists, loops, functions and modules. The latter half provides 5 exercises to practice these concepts, such as printing messages, removing characters, using for loops and if/else statements, writing data to a JSON file, and generating stock data from an online API. The document aims to cover Python fundamentals in 90 minutes through hands-on learning.
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
The document provides information about various Python concepts like print statement, variables, data types, operators, conditional statements, loops, functions, modules, exceptions, files and packages. It explains print statement syntax, how variables work in Python, built-in data types like numbers, strings, lists, dictionaries and tuples. It also discusses conditional statements like if-else, loops like while and for, functions, modules, exceptions, file handling operations and packages in Python.
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.
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
This document provides an introduction to learning Python. It discusses prerequisites for Python, basic Python concepts like variables, data types, operators, conditionals and loops. It also covers functions, files, classes and exceptions handling in Python. The document demonstrates these concepts through examples and exercises learners to practice char frequency counting and Caesar cipher encoding/decoding in Python. It encourages learners to practice more to master the language and provides additional learning resources.
The document provides an introduction and comparison of Python and C programming languages. Some key points:
- Python is an interpreted language while C needs compilation. Python makes program development faster.
- Variables, input/output, arrays, control structures like if/else, for loops work differently in Python compared to C.
- Python uses lists instead of arrays. Lists are mutable and support slicing.
- Strings are treated as character lists in Python.
- Functions are defined using def keyword in Python.
- The document also introduces sequences (strings, tuples, lists), dictionaries, and sets in Python - their usage and operations.
The document provides an introduction to Python including:
- Starting the Python interpreter and basic calculations
- Variables, expressions, statements, functions, modules, comments
- Strings, lists, tuples, dictionaries
- Common list, string, and dictionary methods
It covers the basic Python syntax and many common data structures and their associated methods in less than 3 sentences.
The document provides an introduction to Python including:
- Starting the Python interpreter and basic calculations
- Variables, expressions, statements, functions, modules, comments
- Strings, lists, tuples, dictionaries
- Common list, string, and dictionary methods
It covers the basic Python syntax and many common data structures and their associated methods in less than 3 sentences.
Functions allow storing and reusing code. There are built-in functions and user-defined functions. Functions take arguments as input, can perform operations, and return outputs. Arguments are passed into functions during a call, while parameters receive the arguments inside the function definition. Functions help organize code and avoid repetition.
This document provides an introduction and overview of the Python programming language. It discusses Python's origins, philosophy, features, and uses. Key points covered include Python's simplicity, power, object-oriented approach, and wide portability. Examples are provided of basic Python syntax and constructs like strings, lists, functions, modules, and dictionaries.
The document discusses strategies for porting code to Python 3. It recommends either only supporting Python 3 and running code through the 2to3 converter once, or maintaining separate code branches and running 2to3 on the Python 3 branch. It also discusses continuously running 2to3 on code during development. Common porting issues include bytes handling, print becoming a function, dict methods changing, and test failures. The document provides workarounds and examples for many of these issues.
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 discusses six Python packages that are useful to know:
1. First - A utility for selecting the first successful result from a sequence of functions.
2. Parse - A library for parsing Python format strings and extracting values.
3. Filecmp - A module for comparing files and directories.
4. Bitrot - A tool for detecting silent data corruption in files.
5. Docopt - A tool for generating command-line interfaces from a docstring.
6. Six - A library for writing code that is compatible with both Python 2 and Python 3.
This document provides an overview of the Ruby programming language, including its history, philosophy, characteristics, applications, culture, syntax, built-in types, classes and methods, accessors, control flow, including code, modules, metaprogramming, web frameworks, web servers, shell scripting, testing, JRuby, and calling between Java and Ruby.
Python classes in mumbai
best Python classes in mumbai with job assistance.
our features are:
expert guidance by it industry professionals
lowest fees of 5000
practical exposure to handle projects
well equiped lab
after course resume writing guidance
A dictionary in Python is a mutable container that stores key-value pairs, with keys that must be immutable like strings or numbers. Dictionaries allow fast lookup of values based on keys. Keys must be unique within a dictionary, while values can be of any type including other containers. Dictionaries can be accessed, updated, and modified using square bracket notation or dictionary methods.
The document provides an overview of the Python programming language. It discusses Python's history, how to install and run Python, basic data types like integers, floats, strings, lists, and tuples. It explains that lists are mutable while tuples are immutable. The document also covers topics like functions, modules, control flow, and the Python interpreter.
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.
Chapter 2 Python Language Basics, IPython.pptxSovannDoeur
The document outlines key concepts in Python including:
- Python is an interpreted language and runs code line by line using the Python interpreter.
- Python has various data types including integers, floats, strings, booleans, lists, tuples, and dictionaries.
- Control flow in Python uses conditional statements like if/else and loops like for and while to control program execution.
- Functions and methods allow calling and reusing code, while classes and objects are Python's way of modeling real-world items.
This document provides a cheat sheet on Python keywords and basic data types. It lists common Python keywords like False, True, and, or, not, break, continue, class, def, if, else, for, while, in, is, None, lambda, and return along with code examples. It also covers basic data types like Boolean, integer, float, string, list, set, dictionary, and complex data types like classes. It provides examples of using lists, sets, dictionaries, classes and functions in Python.
This document provides examples and descriptions of Python keywords and basic data types. It discusses keywords like False, True, and, or, not, break, continue, class, def, if, elif, else, for, while, in, is, None, lambda, and return. It also covers basic data types like integers, floats, strings, lists, sets, dictionaries, and Boolean values. It provides code examples to demonstrate the usage of these keywords and data types in Python.
This document provides an introduction and overview of the Python programming language. It outlines the key topics that will be covered in a Python tutorial, including basic data types, variables, control structures, functions, classes and objects, modules and packages, exceptions, files and the standard library. The document also summarizes some of the new features introduced in Python versions 2.0 and 2.1.
This document provides an introduction and overview of the Python programming language. It outlines the key topics that will be covered in a Python tutorial, including basic data types, variables, control structures, functions, classes, exceptions, modules and packages, and the standard library. The document consists of slides from a 2002 presentation on Python given by Guido van Rossum, the creator of Python. It encourages attendees to follow along by downloading and using Python in an 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, container types, variables, control structures, functions, classes, modules, exceptions, and the standard library. It encourages attendees to follow along by downloading and using Python on their laptops. Various versions of Python are recommended and compatibility notes are provided. The document also demonstrates basic interactive use of the Python shell.
This document provides an introduction and overview of the Python programming language. It outlines the key topics that will be covered in a Python tutorial, including basic data types, variables, control structures, functions, classes and objects, modules and packages, exceptions, files and the standard library. The document also summarizes some of the new features introduced in Python versions 2.0 and 2.1.
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, container types, variables, control structures, functions, classes, modules, exceptions, and the standard library. It encourages attendees to follow along by downloading and using Python on their laptops. Various versions of Python are recommended and caveats about specific versions are provided. The document also demonstrates basic interactive use of the Python shell.
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...University of Maribor
Slides from talk presenting:
Aleš Zamuda: Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapter and Networking.
Presentation at IcETRAN 2024 session:
"Inter-Society Networking Panel GRSS/MTT-S/CIS
Panel Session: Promoting Connection and Cooperation"
IEEE Slovenia GRSS
IEEE Serbia and Montenegro MTT-S
IEEE Slovenia CIS
11TH INTERNATIONAL CONFERENCE ON ELECTRICAL, ELECTRONIC AND COMPUTING ENGINEERING
3-6 June 2024, Niš, Serbia
The document provides an introduction to Python including:
- Starting the Python interpreter and basic calculations
- Variables, expressions, statements, functions, modules, comments
- Strings, lists, tuples, dictionaries
- Common list, string, and dictionary methods
It covers the basic Python syntax and many common data structures and their associated methods in less than 3 sentences.
Functions allow storing and reusing code. There are built-in functions and user-defined functions. Functions take arguments as input, can perform operations, and return outputs. Arguments are passed into functions during a call, while parameters receive the arguments inside the function definition. Functions help organize code and avoid repetition.
This document provides an introduction and overview of the Python programming language. It discusses Python's origins, philosophy, features, and uses. Key points covered include Python's simplicity, power, object-oriented approach, and wide portability. Examples are provided of basic Python syntax and constructs like strings, lists, functions, modules, and dictionaries.
The document discusses strategies for porting code to Python 3. It recommends either only supporting Python 3 and running code through the 2to3 converter once, or maintaining separate code branches and running 2to3 on the Python 3 branch. It also discusses continuously running 2to3 on code during development. Common porting issues include bytes handling, print becoming a function, dict methods changing, and test failures. The document provides workarounds and examples for many of these issues.
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 discusses six Python packages that are useful to know:
1. First - A utility for selecting the first successful result from a sequence of functions.
2. Parse - A library for parsing Python format strings and extracting values.
3. Filecmp - A module for comparing files and directories.
4. Bitrot - A tool for detecting silent data corruption in files.
5. Docopt - A tool for generating command-line interfaces from a docstring.
6. Six - A library for writing code that is compatible with both Python 2 and Python 3.
This document provides an overview of the Ruby programming language, including its history, philosophy, characteristics, applications, culture, syntax, built-in types, classes and methods, accessors, control flow, including code, modules, metaprogramming, web frameworks, web servers, shell scripting, testing, JRuby, and calling between Java and Ruby.
Python classes in mumbai
best Python classes in mumbai with job assistance.
our features are:
expert guidance by it industry professionals
lowest fees of 5000
practical exposure to handle projects
well equiped lab
after course resume writing guidance
A dictionary in Python is a mutable container that stores key-value pairs, with keys that must be immutable like strings or numbers. Dictionaries allow fast lookup of values based on keys. Keys must be unique within a dictionary, while values can be of any type including other containers. Dictionaries can be accessed, updated, and modified using square bracket notation or dictionary methods.
The document provides an overview of the Python programming language. It discusses Python's history, how to install and run Python, basic data types like integers, floats, strings, lists, and tuples. It explains that lists are mutable while tuples are immutable. The document also covers topics like functions, modules, control flow, and the Python interpreter.
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.
Chapter 2 Python Language Basics, IPython.pptxSovannDoeur
The document outlines key concepts in Python including:
- Python is an interpreted language and runs code line by line using the Python interpreter.
- Python has various data types including integers, floats, strings, booleans, lists, tuples, and dictionaries.
- Control flow in Python uses conditional statements like if/else and loops like for and while to control program execution.
- Functions and methods allow calling and reusing code, while classes and objects are Python's way of modeling real-world items.
This document provides a cheat sheet on Python keywords and basic data types. It lists common Python keywords like False, True, and, or, not, break, continue, class, def, if, else, for, while, in, is, None, lambda, and return along with code examples. It also covers basic data types like Boolean, integer, float, string, list, set, dictionary, and complex data types like classes. It provides examples of using lists, sets, dictionaries, classes and functions in Python.
This document provides examples and descriptions of Python keywords and basic data types. It discusses keywords like False, True, and, or, not, break, continue, class, def, if, elif, else, for, while, in, is, None, lambda, and return. It also covers basic data types like integers, floats, strings, lists, sets, dictionaries, and Boolean values. It provides code examples to demonstrate the usage of these keywords and data types in Python.
This document provides an introduction and overview of the Python programming language. It outlines the key topics that will be covered in a Python tutorial, including basic data types, variables, control structures, functions, classes and objects, modules and packages, exceptions, files and the standard library. The document also summarizes some of the new features introduced in Python versions 2.0 and 2.1.
This document provides an introduction and overview of the Python programming language. It outlines the key topics that will be covered in a Python tutorial, including basic data types, variables, control structures, functions, classes, exceptions, modules and packages, and the standard library. The document consists of slides from a 2002 presentation on Python given by Guido van Rossum, the creator of Python. It encourages attendees to follow along by downloading and using Python in an 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, container types, variables, control structures, functions, classes, modules, exceptions, and the standard library. It encourages attendees to follow along by downloading and using Python on their laptops. Various versions of Python are recommended and compatibility notes are provided. The document also demonstrates basic interactive use of the Python shell.
This document provides an introduction and overview of the Python programming language. It outlines the key topics that will be covered in a Python tutorial, including basic data types, variables, control structures, functions, classes and objects, modules and packages, exceptions, files and the standard library. The document also summarizes some of the new features introduced in Python versions 2.0 and 2.1.
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, container types, variables, control structures, functions, classes, modules, exceptions, and the standard library. It encourages attendees to follow along by downloading and using Python on their laptops. Various versions of Python are recommended and caveats about specific versions are provided. The document also demonstrates basic interactive use of the Python shell.
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...University of Maribor
Slides from talk presenting:
Aleš Zamuda: Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapter and Networking.
Presentation at IcETRAN 2024 session:
"Inter-Society Networking Panel GRSS/MTT-S/CIS
Panel Session: Promoting Connection and Cooperation"
IEEE Slovenia GRSS
IEEE Serbia and Montenegro MTT-S
IEEE Slovenia CIS
11TH INTERNATIONAL CONFERENCE ON ELECTRICAL, ELECTRONIC AND COMPUTING ENGINEERING
3-6 June 2024, Niš, Serbia
ACEP Magazine edition 4th launched on 05.06.2024Rahul
This document provides information about the third edition of the magazine "Sthapatya" published by the Association of Civil Engineers (Practicing) Aurangabad. It includes messages from current and past presidents of ACEP, memories and photos from past ACEP events, information on life time achievement awards given by ACEP, and a technical article on concrete maintenance, repairs and strengthening. The document highlights activities of ACEP and provides a technical educational article for members.
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesChristina Lin
Traditionally, dealing with real-time data pipelines has involved significant overhead, even for straightforward tasks like data transformation or masking. However, in this talk, we’ll venture into the dynamic realm of WebAssembly (WASM) and discover how it can revolutionize the creation of stateless streaming pipelines within a Kafka (Redpanda) broker. These pipelines are adept at managing low-latency, high-data-volume scenarios.
Literature Review Basics and Understanding Reference Management.pptxDr Ramhari Poudyal
Three-day training on academic research focuses on analytical tools at United Technical College, supported by the University Grant Commission, Nepal. 24-26 May 2024
Using recycled concrete aggregates (RCA) for pavements is crucial to achieving sustainability. Implementing RCA for new pavement can minimize carbon footprint, conserve natural resources, reduce harmful emissions, and lower life cycle costs. Compared to natural aggregate (NA), RCA pavement has fewer comprehensive studies and sustainability assessments.
TIME DIVISION MULTIPLEXING TECHNIQUE FOR COMMUNICATION SYSTEMHODECEDSIET
Time Division Multiplexing (TDM) is a method of transmitting multiple signals over a single communication channel by dividing the signal into many segments, each having a very short duration of time. These time slots are then allocated to different data streams, allowing multiple signals to share the same transmission medium efficiently. TDM is widely used in telecommunications and data communication systems.
### How TDM Works
1. **Time Slots Allocation**: The core principle of TDM is to assign distinct time slots to each signal. During each time slot, the respective signal is transmitted, and then the process repeats cyclically. For example, if there are four signals to be transmitted, the TDM cycle will divide time into four slots, each assigned to one signal.
2. **Synchronization**: Synchronization is crucial in TDM systems to ensure that the signals are correctly aligned with their respective time slots. Both the transmitter and receiver must be synchronized to avoid any overlap or loss of data. This synchronization is typically maintained by a clock signal that ensures time slots are accurately aligned.
3. **Frame Structure**: TDM data is organized into frames, where each frame consists of a set of time slots. Each frame is repeated at regular intervals, ensuring continuous transmission of data streams. The frame structure helps in managing the data streams and maintaining the synchronization between the transmitter and receiver.
4. **Multiplexer and Demultiplexer**: At the transmitting end, a multiplexer combines multiple input signals into a single composite signal by assigning each signal to a specific time slot. At the receiving end, a demultiplexer separates the composite signal back into individual signals based on their respective time slots.
### Types of TDM
1. **Synchronous TDM**: In synchronous TDM, time slots are pre-assigned to each signal, regardless of whether the signal has data to transmit or not. This can lead to inefficiencies if some time slots remain empty due to the absence of data.
2. **Asynchronous TDM (or Statistical TDM)**: Asynchronous TDM addresses the inefficiencies of synchronous TDM by allocating time slots dynamically based on the presence of data. Time slots are assigned only when there is data to transmit, which optimizes the use of the communication channel.
### Applications of TDM
- **Telecommunications**: TDM is extensively used in telecommunication systems, such as in T1 and E1 lines, where multiple telephone calls are transmitted over a single line by assigning each call to a specific time slot.
- **Digital Audio and Video Broadcasting**: TDM is used in broadcasting systems to transmit multiple audio or video streams over a single channel, ensuring efficient use of bandwidth.
- **Computer Networks**: TDM is used in network protocols and systems to manage the transmission of data from multiple sources over a single network medium.
### Advantages of TDM
- **Efficient Use of Bandwidth**: TDM all
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTjpsjournal1
The rivalry between prominent international actors for dominance over Central Asia's hydrocarbon
reserves and the ancient silk trade route, along with China's diplomatic endeavours in the area, has been
referred to as the "New Great Game." This research centres on the power struggle, considering
geopolitical, geostrategic, and geoeconomic variables. Topics including trade, political hegemony, oil
politics, and conventional and nontraditional security are all explored and explained by the researcher.
Using Mackinder's Heartland, Spykman Rimland, and Hegemonic Stability theories, examines China's role
in Central Asia. This study adheres to the empirical epistemological method and has taken care of
objectivity. This study analyze primary and secondary research documents critically to elaborate role of
china’s geo economic outreach in central Asian countries and its future prospect. China is thriving in trade,
pipeline politics, and winning states, according to this study, thanks to important instruments like the
Shanghai Cooperation Organisation and the Belt and Road Economic Initiative. According to this study,
China is seeing significant success in commerce, pipeline politics, and gaining influence on other
governments. This success may be attributed to the effective utilisation of key tools such as the Shanghai
Cooperation Organisation and the Belt and Road Economic Initiative.
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsVictor Morales
K8sGPT is a tool that analyzes and diagnoses Kubernetes clusters. This presentation was used to share the requirements and dependencies to deploy K8sGPT in a local environment.
Batteries -Introduction – Types of Batteries – discharging and charging of battery - characteristics of battery –battery rating- various tests on battery- – Primary battery: silver button cell- Secondary battery :Ni-Cd battery-modern battery: lithium ion battery-maintenance of batteries-choices of batteries for electric vehicle applications.
Fuel Cells: Introduction- importance and classification of fuel cells - description, principle, components, applications of fuel cells: H2-O2 fuel cell, alkaline fuel cell, molten carbonate fuel cell and direct methanol fuel cells.
Introduction- e - waste – definition - sources of e-waste– hazardous substances in e-waste - effects of e-waste on environment and human health- need for e-waste management– e-waste handling rules - waste minimization techniques for managing e-waste – recycling of e-waste - disposal treatment methods of e- waste – mechanism of extraction of precious metal from leaching solution-global Scenario of E-waste – E-waste in India- case studies.
2. 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. 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. 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
◦ By and large they are all mutually compatible
◦ Recommended version: 2.1.1 or 2.2
◦ Oldest version still in widespread use: 1.5.2
◦ Avoid 1.6/1.6.1 if you can
◦ When using 2.0 or 2.1, upgrade to 2.0.1 / 2.1.1
◦ 2.1.2 is coming soon!
Use IDLE if you can
5. 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. 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
◦ In Python 2.2 and beyond, 2**100 does the same thing
◦ 1j**2 -> (-1+0j)
11. 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. Dictionary Details
Keys must be immutable:
◦ numbers, strings, tuples of immutables
◦ these cannot be changed after creation
◦ reason is hashing (fast lookup technique)
◦ not lists or other dictionaries
◦ these types of objects can be changed "in place"
◦ no restrictions on values
Keys will be listed in arbitrary order
◦ again, because of hashing
13. 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. 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. 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. 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. 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)
19. 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. Functions, Procedures
def name(arg1, arg2, ...):
"""documentation""" # optional doc string
statements
return # from procedure
return expression # from function
21. 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
23. 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. 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. 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. 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. 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. Instance Variable Rules
On use via instance (self.x), search order:
◦ (1) instance, (2) class, (3) base classes
◦ this also works for method lookup
On assignment via instance (self.x = ...):
◦ always makes an instance variable
Class variables "default" for instance variables
But...!
◦ mutable class variable: one copy shared by all
◦ mutable instance variable: each instance its own
29. Modules
Collection of stuff in foo.py file
◦ functions, classes, variables
Importing modules:
◦ import re; print re.match("[a-z]+", s)
◦ from re import match; print match("[a-z]+", s)
Import with rename:
◦ import re as regex
◦ from re import match as m
◦ Before Python 2.0:
◦ import re; regex = re; del re
30. Packages
Collection of modules in directory
Must have __init__.py file
May contain subpackages
Import syntax:
◦ from P.Q.M import foo; print foo()
◦ from P.Q import M; print M.foo()
◦ import P.Q.M; print P.Q.M.foo()
◦ import P.Q.M as M; print M.foo() # new
32. Try-finally: Cleanup
f = open(file)
try:
process_file(f)
finally:
f.close() # always executed
print "OK" # executed on success only
33. 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. More on Exceptions
User-defined exceptions
◦ subclass Exception or any other standard exception
Old Python: exceptions can be strings
◦ WATCH OUT: compared by object identity, not ==
Last caught exception info:
◦ sys.exc_info() == (exc_type, exc_value, exc_traceback)
Last uncaught exception (traceback printed):
◦ sys.last_type, sys.last_value, sys.last_traceback
Printing exceptions: traceback module
35. File Objects
f = open(filename[, mode[, buffersize])
◦ mode can be "r", "w", "a" (like C stdio); default "r"
◦ append "b" for text translation mode
◦ append "+" for read/write open
◦ buffersize: 0=unbuffered; 1=line-buffered; buffered
methods:
◦ read([nbytes]), readline(), readlines()
◦ write(string), writelines(list)
◦ seek(pos[, how]), tell()
◦ flush(), close()
◦ fileno()
37. 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. 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
◦ class mydict(dict): …
Fix division operator so 1/2 == 0.5; 1//2 == 0
◦ Requires __future__ statement in Python 2.x
◦ Change will be permanent in Python 3.0