Mohammad Hassan's document discusses various Python data structures including arrays, tuples, dictionaries, and exceptions. It provides examples of how to define, access, modify, and loop through each type of data structure. Key points covered include using arrays to store multiple values, defining empty and one-element tuples, accessing dictionary values by key, and modifying dictionary contents by adding or removing keys. The document also compares the differences between lists and tuples, and between tuples and dictionaries.
Tuples are similar to lists but are immutable. They use parentheses instead of square brackets and can contain heterogeneous data types. Tuples can be used as keys in dictionaries since they are immutable. Accessing and iterating through tuple elements is like lists but tuples do not allow adding or removing items like lists.
This document contains notes from several coding sessions that cover various Python concepts:
1. Strings are immutable objects, so string functions return new strings rather than modifying the original. Common string functions include lower(), capitalize(), strip(), replace(), split(), and join().
2. Tuples are immutable like strings and are used to store multi-dimensional data like coordinates. They are created with parentheses and can be nested.
3. Lists, strings, and tuples are all examples of sequences that support operations like indexing, slicing, length, and iteration with for loops.
4. Dictionaries are mutable objects that store key-value pairs and are accessed using square bracket notation. They are considered unordered
The document discusses for loops in Python. It explains that for loops are used to iterate over sequences like lists, tuples, and strings. There are two types of for loops: 1) Getting each element of the sequence, and 2) Using the range() function to generate a sequence of numbers to use as indexes. The document provides examples of iterating over lists and strings using for loops, and using break and continue statements to control loop behavior. It also explains how to use the range() function to generate a sequence of numbers for iteration.
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxpriestmanmable
ISTA 130: Lab 2
1 Turtle Review
Here are all of the turtle functions we have utilized so far in this course:
turtle.forward(distance) – Moves the turtle forward in the direction it is currently facing the distance
entered
turtle.backward(distance) – Same as forward but it moves in the opposite direction the turtle is facing
turtle.right(degrees) – Roates the turtle to the right by the degrees enteres
turtle.left(degrees) – Same as right, but it rotates the turtle to the left
turtle.pensize(size) – Adjusts the size of the line left by the turtle to whatever value is entered for size
turtle.home() – Moves the turtle to the default location and faces it to the right
turtle.clear() – Clears all the lines that were left by the turtle in the window.
turtle.penup() – Causes the turtle to stop leaving lines (until pen is placed back down)
turtle.pendown() – Places the pen back down to the turtle can continue leaving lines when forward and
backward are called.
turtle.pencolor(color string) – Changes the color of the lines left by the turtle to whatever color string
entered (so long as Python recognizes it).
turtle.bgcolor(color string) – Changes the background color for the window that the turtle draws in.
turtle.speed(new speed) – Changes the speed at which the turtle moves to whatever newSpeed is.
turtle.clearscreen() – Deletes all drawings and turtles from the screen, leaving it in its initial state
Note that abbreviations also exist for many of these functions; for example:
� turtle.fd(distance)
� turtle.rt(degrees)
� turtle.pu()
1
2 Functions and Parameters
Here is the square function we looked at yesterday:
def square(side_length):
’’’
Draws a square given a numerical side_length
’’’
turtle.forward(side_length)
turtle.right(90)
turtle.forward(side_length)
turtle.right(90)
turtle.forward(side_length)
turtle.right(90)
turtle.forward(side_length)
turtle.right(90)
return
square(50) # This would give side_length the value of 50
square(100) # This would give side_length the value of 100
print side_length # This will give an error because side_length
# only exists inside the function!
Try it out:
(1 pt.) Create a new file called lab02.py. In this file, create a simple function called rhombus. It
will take one parameter, side length. Using this parameter, have your function create a rhombus
using turtle graphics. Call your rhombus function in the script. What happens if you provide no
arguments to the function? Two or three arguments?
Then, modify your rhombus function so it takes another argument for the angle inside the
rhombus.
3 Data types
Python recognizes many different types of values when working with data. These can be numbers,
strings of characters, or even user defined objects. For the time being, however, were only going to
focus on three of the data types:
integer – These are whole numbers, both positive and negative. Examples are 5000, 0, and -25
float – These are numbers that are followed by a decimal poi ...
This document discusses tuples in Python. It defines a tuple as a sequence of immutable values that are indexed numerically. Tuples can contain different data types and are created using parentheses. The document explains how to access tuple elements, check if an item exists in a tuple, find the length of a tuple, and use built-in tuple methods. It also compares the key differences between tuples, lists, and dictionaries in terms of mutability, syntax, and supported operations. Sample Python programs are provided to demonstrate common operations on tuples like creation, accessing elements, unpacking values, and adding/removing items.
The document discusses tuples in Python, including what tuples are, how to create and access them, built-in tuple methods like count() and index(), and the differences between tuples, lists, and dictionaries. Tuples are immutable sequences that are indexed and can contain mixed data types. Common tuple operations include accessing elements, checking if an item exists, finding length, and using built-in methods to count occurrences or find indices of values. Tuples cannot be modified but new tuples can be created from existing ones using operators like addition.
The document discusses different Python data types including lists, tuples, and dictionaries. It provides information on how to create, access, modify, and delete items from each data type. For lists, it covers indexing, slicing, and common list methods. For tuples, it discusses creation, concatenation, slicing, and built-in methods. For dictionaries, it explains how they are created as a collection of unique keys and values, and how to access, add, remove, and delete key-value pairs.
Tuples are similar to lists but are immutable. They use parentheses instead of square brackets and can contain heterogeneous data types. Tuples can be used as keys in dictionaries since they are immutable. Accessing and iterating through tuple elements is like lists but tuples do not allow adding or removing items like lists.
This document contains notes from several coding sessions that cover various Python concepts:
1. Strings are immutable objects, so string functions return new strings rather than modifying the original. Common string functions include lower(), capitalize(), strip(), replace(), split(), and join().
2. Tuples are immutable like strings and are used to store multi-dimensional data like coordinates. They are created with parentheses and can be nested.
3. Lists, strings, and tuples are all examples of sequences that support operations like indexing, slicing, length, and iteration with for loops.
4. Dictionaries are mutable objects that store key-value pairs and are accessed using square bracket notation. They are considered unordered
The document discusses for loops in Python. It explains that for loops are used to iterate over sequences like lists, tuples, and strings. There are two types of for loops: 1) Getting each element of the sequence, and 2) Using the range() function to generate a sequence of numbers to use as indexes. The document provides examples of iterating over lists and strings using for loops, and using break and continue statements to control loop behavior. It also explains how to use the range() function to generate a sequence of numbers for iteration.
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxpriestmanmable
ISTA 130: Lab 2
1 Turtle Review
Here are all of the turtle functions we have utilized so far in this course:
turtle.forward(distance) – Moves the turtle forward in the direction it is currently facing the distance
entered
turtle.backward(distance) – Same as forward but it moves in the opposite direction the turtle is facing
turtle.right(degrees) – Roates the turtle to the right by the degrees enteres
turtle.left(degrees) – Same as right, but it rotates the turtle to the left
turtle.pensize(size) – Adjusts the size of the line left by the turtle to whatever value is entered for size
turtle.home() – Moves the turtle to the default location and faces it to the right
turtle.clear() – Clears all the lines that were left by the turtle in the window.
turtle.penup() – Causes the turtle to stop leaving lines (until pen is placed back down)
turtle.pendown() – Places the pen back down to the turtle can continue leaving lines when forward and
backward are called.
turtle.pencolor(color string) – Changes the color of the lines left by the turtle to whatever color string
entered (so long as Python recognizes it).
turtle.bgcolor(color string) – Changes the background color for the window that the turtle draws in.
turtle.speed(new speed) – Changes the speed at which the turtle moves to whatever newSpeed is.
turtle.clearscreen() – Deletes all drawings and turtles from the screen, leaving it in its initial state
Note that abbreviations also exist for many of these functions; for example:
� turtle.fd(distance)
� turtle.rt(degrees)
� turtle.pu()
1
2 Functions and Parameters
Here is the square function we looked at yesterday:
def square(side_length):
’’’
Draws a square given a numerical side_length
’’’
turtle.forward(side_length)
turtle.right(90)
turtle.forward(side_length)
turtle.right(90)
turtle.forward(side_length)
turtle.right(90)
turtle.forward(side_length)
turtle.right(90)
return
square(50) # This would give side_length the value of 50
square(100) # This would give side_length the value of 100
print side_length # This will give an error because side_length
# only exists inside the function!
Try it out:
(1 pt.) Create a new file called lab02.py. In this file, create a simple function called rhombus. It
will take one parameter, side length. Using this parameter, have your function create a rhombus
using turtle graphics. Call your rhombus function in the script. What happens if you provide no
arguments to the function? Two or three arguments?
Then, modify your rhombus function so it takes another argument for the angle inside the
rhombus.
3 Data types
Python recognizes many different types of values when working with data. These can be numbers,
strings of characters, or even user defined objects. For the time being, however, were only going to
focus on three of the data types:
integer – These are whole numbers, both positive and negative. Examples are 5000, 0, and -25
float – These are numbers that are followed by a decimal poi ...
This document discusses tuples in Python. It defines a tuple as a sequence of immutable values that are indexed numerically. Tuples can contain different data types and are created using parentheses. The document explains how to access tuple elements, check if an item exists in a tuple, find the length of a tuple, and use built-in tuple methods. It also compares the key differences between tuples, lists, and dictionaries in terms of mutability, syntax, and supported operations. Sample Python programs are provided to demonstrate common operations on tuples like creation, accessing elements, unpacking values, and adding/removing items.
The document discusses tuples in Python, including what tuples are, how to create and access them, built-in tuple methods like count() and index(), and the differences between tuples, lists, and dictionaries. Tuples are immutable sequences that are indexed and can contain mixed data types. Common tuple operations include accessing elements, checking if an item exists, finding length, and using built-in methods to count occurrences or find indices of values. Tuples cannot be modified but new tuples can be created from existing ones using operators like addition.
The document discusses different Python data types including lists, tuples, and dictionaries. It provides information on how to create, access, modify, and delete items from each data type. For lists, it covers indexing, slicing, and common list methods. For tuples, it discusses creation, concatenation, slicing, and built-in methods. For dictionaries, it explains how they are created as a collection of unique keys and values, and how to access, add, remove, and delete key-value pairs.
Anton Kasyanov, Introduction to Python, Lecture4Anton Kasyanov
This document provides an introduction and overview of Python lists, tuples, dictionaries, and files. It discusses how lists can contain a grouping of similar items indexed from 0, how tuples are immutable lists, how dictionaries contain key-value pairs, and how to read files line by line in Python. It also assigns as homework to create a basic translation program that uses lists or dictionaries to translate words between two languages using a file-based dictionary.
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptxOut Cast
The document discusses properties and uses of Python lists. Key points include:
- Lists are mutable, ordered, heterogeneous collections that can contain duplicates. They are useful when data needs to change frequently.
- Lists can be created using list() or square brackets. Elements are accessed by index, which can be positive or negative.
- Common list methods include append(), pop(), index(), count(), and sort(). Lists also support slicing, and can be used as stacks.
The document discusses container data types in Python, including lists, tuples, sets, and dictionaries.
Lists allow indexing, slicing, and various methods like append(), insert(), pop(), and sort(). Tuples are like lists but immutable, and have methods like count(), index(), and tuple comprehension. Sets store unique elements and support operations like union and intersection. Dictionaries map keys to values and allow accessing elements via keys along with functions like get() and update().
The lesson covers lists in Python including an introduction to lists, list operations like enumeration and mutability, and challenges using lists like creating a contacts list program and times table application. Various list methods are demonstrated and discussed such as sorting, appending, searching by index, and removing elements from a list. The anatomy and uses of lists in computing and programming are explored.
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docxfaithxdunce63732
The document discusses Python strings, functions, and methods. It provides instructions for a lab exercise on evaluating string expressions and accessing substrings using indexing and slicing. It also introduces various Python data types like strings, lists, and numbers. The document compares Python to C and Java by discussing equivalent operations like variable assignment, data types, string concatenation, slicing, and deletion statements. It categorizes Python as having more flexible data types than C and Java.
The document provides information about Python lists, tuples, sets, and dictionaries. It discusses that lists are ordered, mutable collections that allow duplicate elements. Tuples are ordered and immutable collections that allow duplicate elements. Sets are unordered, immutable collections that do not allow duplicate elements. The document includes examples of built-in methods for each data type like append(), pop(), update(), remove(), etc. It also discusses indexing, slicing, looping and sorting lists as well as unpacking, joining and multiplying tuples.
This document introduces a new data modelling approach and compares it to traditional relational database models. It provides definitions and examples of key concepts in relational modelling like entities, attributes, relations, and constraints. It also demonstrates various ways to represent these constructs in Wolfram Language, including as lists, associations, graphs, and RDF triplets. The goal is to help software developers and data modellers learn the advantages of applying this new method.
This document provides notes on Python lists. It begins by defining lists as sequences that store elements in order and can contain different data types. It reviews basic list syntax like creating lists using brackets, accessing elements using indexes starting from 0, and finding the length of a list using len().
The document then explains that lists are objects stored in memory rather than in variables, and that variables actually store references or pointers to the objects. It provides an example to illustrate how changes made to a list through a function reference are reflected outside the function.
The notes cover how lists are mutable objects, meaning their contents can be changed, and how they have member functions like append() that modify the list. It discusses the concept of mut
The document provides an overview of arrays in Java, including:
- Arrays can hold multiple values of the same type, unlike primitive variables which can only hold one value.
- One-dimensional arrays use a single index, while multi-dimensional arrays use two or more indices.
- Elements in an array are accessed using their index number, starting from 0.
- The size of an array is set when it is declared and cannot be changed, but reference variables can point to different arrays.
- Common operations on arrays include initializing values, accessing elements, looping through elements, and copying arrays.
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docxdonnajames55
COMPLEX AND USER DEFINED TYPES
Please note that the material on this website is not intended to be exhaustive.
This is intended as a summary and supplementary material to required textbook.
INTRODUCTION
Previously we have been dealing with C++ built-in types, that is: types that the language already supports. In addition, all of the types we have been using so far (with two exceptions: string, and the reference type: &) have been simple types. In this module we will begin to look at complex types, sometimes called structured types. Complex types allow the programmer to define their own types, which we will call user defined types.
C++ Built-In Types
Classification
Name
Examples
Can be unsigned?
Simple
Integral
char
yes
"
"
short
yes
"
"
int
yes
"
"
long
yes
"
"
bool
no
"
Enumerated
enum
"
"
Decimal
float
"
"
"
double
"
"
"
long double
"
Address
Pointer
* (asterisk)
"
"
Reference
& (ampersand)
"
Complex
Array
[ ] (brackets)
"
"
Structured
struct
"
"
Union
union
"
"
Abstract
class
"
In this module we will explain enumerations, structures, and unions. In future modules we will cover arrays and classes.
Some classifications above may come as a surprise. How can char be an integral type (and even unsigned), and why is bool considered an integral type?
Characters in C++ are considered 8-bit bytes, and hence they are represented internally as integers in base 2: just 0s and 1s. If you want an integer that only ranges between 0 and 255 (unsigned), or between -128 and 127 (signed), you can use a char. All of the arithmetic operations can be used on char.
A character (char) was originally taken to be one of the symbols on your keyboard, and to represent those only need 7 bits are needed. Extended character sets must use 2 or more bytes to represent characters not on your keyboard (such a representation scheme is known as Unicode), for instance, Cyrillic characters or some mathematic symbols.
We have already seen that the Boolean true and false are really internally represented as 1 and 0, respectively. However, arithmetic operations will not work on bool.
You will also notice that a type we have used repeatedly (string) is not listed above. The strings we have been using are really of type class, which will be introduced another module.
ENUMERATIONS
Enumerated types are user-defined; that is, you get to choose what you want to enumerate. Here are some simple examples:
enum PrimaryColors {RED, YELLOW, BLUE}; enum Days {SUN, MON, YUE, WED, THU, FRI, SAT};
C++ will internally represent these types using 0, 1, 2, 3, .... Notice that the standard convention is to use upper-case alphas in the enumeration, as they are really very similar to constants. You can override the internal defaults with something like the following:
enum PrimaryColors {RED = 5, YELLOW = 10, BLUE = 20};
The default internal representation is often very convenient, as the enumeration symbol strings can then be used as indices of arrays, a future topic.
STRUCT.
The document provides an overview of Python data structures, functions, and recursion. It outlines topics including lists, dictionaries, tuples, sets, functions, recursion, and common errors. The aim is to equip students with a strong foundation in Python programming with a focus on understanding and applying fundamental concepts through programming tasks and examples. Key data structures are explained, such as how to create, access, modify, and delete elements from lists and tuples. Functions are also covered, including defining functions, passing arguments, and common errors.
This document provides an overview of basic Python syntax and data types. It discusses indentation, statements, variables, numbers, strings, lists, tuples, and dictionaries. For each data type, it describes how to define, access, and manipulate objects of that type using various functions and methods. It also provides examples of working with each data type and exercises for hands-on practice. Overall, the document serves as a basic introduction to Python syntax and core data types for new programmers.
A for loop is probably the most common type of loop in Python. A for loop will select items from any iterable. In Python an iterable is any container (list, tuple, set, dictionary), as well as many other important objects such as generator function, generator expressions, the results of builtin functions such as filter, map, range and many other items.
This document discusses tuples and dictionaries in Python. Tuples are immutable sequences that are defined using parentheses, while dictionaries are mutable mappings that associate keys with values. The document provides examples of creating, accessing, iterating over, and modifying tuples and dictionaries using various built-in functions and methods. It also compares the differences between tuples, lists, and dictionaries.
This document provides an overview of key concepts for data science in Python, including popular Python packages like NumPy and Pandas. It introduces Python basics like data types, operators, and functions. It then covers NumPy topics such as arrays, slicing, splitting and reshaping arrays. It discusses Pandas Series and DataFrame data structures. Finally, it covers operations on missing data and combining datasets using merge and join functions.
The document discusses data structures and algorithms. It defines arrays as a series of objects of the same size and type, where each object is an element that can be accessed via an index. Algorithms are described as finite sequences of instructions to solve problems, with analysis of algorithms determining the resources like time and storage required.
This document provides an overview of Python data structures, focusing on lists and tuples. It discusses how lists and tuples store and organize data, how to define, access, update, and manipulate elements within lists and tuples using various Python functions and methods. Lists are described as mutable sequences that can contain elements of different data types, while tuples are described as immutable sequences. The document provides examples of using lists and tuples for tasks like stacks, queues, and storing records. It also covers list and tuple operations like slicing, filtering, mapping, and reducing.
This document discusses various data structures in Python including lists, dictionaries, tuples, sets, and strings. Lists are mutable sequences that can contain heterogeneous data types. Dictionaries are mutable and store key-value pairs with unique keys. Tuples are immutable sequences that can be nested. Sets store unordered and unique elements. Strings are immutable sequences of characters that support slicing, formatting, and other common string operations.
How to Fix the Import Error in the Odoo 17Celine George
An import error occurs when a program fails to import a module or library, disrupting its execution. In languages like Python, this issue arises when the specified module cannot be found or accessed, hindering the program's functionality. Resolving import errors is crucial for maintaining smooth software operation and uninterrupted development processes.
Anton Kasyanov, Introduction to Python, Lecture4Anton Kasyanov
This document provides an introduction and overview of Python lists, tuples, dictionaries, and files. It discusses how lists can contain a grouping of similar items indexed from 0, how tuples are immutable lists, how dictionaries contain key-value pairs, and how to read files line by line in Python. It also assigns as homework to create a basic translation program that uses lists or dictionaries to translate words between two languages using a file-based dictionary.
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptxOut Cast
The document discusses properties and uses of Python lists. Key points include:
- Lists are mutable, ordered, heterogeneous collections that can contain duplicates. They are useful when data needs to change frequently.
- Lists can be created using list() or square brackets. Elements are accessed by index, which can be positive or negative.
- Common list methods include append(), pop(), index(), count(), and sort(). Lists also support slicing, and can be used as stacks.
The document discusses container data types in Python, including lists, tuples, sets, and dictionaries.
Lists allow indexing, slicing, and various methods like append(), insert(), pop(), and sort(). Tuples are like lists but immutable, and have methods like count(), index(), and tuple comprehension. Sets store unique elements and support operations like union and intersection. Dictionaries map keys to values and allow accessing elements via keys along with functions like get() and update().
The lesson covers lists in Python including an introduction to lists, list operations like enumeration and mutability, and challenges using lists like creating a contacts list program and times table application. Various list methods are demonstrated and discussed such as sorting, appending, searching by index, and removing elements from a list. The anatomy and uses of lists in computing and programming are explored.
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docxfaithxdunce63732
The document discusses Python strings, functions, and methods. It provides instructions for a lab exercise on evaluating string expressions and accessing substrings using indexing and slicing. It also introduces various Python data types like strings, lists, and numbers. The document compares Python to C and Java by discussing equivalent operations like variable assignment, data types, string concatenation, slicing, and deletion statements. It categorizes Python as having more flexible data types than C and Java.
The document provides information about Python lists, tuples, sets, and dictionaries. It discusses that lists are ordered, mutable collections that allow duplicate elements. Tuples are ordered and immutable collections that allow duplicate elements. Sets are unordered, immutable collections that do not allow duplicate elements. The document includes examples of built-in methods for each data type like append(), pop(), update(), remove(), etc. It also discusses indexing, slicing, looping and sorting lists as well as unpacking, joining and multiplying tuples.
This document introduces a new data modelling approach and compares it to traditional relational database models. It provides definitions and examples of key concepts in relational modelling like entities, attributes, relations, and constraints. It also demonstrates various ways to represent these constructs in Wolfram Language, including as lists, associations, graphs, and RDF triplets. The goal is to help software developers and data modellers learn the advantages of applying this new method.
This document provides notes on Python lists. It begins by defining lists as sequences that store elements in order and can contain different data types. It reviews basic list syntax like creating lists using brackets, accessing elements using indexes starting from 0, and finding the length of a list using len().
The document then explains that lists are objects stored in memory rather than in variables, and that variables actually store references or pointers to the objects. It provides an example to illustrate how changes made to a list through a function reference are reflected outside the function.
The notes cover how lists are mutable objects, meaning their contents can be changed, and how they have member functions like append() that modify the list. It discusses the concept of mut
The document provides an overview of arrays in Java, including:
- Arrays can hold multiple values of the same type, unlike primitive variables which can only hold one value.
- One-dimensional arrays use a single index, while multi-dimensional arrays use two or more indices.
- Elements in an array are accessed using their index number, starting from 0.
- The size of an array is set when it is declared and cannot be changed, but reference variables can point to different arrays.
- Common operations on arrays include initializing values, accessing elements, looping through elements, and copying arrays.
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docxdonnajames55
COMPLEX AND USER DEFINED TYPES
Please note that the material on this website is not intended to be exhaustive.
This is intended as a summary and supplementary material to required textbook.
INTRODUCTION
Previously we have been dealing with C++ built-in types, that is: types that the language already supports. In addition, all of the types we have been using so far (with two exceptions: string, and the reference type: &) have been simple types. In this module we will begin to look at complex types, sometimes called structured types. Complex types allow the programmer to define their own types, which we will call user defined types.
C++ Built-In Types
Classification
Name
Examples
Can be unsigned?
Simple
Integral
char
yes
"
"
short
yes
"
"
int
yes
"
"
long
yes
"
"
bool
no
"
Enumerated
enum
"
"
Decimal
float
"
"
"
double
"
"
"
long double
"
Address
Pointer
* (asterisk)
"
"
Reference
& (ampersand)
"
Complex
Array
[ ] (brackets)
"
"
Structured
struct
"
"
Union
union
"
"
Abstract
class
"
In this module we will explain enumerations, structures, and unions. In future modules we will cover arrays and classes.
Some classifications above may come as a surprise. How can char be an integral type (and even unsigned), and why is bool considered an integral type?
Characters in C++ are considered 8-bit bytes, and hence they are represented internally as integers in base 2: just 0s and 1s. If you want an integer that only ranges between 0 and 255 (unsigned), or between -128 and 127 (signed), you can use a char. All of the arithmetic operations can be used on char.
A character (char) was originally taken to be one of the symbols on your keyboard, and to represent those only need 7 bits are needed. Extended character sets must use 2 or more bytes to represent characters not on your keyboard (such a representation scheme is known as Unicode), for instance, Cyrillic characters or some mathematic symbols.
We have already seen that the Boolean true and false are really internally represented as 1 and 0, respectively. However, arithmetic operations will not work on bool.
You will also notice that a type we have used repeatedly (string) is not listed above. The strings we have been using are really of type class, which will be introduced another module.
ENUMERATIONS
Enumerated types are user-defined; that is, you get to choose what you want to enumerate. Here are some simple examples:
enum PrimaryColors {RED, YELLOW, BLUE}; enum Days {SUN, MON, YUE, WED, THU, FRI, SAT};
C++ will internally represent these types using 0, 1, 2, 3, .... Notice that the standard convention is to use upper-case alphas in the enumeration, as they are really very similar to constants. You can override the internal defaults with something like the following:
enum PrimaryColors {RED = 5, YELLOW = 10, BLUE = 20};
The default internal representation is often very convenient, as the enumeration symbol strings can then be used as indices of arrays, a future topic.
STRUCT.
The document provides an overview of Python data structures, functions, and recursion. It outlines topics including lists, dictionaries, tuples, sets, functions, recursion, and common errors. The aim is to equip students with a strong foundation in Python programming with a focus on understanding and applying fundamental concepts through programming tasks and examples. Key data structures are explained, such as how to create, access, modify, and delete elements from lists and tuples. Functions are also covered, including defining functions, passing arguments, and common errors.
This document provides an overview of basic Python syntax and data types. It discusses indentation, statements, variables, numbers, strings, lists, tuples, and dictionaries. For each data type, it describes how to define, access, and manipulate objects of that type using various functions and methods. It also provides examples of working with each data type and exercises for hands-on practice. Overall, the document serves as a basic introduction to Python syntax and core data types for new programmers.
A for loop is probably the most common type of loop in Python. A for loop will select items from any iterable. In Python an iterable is any container (list, tuple, set, dictionary), as well as many other important objects such as generator function, generator expressions, the results of builtin functions such as filter, map, range and many other items.
This document discusses tuples and dictionaries in Python. Tuples are immutable sequences that are defined using parentheses, while dictionaries are mutable mappings that associate keys with values. The document provides examples of creating, accessing, iterating over, and modifying tuples and dictionaries using various built-in functions and methods. It also compares the differences between tuples, lists, and dictionaries.
This document provides an overview of key concepts for data science in Python, including popular Python packages like NumPy and Pandas. It introduces Python basics like data types, operators, and functions. It then covers NumPy topics such as arrays, slicing, splitting and reshaping arrays. It discusses Pandas Series and DataFrame data structures. Finally, it covers operations on missing data and combining datasets using merge and join functions.
The document discusses data structures and algorithms. It defines arrays as a series of objects of the same size and type, where each object is an element that can be accessed via an index. Algorithms are described as finite sequences of instructions to solve problems, with analysis of algorithms determining the resources like time and storage required.
This document provides an overview of Python data structures, focusing on lists and tuples. It discusses how lists and tuples store and organize data, how to define, access, update, and manipulate elements within lists and tuples using various Python functions and methods. Lists are described as mutable sequences that can contain elements of different data types, while tuples are described as immutable sequences. The document provides examples of using lists and tuples for tasks like stacks, queues, and storing records. It also covers list and tuple operations like slicing, filtering, mapping, and reducing.
This document discusses various data structures in Python including lists, dictionaries, tuples, sets, and strings. Lists are mutable sequences that can contain heterogeneous data types. Dictionaries are mutable and store key-value pairs with unique keys. Tuples are immutable sequences that can be nested. Sets store unordered and unique elements. Strings are immutable sequences of characters that support slicing, formatting, and other common string operations.
How to Fix the Import Error in the Odoo 17Celine George
An import error occurs when a program fails to import a module or library, disrupting its execution. In languages like Python, this issue arises when the specified module cannot be found or accessed, hindering the program's functionality. Resolving import errors is crucial for maintaining smooth software operation and uninterrupted development processes.
বাংলাদেশের অর্থনৈতিক সমীক্ষা ২০২৪ [Bangladesh Economic Review 2024 Bangla.pdf] কম্পিউটার , ট্যাব ও স্মার্ট ফোন ভার্সন সহ সম্পূর্ণ বাংলা ই-বুক বা pdf বই " সুচিপত্র ...বুকমার্ক মেনু 🔖 ও হাইপার লিংক মেনু 📝👆 যুক্ত ..
আমাদের সবার জন্য খুব খুব গুরুত্বপূর্ণ একটি বই ..বিসিএস, ব্যাংক, ইউনিভার্সিটি ভর্তি ও যে কোন প্রতিযোগিতা মূলক পরীক্ষার জন্য এর খুব ইম্পরট্যান্ট একটি বিষয় ...তাছাড়া বাংলাদেশের সাম্প্রতিক যে কোন ডাটা বা তথ্য এই বইতে পাবেন ...
তাই একজন নাগরিক হিসাবে এই তথ্য গুলো আপনার জানা প্রয়োজন ...।
বিসিএস ও ব্যাংক এর লিখিত পরীক্ষা ...+এছাড়া মাধ্যমিক ও উচ্চমাধ্যমিকের স্টুডেন্টদের জন্য অনেক কাজে আসবে ...
How to Manage Your Lost Opportunities in Odoo 17 CRMCeline George
Odoo 17 CRM allows us to track why we lose sales opportunities with "Lost Reasons." This helps analyze our sales process and identify areas for improvement. Here's how to configure lost reasons in Odoo 17 CRM
Executive Directors Chat Leveraging AI for Diversity, Equity, and InclusionTechSoup
Let’s explore the intersection of technology and equity in the final session of our DEI series. Discover how AI tools, like ChatGPT, can be used to support and enhance your nonprofit's DEI initiatives. Participants will gain insights into practical AI applications and get tips for leveraging technology to advance their DEI goals.
Walmart Business+ and Spark Good for Nonprofits.pdfTechSoup
"Learn about all the ways Walmart supports nonprofit organizations.
You will hear from Liz Willett, the Head of Nonprofits, and hear about what Walmart is doing to help nonprofits, including Walmart Business and Spark Good. Walmart Business+ is a new offer for nonprofits that offers discounts and also streamlines nonprofits order and expense tracking, saving time and money.
The webinar may also give some examples on how nonprofits can best leverage Walmart Business+.
The event will cover the following::
Walmart Business + (https://business.walmart.com/plus) is a new shopping experience for nonprofits, schools, and local business customers that connects an exclusive online shopping experience to stores. Benefits include free delivery and shipping, a 'Spend Analytics” feature, special discounts, deals and tax-exempt shopping.
Special TechSoup offer for a free 180 days membership, and up to $150 in discounts on eligible orders.
Spark Good (walmart.com/sparkgood) is a charitable platform that enables nonprofits to receive donations directly from customers and associates.
Answers about how you can do more with Walmart!"
it describes the bony anatomy including the femoral head , acetabulum, labrum . also discusses the capsule , ligaments . muscle that act on the hip joint and the range of motion are outlined. factors affecting hip joint stability and weight transmission through the joint are summarized.
How to Make a Field Mandatory in Odoo 17Celine George
In Odoo, making a field required can be done through both Python code and XML views. When you set the required attribute to True in Python code, it makes the field required across all views where it's used. Conversely, when you set the required attribute in XML views, it makes the field required only in the context of that particular view.
How to Setup Warehouse & Location in Odoo 17 InventoryCeline George
In this slide, we'll explore how to set up warehouses and locations in Odoo 17 Inventory. This will help us manage our stock effectively, track inventory levels, and streamline warehouse operations.
Strategies for Effective Upskilling is a presentation by Chinwendu Peace in a Your Skill Boost Masterclass organisation by the Excellence Foundation for South Sudan on 08th and 09th June 2024 from 1 PM to 3 PM on each day.
This presentation includes basic of PCOS their pathology and treatment and also Ayurveda correlation of PCOS and Ayurvedic line of treatment mentioned in classics.
The simplified electron and muon model, Oscillating Spacetime: The Foundation...RitikBhardwaj56
Discover the Simplified Electron and Muon Model: A New Wave-Based Approach to Understanding Particles delves into a groundbreaking theory that presents electrons and muons as rotating soliton waves within oscillating spacetime. Geared towards students, researchers, and science buffs, this book breaks down complex ideas into simple explanations. It covers topics such as electron waves, temporal dynamics, and the implications of this model on particle physics. With clear illustrations and easy-to-follow explanations, readers will gain a new outlook on the universe's fundamental nature.
2. Objectives
Arrays;
Sequence Type & Mutability;
Understand the need of Tuples;
Solve problems by using Tuples;
Get clear idea about Tuple functions;
Understand the difference between list, dictionary and
tuples; and
Exceptions
3. Arrays are used to store multiple values in one single variable:
cars = ["Ford", "Volvo", "BMW"]
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:
car1 = "Ford"
car2 = "Volvo"
car3 = "BMW“
what if you want to loop through the cars and find a specific one? And what if
you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the
values by referring to an index number.
ARRAY
4. Access the Elements of an Array
Get the value of the first array item:
cars = ["Ford", "Volvo", "BMW"]
x = cars[0]
print(x)
This will give output:
Ford
5. Modify the value of the first array
Modify the value of the first array item:
cars = ["Ford", "Volvo", "BMW"]
cars[0] = "Toyota"
print(cars)
This will give output:
['Toyota', 'Volvo', 'BMW']
6. The Length of an Array
Use the len() method to return the length of an array (the number of
elements in an array).
Return the number of elements in the cars array:
cars = ["Ford", "Volvo", "BMW"]
x = len(cars)
print(x)
This will give output:
3
The length of an array is always one more than the highest
array index.
7. Looping Array Elements
Print each item in the cars array:
cars = ["Ford", "Volvo", "BMW"]
for x in cars:
print(x)
This will give output:
Ford
Volvo
BMW
8. WHAT IS TUPLE?
A tuple is essentially an immutable list. Below is a list with three
elements and a tuple with three elements:
L = [1,2,3]
t = (1,2,3)
Tuples are enclosed in parentheses, though the parentheses are
actually optional.
Indexing and slicing work the same as with lists.
As with lists, you can get the length of the tuple by using the len
function, and, like lists, tuples have count and index
methods.However, since a tuple is immutable, it does not have any
of the other methods that lists have, like sort or reverse, as those
change the list.
9. Adding Array Elements
You can use the append() method to add an element to an
array.
Add one more element to the cars array:
cars = ["Ford", "Volvo", "BMW"]
cars.append("Honda")
print(cars)
This will give output:
['Ford', 'Volvo', 'BMW', 'Honda']
10. Removing Array Elements
You can use the pop() method to remove an element from the array.
Delete the second element of the cars array:
cars = ["Ford", "Volvo", "BMW"]
cars.pop(1)
print(cars)
This will give output:
['Ford', 'BMW’]
You can also use the remove() method to remove an element from the array.
Delete the element that has the value "Volvo":
cars = ["Ford", "Volvo", "BMW"]
cars.remove("Volvo")
print(cars)
This will give output:
['Ford', 'BMW']
12. Sequence Type & Mutability
A sequence type is a type of data in Python which is
able to store more than one value (or less than one, as a
sequence may be empty), and these values can be
sequentially (hence the name) browsed, element by
element.
As the for loop is a tool especially designed to iterate
through sequences, we can express the definition as: a
sequence is data which can be scanned by
the for loop.
Mutability is a property of any Python data that
describes its readiness to be freely changed during
program execution. There are two kinds of Python
data: mutable and immutable.
13. Mutable data can be freely updated at any time − we call
such an operation in situ.
In situ is a Latin phrase that translates as literally in position.
For example, the following instruction modifies the data in situ:
list.append(1)
Immutable data cannot be modified in this way.
Imagine that a list can only be assigned and read over. You
would be able neither to append an element to it, nor remove
any element from it. This means that appending an element to
the end of the list would require the recreation of the list from
scratch.
You would have to build a completely new list, consisting of the
Sequence Type & Mutability
14. A tuple is a sequence of values, which can be of any type and they
are indexed by integer. Tuples are just like list, but we can’t change
values of tuples in place.
A tuple is an immutable sequence type. It can behave like a list,
but it can't be modified in situ.
The index value of tuple starts from 0.
A tuple consists of a number of values separated by commas.
tuple_1 = (1, 2, 4, 8)
tuple_2 = 1., .5, .25, .125
print(tuple_1)
print(tuple_2)
The output:
(1, 2, 4, 8)
(1.0, 0.5, 0.25, 0.125)
Each tuple element may be of a different type (floating-point,
integer, or any other not-as-yet-introduced kind of data).
WHAT IS TUPLE?
15. CREATING EMPTY TUPLE
It is possible to create an empty tuple – parentheses
are required then:
16. If you want to create a one-element tuple, you have to take
into consideration the fact that, due to syntax reasons (a
tuple has to be distinguishable from an ordinary, single
value), you must end the value with a comma:
one_element_tuple_1 = (1, )
one_element_tuple_2 = 1.,
Removing the commas won't spoil the program in any
syntactical sense, but you will instead get two single
variables, not tuples.
CREATING TUPLE
17. ACCESSING TUPLE
If you want to get the elements of a tuple in order to read
them over, you can use the same conventions to which
you're accustomed while using lists.
The similarities may be misleading − don't try to modify a
tuple's contents! It's not a list!
21. You cannot remove or delete or update items in a
tuple.
Tuples are unchangeable, so you cannot remove
items from it, but you can delete the tuple completely:
NOTE: TUPLES ARE IMMUTABLE
REMOVING A TUPLE
22. Python provides two built-in methods that you can
use on tuples.
1. count() Method
2. index() Method
TUPLE METHODS
23. 1. count() Method
Return the number of times the value appears in the
tuple
Count()
method
returns
total no
times
‘banana’
present in
the given
tuple
TUPLE METHODS
24. What else can tuples do for you?
•the len() function accepts tuples, and returns the
number of elements contained inside;
•the + operator can join tuples together (we've shown
you this already)
•the * operator can multiply tuples, just like lists;
•the in and not in operators work in the same way as in
lists.
25. What else can tuples do for you?
my_tuple = (1, 10, 100)
t1 = my_tuple + (1000, 10000)
t2 = my_tuple * 3
print(len(t2))
print(t1)
print(t2)
print(10 in my_tuple)
print(-10 not in my_tuple)
The output should look
as follows:
9
(1, 10, 100, 1000,
10000)
(1, 10, 100, 1, 10, 100,
1, 10, 100)
True
True
26. •One of the most useful tuple properties is their ability
to appear on the left side of the assignment operator.
• A tuple's elements can be variables, not only literals.
Moreover, they can be expressions if they're on the right side
of the assignment operator.
var = 123
t1 = (1, )
t2 = (2, )
t3 = (3, var)
t1, t2, t3 = t2, t3, t1
print(t1, t2, t3)
What else can tuples do for you?
28. LIST TUPLE
Syntax for list is slightly
different comparing with
tuple
Syntax for tuple is slightly
different comparing with lists
Weekdays=[‘Sun’,’Mon’,
‘wed’,46,67]
type(Weekdays)
class<‘lists’>
twdays = (‘Sun’, ‘mon', ‘tue',
634)
type(twdays)
class<‘tuple’>
List uses [ and ] (square
brackets) to bind the
elements.
Tuple uses rounded brackets(
and ) to bind the elements.
DIFFERENCE BETWEEN LIST AND TUPLE
29. LIST TUPLE
List can be edited once it
is created in python. Lists
are mutable data
structure.
A tuple is a list which one
cannot edit once it is created in
Python code. The tuple is an
immutable data structure
More methods or functions
are associated with lists.
Compare to lists tuples have
Less methods or functions.
DIFFERENCE BETWEEN LIST AND TUPLE
30. Dictionaries
The dictionary is another Python data structure. It's not a
sequence type (but can be easily adapted to sequence processing)
and it is mutable.
Dictionaries are not lists - they don't preserve the order of their
data, as the order is completely meaningless (unlike in real, paper
dictionaries).
In Python 3.6x dictionaries have become ordered collections by
default. Your results may vary depending on what Python version
you're using. The order in which a dictionary stores its data is
completely out of your control, and your expectations.
31. In Python's world, the word you look for is named a key. The word
you get from the dictionary is called a value.
This means that a dictionary is a set of key-value pairs. Note:
•each key must be unique − it's not possible to have more than one
key of the same value;
•a key may be any immutable type of object: it can be a number
(integer or float), or even a string, but not a list;
•a dictionary is not a list − a list contains a set of numbered values,
while a dictionary holds pairs of values;
•the len() function works for dictionaries, too − it returns the number
of key-value elements in the dictionary;
•a dictionary is a one-way tool − if you have an English-French
dictionary, you can look for French equivalents of English terms, but
not vice versa.
Dictionaries
32. How to use a dictionary
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
phone_numbers = {'boss' : 5551234567, 'Suzy' : 22657854310}
empty_dictionary = {}
print(dictionary['cat'])
print(phone_numbers['Suzy’])
Getting a dictionary's value resembles indexing, especially thanks to the brackets
surrounding the key's value.
Note:
•if the key is a string, you have to specify it as a string;
•keys are case-sensitive: 'Suzy' is something different from 'suzy'.
The snippet outputs two lines of text:
chat
5557654321
you mustn't use a non-existent key.
33. Dictionary methods and functions
Can dictionaries be browsed using the for loop, like lists or tuples?
No and yes.
No, because a dictionary is not a sequence type − the for loop is
useless with it.
Yes, because there are simple and very effective tools that can adapt
any dictionary to the for loop requirements (in other words,
building an intermediate link between the dictionary and a temporary
sequence entity).
34. The keys() method
keys(), is possessed by each dictionary. The
method returns an iterable object consisting of all
the keys gathered within the dictionary. Having a
group of keys enables you to access the whole
dictionary in an easy and handy way. dictionary =
{"cat": "chat", "dog": "chien", "horse": "che
val"}
for key in dictionary.keys():
print(key, "->", dictionary[key]
Dictionary methods and functions
35. The items() method
items() method returns tuples (this is the first example where
tuples are something more than just an example of
themselves) where each tuple is a key-value pair.
dictionary =
{"cat": "chat", "dog": "chien", "horse": "cheval"}
for english, french in dictionary.items():
print(english, "->", french)
Note the way in which the tuple has been used as a for loop
variable.
Dictionary methods and functions
36. Modifying and adding values in Dictionary
Assigning a new value to an existing key is simple - as
dictionaries are fully mutable, there are no obstacles to
modifying them.
We're going to replace the value "chat" with "minou", which is
not very accurate, but it will work well with our example.
dictionary =
{"cat": "chat", "dog": "chien", "horse": "cheval"}
dictionary['cat'] = 'minou'
print(dictionary)
The output is:
{'cat': 'minou', 'dog': 'chien', 'horse': 'cheval'}
37. Do you want it sorted? Just enrich the for loop to get such a form:
for key in sorted(dictionary.keys()):
There is also a method called values(), which works similarly
to keys(), but returns values.
Here is a simple example:
dictionary =
{"cat": "chat", "dog": "chien", "horse": "cheval"}
for french in dictionary.values():
print(french)
As the dictionary is not able to automatically find a key for a given
value, the role of this method is rather limited.
Modifying and adding values in Dictionary
38. Adding a new key-value pair to a dictionary is as simple as changing a
value – you only have to assign a value to a new, previously non-
existent key.
Note: this is very different behavior compared to lists, which don't allow
you to assign values to non-existing indices.
Let's add a new pair of words to the dictionary − a bit weird, but still valid:
dictionary =
{"cat": "chat", "dog": "chien", "horse": "cheval"}
dictionary['swan'] = 'cygne'
print(dictionary)
The example outputs:
{'cat': 'chat', 'dog': 'chien', 'horse': 'cheval', 'swan': '
cygne’}
Adding a new key in Dictionary
39. You can also insert an item to a dictionary by using
the update() method, e.g.:
dictionary =
{"cat": "chat", "dog": "chien", "horse": "che
val"}
dictionary.update({"duck": "canard"})
print(dictionary)
Adding a new key in Dictionary
40. Removing a key in Dictionary
Can you guess how to remove a key from a dictionary?
Note: removing a key will always cause the removal of the associated
value. Values cannot exist without their keys.
This is done with the del instruction.
Here's the example:
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
del dictionary['dog']
print(dictionary)
Note: removing a non-existing key causes an error.
The example outputs:
{'cat': 'chat', 'horse': 'cheval’}
41. To remove the last item in a dictionary, you can use
the popitem() method:
dictionary =
{"cat": "chat", "dog": "chien", "horse": "cheval"
}
dictionary.popitem()
print(dictionary) # outputs: {'cat': 'chat',
'dog': 'chien’}
In the older versions of Python, i.e., before 3.6.7,
the popitem() method removes a random item from a
dictionary.
Removing a key in Dictionary
42. TUPLE DICTIONARY
Order is maintained. Ordering is not guaranteed.
They are immutable. Values in a dictionary can be
changed.
They can hold any type,
and types can be mixed.
Every entry has a key and a
value.
DIFFERENCE BETWEEN TUPLE AND
DICTIONARY
Tuples and dictionaries can work together
43. TUPLE DICTIONARY
Elements are accessed via
numeric (zero based)
indices
Elements are accessed using
key's values
There is a difference in
syntax and looks easy to
define tuple
Differ in syntax, looks bit
complicated when compare
with Tuple or lists
DIFFERENCE BETWEEN TUPLE AND
DICTIONARY
44. Python Exceptions Handling
Python provides a very important features to handle any unexpected error in
your Python programs and to add debugging capabilities in them:
Exception Handling: This would be covered in this tutorial.
What is Exception?
An exception is an event, which occurs during the execution of a program,
that disrupts the normal flow of the program's instructions.
In general, when a Python script encounters a situation that it can't cope with,
it raises an exception. An exception is a Python object that represents an
error.
When a Python script raises an exception, it must either handle the exception
immediately otherwise it would terminate and come out.
45. Handling an exception
If you have some suspicious code that may raise an exception, you can
defend your program by placing the suspicious code in a try: block.
After the try: block, include an except: statement, followed by a block of code
which handles the problem as elegantly as possible.
Syntax:
try:
You do your operations here;
......................
except Exception I:
If there is ExceptionI, then execute this block.
except Exception II:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
46. Here are few important points above the above mentioned syntax:
A single try statement can have multiple except statements. This is useful
when the try block contains statements that may throw different types of
exceptions.
You can also provide a generic except clause, which handles any exception.
After the except clause(s), you can include an else-clause. The code in the
else-block executes if the code in the try: block does not raise an exception.
The else-block is a good place for code that does not need the try: block's
protection.
Handling an exception
47. Example:
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception
handling!!")
except IOError: print "Error: can't find file or read
data"
else: print "Written content in the file successfully"
fh.close()
This will produce following result:
Written content in the file successfully
Handling an exception
48. The except clause with no exceptions:
You can also use the except statement with no exceptions defined as follows:
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
This kind of a try-except statement catches all the exceptions that occur. Using this
kind of try-except statement is not considered a good programming practice, though,
because it catches all exceptions but does not make the programmer identify the root
cause of the problem that may occur.
Handling an exception
49. The except clause with multiple exceptions:
You can also use the same except statement to handle multiple
exceptions as follows:
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception
list, then execute this block
.......................
else:
If there is no exception then execute this block.
Handling an exception
50. Standard Exceptions
Here is a list standard Exceptions available in Python: Standard
Exceptions
The try-finally clause:
You can use a finally: block along with a try: block. The finally block
is a place to put any code that must execute, whether the try-block raised an
exception or not. The syntax of the try-finally statement is this:
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Note that you can provide except clause(s), or a finally clause, but
not both. You can not use else clause as well along with a finally clause.
51. Example:
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception
handling!!")
finally:
print "Error: can't find file or read data"
If you do not have permission to open the file in writing mode then this
will produce following result:
Error: can't find file or read data
Standard Exceptions
52. Argument of an Exception
An exception can have an argument, which is a value that gives
additional information about the problem. The contents of the argument vary
by exception. You capture an exception's argument by supplying a variable in
the except clause as follows:
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
If you are writing the code to handle a single exception, you can have a
variable follow the name of the exception in the except statement. If you are
trapping multiple exceptions, you can have a variable follow the tuple of the
exception.
This variable will receive the value of the exception mostly containing the
cause of the exception. The variable can receive a single value or multiple
values in the form of a tuple. This tuple usually contains the error string, the
error number, and an error location.
53. Example:
Following is an example for a single exception:
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain
numbersn", Argument
temp_convert("xyz");
This would produce following result:
The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'
Argument of an Exception
54. Raising an exceptions
You can raise exceptions in several ways by using the raise
statement. The general syntax for the raise statement.
Syntax:
raise [Exception [, args [, traceback]]]
Here Exception is the type of exception (for example, NameError) and
argument is a value for the exception argument. The argument is optional; if
not supplied, the exception argument is None.
The final argument, traceback, is also optional (and rarely used in practice),
and, if present, is the traceback object used for the exception
Example:
def functionName( level ):
if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception
55. Note: In order to catch an exception, an "except" clause must refer to
the same exception thrown either class object or simple string. For
example to capture above exception we must write our except clause
as follows:
try:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here...
Raising an exceptions
56. User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes
from the standard built-in exceptions.
Here is an example related to RuntimeError. Here a class is created that is
subclassed from RuntimeError. This is useful when you need to display more
specific information when an exception is caught.
In the try block, the user-defined exception is raised and caught in the except
block. The variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
So once you defined above class, you can raise your exception as follows:
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args