CSE Python R20
CSE Python R20
Introduction of Python
Python is a free, open-source programming language. Python is also a cross-platform
compatible language.
So, what does this mean?
It means you can install and run Python on several operating systems. Whether you have a
Windows, Mac, or Linux, you can rest assured that Python will work on all these operating systems.
Python is also a great visualization tool. It provides libraries such as Matplotlib, Seaborn, and bokeh to
create stunning visualizations.
Python is the most popular language for Machine learning and deep Learning.
Why Python?
If you compare Python with any other language, for example, C or Java or C++, then you will find that
its syntax is a way lot easier. You also don’t have to worry about the missing semicolons (;) in the end!
Suppose we want to print “Welcome to the world of programming” on our screen. Let’s compare the
syntax for C and Python:
C Syntax:
#include<stdio.h>
int main(){
printf(“Welcome to the world of programming”);
}
Python Syntax:
So here we see that Python code consists of only one line, but for Java, there are multiple lines of code
just for printing a statement.
Features of Python
1. Easy
Easy to CodePython is very easy to code as compared to other popular languages like Java
and C++
Easy to Readbeing a high-level language, Python code is quite like English. Looking at it, you
can tell what the code is supposed to do. Also, since it is dynamically-typed, it mandates
indentation. This aids readability.
2. Expressive First, let’s learn what expressiveness is. Suppose we have two languages A and B,
and all programs that can be made in A can be made in B using local transformations.
However, there are some programs that can be made in B, but not in A, using local
transformations. Then, B is said to be more expressive than A.
Python provides us with a myriad of constructs that help us focus on the solution rather than on
the syntax. This is one of the outstanding python features that tell you why you should learn
Python.
3. Free and Open-SourceFirstly, Python is freely available. You can download it from the Python
Official Website (https://python.org).
Secondly, it is open-source. This means that its source code is available to the public. You can
download it, change it, use it, and distribute it.
This is called FLOSS(Free/Libre and Open Source Software).
5. PortableLet’s assume you’ve written a Python code for your Windows machine. Now, if you
want to run it on a Mac or Ubuntu, you don’t need to make changes to it for the same. In other
words, you can take one code and run it on any machine. This makes Python a portable language.
However, you must avoid any system-dependent features in this case.
6. Interpretedif you’re familiar with any languages like C++ or Java, you must first compile it, and
then run it. But in Python, there is no need to compile it. Internally, its source code is converted
into an immediate form called bytecode. So, all you need to do is to run your Python code without
worrying about linking to libraries, and a few other things.
By interpreted, we mean the source code is executed line by line, and not all at once. Because of
this, it is easier to debug your code. Also, interpreting makes it just slightly slower than Java, but
that does not matter compared to the benefits it offers.
7. Object-OrientedA programming language that can model the real world is said to be object-
oriented. It focuses on objects and combines data and functions. Contrarily, a procedure-oriented
language revolves around functions, which are code that can be reused. Python supports both
procedure-oriented and object-oriented programming which is one of the key python features. It
9. Embeddablewe just saw that we can put code in other languages in our Python source code.
However, it is also possible to put our Python code in a source code in a different language like C++.
This allows us to integrate scripting capabilities into our program of the other language.
10. Large Standard LibraryPython downloads with a large library that you can use so you don’t
have to write your own code for every single thing. There are libraries for regular expressions,
documentation-generation, unit-testing, web browsers, threading, databases, CGI, email, image
manipulation, and a lot of other functionality.
11. GUI Programming Software is not user-friendly until its GUI is made. A user can easily interact
with the software with a GUI. Python offers various libraries for making Graphical user interface for
your applications. For this, you can use Tkinter, wxPython or JPython. These toolkits allow you for
easy and fast development of GUI.
12. Dynamically TypedPython is dynamically-typed. This means that the type for a value is decided
at runtime, not in advance. This is why we don’t need to specify the type of data while declaring it.
>>>print(123123123123123123123123123123123123123123123123+1)
123123123123123123123123123123123123123123123124
Python interprets a sequence of decimal digits without any prefix to be a decimal number:
>>>print(10)
10
The following strings can be prepended to an integer value to indicate a base other than 10:
Complex Numbers
Complex Numbers are specified as <real part>+<imaginary part>j. For example:
Floating-point Numbers
The float type in Python designates a floating-point number. float values are specified with a
decimal point
Almost all platforms represent Python float values as 64-bit “double-precision” values, according to
the IEEE 754 standard. In that case, the maximum value a floating-point number can have is
approximately 1.8 ⨉ 10308. Python will indicate a number greater than that by the string inf:
The closest a nonzero number can be to zero is approximately 5.0 ⨉ 10-324. Anything closer to zero
than that is effectively zero:
You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}). A
colon (:) separates each key from its associated value:
Sets:
Set is collection of elements or group of elements. Python’s built-in set type has the following
characteristics:
Sets are unordered.
Set elements are unique. Duplicate elements are not allowed.
A set itself may be modified, but the elements contained in the set must be of an immutable
type.
A set can be created in two ways. First, you can define a set with the built-in set() function:
>>>X = set(<iter>)
Strings are also iterable, so a string can be passed to set() as well. You have already seen that list(s)
generates a list of the characters in the string s. Similarly, set(s) generates a set of the characters in s:
Thus, the sets shown above can also be defined like this:
A set can be empty. However, recall that Python interprets empty curly braces ({}) as an empty
dictionary, so the only way to define an empty set is with the set() function:
You might think the most intuitive sets would contain similar objects—for example, even numbers or
surnames:
>>>s1={2,4,6,8,10}
>>>s2={'Smith','McArthur','Wilson','Johansson'}
>>>x={42,'foo',3.14159,None}
>>>x
{None, 'foo', 42, 3.14159}
>>>x={42,'foo',(1,2,3),3.14159}
>>>x
{42, 'foo', 3.14159, (1, 2, 3)}
But lists and dictionaries are mutable, so they can’t be set elements:
Sequence type:
Sequence type is collection elements in linear way. The Sequence type are classified into three group
Strings:
Strings are sequences of character data. The string type in Python is called str.
String literals may be delimited using either single or double quotes. All the characters between the
opening delimiter and matching closing delimiter are part of the string:
>>>print("I am a string.")
I am a string.
>>>type("I am a string.")
<class 'str'>
>>>print('I am too.')
I am too.
>>>type('I am too.')
<class 'str'>
>>>''
''
What if you want to include a quote character as part of the string itself? Your first impulse might be to
try something like this:
Sometimes, you want Python to interpret a character or sequence of characters within a string
differently. This may occur in one of two ways:
You may want to suppress the special interpretation that certain characters are usually given
within a string.
You may want to apply special interpretation to characters in a string which would normally be
taken literally.
You can accomplish this using a backslash (\) character. A backslash character in a string indicates that
one or more characters that follow it should be treated specially.
The following is a table of escape sequences which cause Python to suppress the usual special
interpretation of a character in a string:
>>>print('a
SyntaxError: EOL while scanning string literal
>>>print('a\
... b\
... c')
abc
>>>print('foo\\bar')
foo\bar
>>>print('foo\tbar')
foo bar
Examples:
>>>print("a\tb")
a b
>>>print("a\141\x61")
aaa
>>>print("a\nb")
a
b
>>>print('\u2192 \N{rightwards arrow}')
→ →
>>>print('foo\nbar')
foo
bar
>>>print(r'foo\nbar')
foo\nbar
>>>print('foo\\bar')
foo\bar
>>>print(R'foo\\bar')
foo\\bar
>>>print('''This string has a single (') and a double (") quote.''')
This string has a single (') and a double (") quote.
>>>print("""This is a
string that spans
across several lines""")
This is a
string that spans
across several lines
List:
Lists are used to store multiple items in a single variable. Lists are a very useful variable type in
Python. A list can contain a series of values. List variables are declared by using brackets [
] following the variable name.
>>>a=['foo','bar','baz','qux']
>>>b=['baz','qux','bar','foo']
>>>a==b
False
>>>aisb
False
>>>[1,2,3,4]==[4,1,3,2]
False
>>>a=[2,4,6,8]
>>>a
[2, 4, 6, 8]
>>>a=[21.42,'foobar',3,4,'bark',False,3.14159]
>>>a
[21.42, 'foobar', 3, 4, 'bark', False, 3.14159]
>>>int
<class 'int'>
>>>len
<built-in function len>
>>>deffoo():
... pass
...
>>>foo
<function foo at 0x035B9030>
>>>importmath
>>>math
<module 'math' (built-in)>
>>>a=[int,len,foo,math]
>>>a
[<class 'int'>, <built-in function len>, <function foo at 0x02CA2618>,
>>>a=['foo']
>>>a
['foo']
>>>a=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
... 21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
... 41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,
... 61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,
... 81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100]
>>>a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58,
59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96,
97, 98, 99, 100]
>>>a=['bark','meow','woof','bark','cheep','bark']
>>>a
['bark', 'meow', 'woof', 'bark', 'cheep', 'bark']
>>>a[0]
'foo'
>>>a[2]
'baz'
>>>a[5]
'corge'
>>>a[-1]
'corge'
>>>a[-2]
'quux'
>>>a[-5]
'bar'
>>>a=['foo','bar','baz','qux','quux','corge']
>>>a[2:5]
['baz', 'qux', 'quux']
Both positive and negative indices can be specified:
>>>a[-5:-2]
['bar', 'baz', 'qux']
>>>a[1:4]
['bar', 'baz', 'qux']
>>>a[-5:-2]==a[1:4]
True
Omitting the first index starts the slice at the beginning of the list, and omitting the
second index extends the slice to the end of the list:
>>>print(a[:4],a[0:4])
['foo', 'bar', 'baz', 'qux'] ['foo', 'bar', 'baz', 'qux']
>>>print(a[2:],a[2:len(a)])
['baz', 'qux', 'quux', 'corge'] ['baz', 'qux', 'quux', 'corge']
>>>a[:4]+a[4:]
['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>>a[:4]+a[4:]==a
True
You can specify a stride—either positive or negative:
>>>a[0:6:2]
['foo', 'baz', 'quux']
>>>a[1:6:2]
['bar', 'qux', 'corge']
>>>a[6:0:-2]
['corge', 'qux', 'bar']
>>>a[::-1]
['corge', 'quux', 'qux', 'baz', 'bar', 'foo']
The [:] syntax works for lists.
>>>s='foobar'
>>>s[:]
'foobar'
>>>s[:]iss
True
>>>a=['foo','bar','baz','qux','quux','corge']
>>>a[:]
['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>>a[:]isa
False
>>>a
['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>>'qux'ina
True
>>>'thud'notina
True
The concatenation (+) and replication (*) operators:
>>>a
['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>>a+['grault','garply']
['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'grault', 'garply']
>>>a*2
['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'foo', 'bar', 'baz',
'qux', 'quux', 'corge']
The len(), min(), and max() functions:
>>>a
['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>>len(a)
6
>>>min(a)
'bar'
>>>max(a)
'qux'
To define matrix
MyTable variable is a two-dimensional array :
MyTable = [[], []]
Tuple:
Tuples are a group of values like a list and are manipulated in similar ways. But, tuples are fixed in
size once they are assigned. In Python the fixed size is considered immutable as compared to a
list that is dynamic and mutable. Tuples are defined by parenthesis ().
print(myGroup)
>>>t=('spam','egg','bacon','tomato','ham','lobster')
>>>t
('spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster')
>>>type(t)
<class 'tuple'>
>>>t[0]
'spam'
>>>t[-1]
'lobster'
>>>t[3:6]
('tomato', 'ham', 'lobster')
>>>t[1:4]
('egg', 'bacon', 'tomato')
>>>t[0:6:2]
('spam', 'bacon', 'ham')
>>>t[::-1]
('lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam')
>>>t
('spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster')
>>>t[2]
'bacon'
>>>t[2]='butter'
Traceback (most recent call last):
File "<input>", line 1, in <module>
t[2]='butter'
TypeError: 'tuple' object does not support item assignment
>>>a='spam'
>>>b=42
>>>a,3.14159,b
('spam', 3.14159, 42)
>>>t=()
>>>type(t)
<class 'tuple'>
>>>t
()
>>>t=(1,2)
>>>type(t)
<class 'tuple'>
>>>t=(2)
>>>t
2
>>>type(t)
<class 'int'>
>>>t=(2,)
>>>type(t)
<class 'tuple'>
>>>t
(2,)
Operators in Python
In Python, operators are special symbols that designate that some sort of computation should be
performed. The values that an operator acts on are called operands.
Here is an example:
A sequence of operands and operators, like a + b - 5, is called an expression. Python supports many
operators for combining data objects into expressions. These are explored below.
Arithmetic Operators
The following table lists the arithmetic operators supported by Python:
Comparison Operators
Logical Operators
The logical operators not, or, and and modify and join together expressions evaluated in Boolean
context to create more complex conditions.
Interpretation of logical expressions involving not, or, and and is straightforward when the operands
are Boolean:
If x is not x is
“truthy” False
“falsy” True
>>>x=0.0
>>>bool(x)
False
>>>notx
True
False
>>>f(1)andf(0.0)andf(2)andf(3)
->f(1) = 1
->f(0.0) = 0.0
0.0
Another idiom involves selecting a default value when a specified value is zero or empty. For example,
suppose you want to assign a variable s to the value contained in another variable called string. But if
string is empty, you want to supply a default value.
s=stringor'<default_value>'
>>>string='foo bar'
>>>s=stringor'<default_value>'
>>>s
'foo bar'
Chained Comparisons
Comparison operators can be chained together to arbitrary length. For example, the following
expressions are nearly equivalent:
x<y<=z
x<yandy<=z
x<f()<=z# Here f() is a user function
x<f()andf()<=z
Bitwise Operators
Bitwise operators treat operands as sequences of binary digits and operate on them bit by bit. The
following operators are supported:
Operator Exam Meaning Result
ple
& a & b bitwise AND Each bit position in the result is the
logical AND of the bits in the corresponding
position of the operands. (1 if both are 1,
otherwise 0.)
| a | b bitwise OR Each bit position in the result is the logical OR of
Identity Operators
Python provides two operators, is and is not, that determine whether the given operands have the
same identity—that is, refer to the same object. This is not the same thing as equality, which means
the two operands refer to objects that contain the same data but are not necessarily the same object.
Here is an example of two objects that are equal but not identical:
>>>x=1001
>>>y=1000+1
>>>print(x,y)
1001 1001
>>>x==y
True
>>>xisy
False
Here, x and y both refer to objects whose value is 1001. They are equal. But they do not reference the
same object, as you can verify:
>>>id(x)
60307920
>>>id(y)
60307936
Operator Precedence
Here is the order of precedence of the Python operators you have seen so far, from lowest to highest:
Description
Operator
lowest Or Boolean OR
precedence
And Boolean AND
Not Boolean NOT
==, !=, <, <=, >, >=, is, is comparisons, identity
not
| bitwise OR
^ bitwise XOR
& bitwise AND
<<, >> bit shifts
+, - addition, subtraction
*, /, //, % multiplication, division, floor division, modulo
+x, -x, ~x unary positive, unary negation, bitwise
negation
highest ** Exponentiation
precedence
>>>2*3**4*5# Here ** is work like as power operator i.e.3 power of 4
810
Programs often need to read data from the user, usually by way of input from the keyboard. One way
to accomplish this in Python is with input() function:
Syntax:
input([<prompt>])
Example:
>>>user_input=input()
foo bar baz
>>>user_input
'foo bar baz'
If you include the optional <prompt> argument, then input() displays it as a prompt so that your user
knows what to input:
In addition to obtaining data from the user, a program will also usually need to present data back to
the user. You can display program data to the console in Python with print().
To display objects to the console, pass them as a comma-separated list of arguments to print().
By default, print() separates objects by a single space and appends a newline to the end of the output:
>>>first_name="Winston"
>>>last_name="Smith"
>>>print("Name:",first_name,last_name)
Name: Winston Smith
print() takes a few additional arguments that provide modest control over the format of the output.
Each of these is a special type of argument called a keyword argument.
>>>print("foo",42,"bar")
foo 42 bar
>>>print("foo",42,"bar",sep="/")
foo/42/bar
>>>print("foo",42,"bar",sep="...")
foo...42...bar
>>>d={"foo":1,"bar":2,"baz":3}
>>>fork,vind.items():
... print(k,v,sep=" -> ")
...
foo -> 1
bar -> 2
baz -> 3
>>>fornumberinrange(10):
... print(number)
0
1
2
3
4
5
6
7
8
9
>>>fornumberinrange(10):
... print(number,end=(" "ifnumber<9else"\n"))
...
0 1 2 3 4 5 6 7 8 9
>>>name=input("What is your name? ")
What is your name? Winston
>>>age=int(input("How old are you? "))
How old are you? 24
>>>print(name)
Winston
>>>print(age)
24
Conditional Statements
In Python, condition statements act
depending on whether a given condition
is true or false. You can execute
different blocks of codes depending on
the outcome of a condition. Condition
statements always evaluate to either
True or False.
Iterative Statement
Iteration means executing the same block of code over and over, potentially many times. A
programming structure that implements iteration is called a loop.
With indefinite iteration, the number of times the loop is executed isn’t specified explicitly in
advance. Rather, the designated block is executed repeatedly as long as some condition is met.
With definite iteration, the number of times the designated block will be executed is specified
explicitly at the time the loop starts.
while<expr>:
<statement(s)>
<statement(s)> represents the block to be repeatedly executed, often referred to as the body of the
loop
The controlling expression, <expr>, typically involves one or more variables that are initialized prior to
starting the loop and then modified somewhere in the loop body.
When a while loop is encountered, <expr> is first evaluated in Boolean context. If it is true, the loop
body is executed. Then <expr> is checked again, and if still true, the body is executed again. This
continues until <expr> becomes false, at which point program execution proceeds to the first
statement beyond the loop body.
Example1:
>>>n=5
>>>whilen>0:
n-=1
print(n)
4
3
2
1
0
Example2:
>>>n=0
>>>whilen>0:
... n-=1
... print(n)
In the example above, when the loop is encountered, n is 0. The controlling expression n > 0 is
already false, so the loop body never executes.
Here’s another while loop involving a list, rather than a numeric comparison:
>>>a=['foo','bar','baz']
>>>whilea:
... print(a.pop(-1))
...
baz
bar
foo
The distinction between break and continue is demonstrated in the following diagram:
n=5
whilen>0:
n-=1
ifn==2:
break
print(n)
print('Loop ended.')
C:\Users\john\Documents>python break.py
4
3
Loop ended.
When n becomes 2, the break statement is executed. The loop is terminated completely, and program
execution jumps to the print() statement on line 7.
n=5
whilen>0:
n-=1
ifn==2:
continue
print(n)
print('Loop ended.')
C:\Users\john\Documents>python continue.py
4
3
1
0
Loop ended.
while<expr>:
<statement(s)>
else:
<additional_statement(s)>
The <additional_statement(s)> specified in the else clause will be executed when the while loop
terminates.
You could accomplish the same thing by putting those statements immediately after the while loop,
without the else:
while<expr>:
<statement(s)>
<additional_statement(s)>
Example2:
>>>n=5
>>>whilen>0:
... n-=1
... print(n)
... ifn==2:
... break
... else:
... print('Loop done.')
...
4
3
2
Example3:
>>>a=['foo','bar','baz','qux']
>>>s='corge'
>>>i=0
>>>whilei<len(a):
... ifa[i]==s:
... # Processing for item found
... break
... i+=1
... else:
Infinite Loops
Suppose you write a while loop that theoretically never ends. Sounds weird, right?
>>>whileTrue:
... print('foo')
...
foo
foo
foo
.
.
.
foo
foo
foo
KeyboardInterrupt
Traceback (most recent call last):
File "<pyshell#2>", line 2, in <module>
print('foo')
Here’s another variant of the loop shown above that successively removes items from a list using
.pop() until it is empty:
Example:
>>>a=['foo','bar','baz']
>>>whileTrue:
... ifnota:
... break
... print(a.pop(-1))
...
baz
bar
foo
When a becomes empty, not a becomes true, and the break statement exits the loop.
In general, Python control structures can be nested within one another. For
example, if/elif/else conditional statements can be nested:
ifage<18:
ifgender=='M':
print('son')
else:
print('daughter')
elifage>=18andage<65:
ifgender=='M':
print('father')
else:
print('mother')
else:
ifgender=='M':
print('grandfather')
else:
print('grandmother')
>>>a=['foo','bar']
>>>whilelen(a):
... print(a.pop(0))
... b=['baz','qux']
... whilelen(b):
... print('>',b.pop(0))
...
foo
>baz
>qux
bar
>baz
>qux
A break or continue statement found within nested loops applies to the nearest enclosing loop:
while<expr1>:
statement
statement
while<expr2>:
statement
statement
break# Applies to while <expr2>: loop
break# Applies to while <expr1>: loop
Additionally, while loops can be nested inside if/elif/else statements, and vice versa:
Syntax1:
if<expr>:
statement
while<expr>:
statement
statement
else:
while<expr>:
statement
statement
statement
In fact, all the Python control structures can be intermingled with one another to whatever extent you
need.
This only works with simple statements though. You can’t combine two compound statements into one
line. Thus, you can specify a while loop all on one line as above, and you write an if statement on one
line:
>>>ifTrue:print('foo')
Foo
range(stop)
But you can define the starting number of the sequence and then step size.
x =list(range(1,101))
print(x)
...
1,2,3,…………….100
i=range(0,100,10):
... print(i)
...
0, 10, 20, 30, 40, 50, 60, 70, 80, 90
fori=1to10
<loopbody>
Here, the body of the loop is executed ten times. The variable i assumes the value 1 on the first
iteration, 2 on the second, and so on. This sort of for loop is used in the languages BASIC, Algol, and
Pascal.
Another form of for loop popularized by the C programming language contains three parts:
* An initialization
* An expression specifying an ending condition
* An action to be performed at the end of each iteration.
for(i=1;i<=10;i++)
<loopbody>
for<var>in<iterable>:
<statement(s)> [
<iterable> is
a collection of objects—for example, a list or tuple. The <statement(s)> in the loop
body are denoted by indentation, as with all Python control structures, and are executed
once for each item in <iterable>. The loop variable <var> takes on the value of the next
element in <iterable> each time through the loop.
Iterables
In Python, iterable means an object can be used in iteration. The term is used as:
If an object is iterable, it can be passed to the built-in Python function iter(), which returns something
called an iterator
Each of the objects in the following example is an iterable and returns some type of iterator when
passed to iter():
>>>iter('foobar')# String
<str_iterator object at 0x036E2750>
>>>iter(['foo','bar','baz'])# List
<list_iterator object at 0x036E27D0>
>>>iter(('foo','bar','baz'))# Tuple
<tuple_iterator object at 0x036E27F0>
>>>iter({'foo','bar','baz'})# Set
<set_iterator object at 0x036DEA08>
>>>iter({'foo':1,'bar':2,'baz':3})# Dict
<dict_keyiterator object at 0x036DD990>
>>>iter(42)# Integer
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
iter(42)
TypeError: 'int' object is not iterable
>>>iter(3.1)# Float
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
iter(3.1)
TypeError: 'float' object is not iterable
>>>itr=iter(a)
>>>itr
<list_iterator object at 0x031EFD10>
>>>next(itr)
'foo'
>>>next(itr)
'bar'
>>>next(itr)
'baz'
Term Meaning
Iteration The process of looping through the objects or items in a
collection
Iterable An object (or the adjective used to describe an object)
that can be iterated over
Iterator The object that produces successive items or values from
its associated iterable
iter() The built-in function used to obtain an iterator from an
iterable
Now, consider again the simple for loop presented at the start of this tutorial:
>>>a=['foo','bar','baz']
>>>for i in a:
... print(i)
...
foo
bar
baz
This loop can be described entirely in terms of the concepts you have just learned about. To carry out
the iteration this for loop describes, Python does the following:
The loop body is executed once for each item next() returns,
with loop variable i set to the given item for each iteration.
>>>d={'foo':1,'bar':2,'baz':3}
>>>forkind:
... print(k)
...
foo
bar
baz
>>>forkind:
... print(d[k])
...
1
2
3
>>>forvind.values():
... print(v)
...
1
2
3
>>>d.items()
dict_items([('foo', 1), ('bar', 2), ('baz', 3)])
>>>d={'foo':1,'bar':2,'baz':3}
>>>fork,vind.items():
... print('k =',k,', v =',v)
...
k = foo , v = 1
k = bar , v = 2
k = baz , v = 3
>>>fornin(0,1,2,3,4):
... print(n)
...
0
1
2
3
4
returns an iterable that yields integers starting with 0, up to but not
range(<end>)
including <end>:
>>>x=range(5)
>>>x
range(0, 5)
>>>type(x)
<class 'range'>
>>>forninx:
... print(n)
...
0
1
2
3
4
>>>list(x)
[0, 1, 2, 3, 4]
>>>tuple(x)
(0, 1, 2, 3, 4)
>>>list(range(5,20,3))
[5, 8, 11, 14, 17]
>>>list(range(5,10,1))
[5, 6, 7, 8, 9]
>>>list(range(5,10))
[5, 6, 7, 8, 9]
>>>list(range(-5,5))
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
>>>list(range(5,-5))
[]
>>>list(range(5,-5,-1))
[5, 4, 3, 2, 1, 0, -1, -2, -3, -4]
break and continue work the same way with for loops as with while loops. break terminates the loop
completely and proceeds to the first statement following the loop
>>>foriin['foo','bar','baz','qux']:
... if'b'ini:
... break
... print(i)
...
foo
continue terminates the current iteration and proceeds to the next iteration:
>>>foriin['foo','bar','baz','qux']:
... if'b'ini:
... continue
... print(i)
...
foo
qux
A for loop can have an else clause as well. The interpretation is analogous to that of a while loop.
The else clause will be executed if the loop terminates through exhaustion of the iterable:
>>>foriin['foo','bar','baz','qux']:
... print(i)
... else:
... print('Done.')# Will execute
...
foo
bar
baz
qux
Done.
The else clause won’t be executed if the list is broken out of with a break statement:
>>>foriin['foo','bar','baz','qux']:
... ifi=='bar':
... break
... print(i)
... else:
... print('Done.')# Will not execute
...
foo
String Methods
Dictionary Methods
List Methods