Professional Documents
Culture Documents
Unit 1
Programs and Programming
• A program is a set of instructions.
• When you write down directions to your house for a
friend, you are writing a program. Your friend “executes”
that program by following each instruction in turn.
• Every program is written in terms of a few basic operations
that its reader already understands. For example, the set
of operations that your friend can understand might
include the following: “Turn left at Darwin Street,” “Go
forward three blocks,” and “If you get to the gas station,
turn around—you’ve gone too far.”
• Computers are similar but have a different set of
operations. Some operations are mathematical,
like “Add 10 to a number and take the square
root,” while others include “Read a line from the
file named data.txt,” “Make a pixel blue,” or
“Send email to the authors of this book.
• The most important difference between a
computer and an oldfashioned calculator is that
you can “teach” a computer new operations by
defining them in terms of old ones
• For example, you can teach the computer that
“Take the average” means “Add up the numbers
in a set and divide by the set’s size.”
• Defining new operations, and combining
them to do useful things, is the heart and
soul of programming
Prof. Jeannette Wing wrote computational
thinking is about the following:
• • Conceptualizing, not programming. Computer science is not
computer programming. Thinking like a computer scientist
means more than being able to program a computer. It
requires thinking at multiple levels of abstraction. •
• A way that humans, not computers, think. Computational
thinking is a way humans solve problems; it is not trying to get
humans to think like computers. Computers are dull and boring;
humans are clever and imaginative. We humans make
computers exciting. Equipped with computing devices, we use
our cleverness to tackle problems we would not dare take on
before the age of computing and build systems with
functionality limited only by our imaginations.
• • For everyone, everywhere. Computational thinking will be a
reality when it is so integral to human endeavors it disappears as
an explicit philosophy.
We choose Python for several reasons:
Interpreter
Compiler
● high-level program is called the source code, and the translated
program is called the object code or the executable.
● Once a program is compiled, you can execute it repeatedly without
further translation.
● There are two ways to use the interpreter: interactive mode and
script mode.
● In interactive mode, you type Python programs and the interpreter
displays the result:
● The chevron, >>> , is the prompt the interpreter uses to indicate that it
is ready.
● Alternatively, you can store code in a file and use the interpreter to
execute the contents of the file, which is called a script.
● By convention, Python scripts have names that end with “.py”
● To execute the script, you have to tell the interpreter the name of the file.
● If you have a script named “hello.py” and you are working in a UNIX
command window, you type “$python hello.py” .
● In other development environments, the details of executing scripts are
different.
History of Python
• Python was developed by Guido van Rossum in the late
eighties and early nineties at the National Research Institute
for Mathematics and Computer Science in the Netherlands.
• Python is derived from many other languages, including
ABC, Modula-3, C, C++,Algol-68, SmallTalk, Unix shell, and
other scripting languages.
• Python is copyrighted. Like Perl, Python source code is now
available under the GNU General Public License (GPL).
• Python is now maintained by a core development team at
the institute, although Guido van Rossum still holds a vital
role in directing its progress.
Python Features
• Easy-to-learn: Python has few keywords,
simple structure, and a clearly defined syntax.
This allows the student to pick up the
language quickly.
• Easy-to-read: Python code is more clearly
defined and visible to the eyes.
• Easy-to-maintain: Python's source code is
fairly easy-to-maintain.
• A broad standard library: Python's bulk of the library is
very portable and cross-platform compatible on UNIX,
Windows, and Macintosh.
• Interactive Mode: Python has support for an
interactive mode which allows interactive testing and
debugging of snippets of code.
• Portable: Python can run on a wide variety of
hardware platforms and has the same interface on all
platforms.
• Extendable: You can add low-level modules to the
Python interpreter. These modules enable programmers
to add to or customize their tools to be more efficient.
• Databases: Python provides interfaces to all major
commercial databases.
• GUI Programming: Python supports GUI
applications that can be created and ported to
many system calls, libraries, and windows
systems, such as Windows MFC, Macintosh, and
the X Window system of Unix.
• Scalable: Python provides a better structure and
support for large programs than shell scripting.
Installing Python(Windows)
• 1. Open a Web browser and go to http://www.python.org.
• 2. Click the “Download” link.
• 3. You should see several links here, with names such as
“Python 2.4” and “Python 2.4Windows installer”. Click the
“Windows installer” link—it should give you the installer file
directly.
• 4. Run the downloaded file by double-clicking it in Windows
Explorer. This brings up the Python install wizard, which is
really easy to use. Just accept the default settings, wait until
the install is finished, and you’re ready to roll!
IDLE (Integrated Development and Learning
Environment)
• Assuming that the installation went well, you now have a
new program in your Windows
• Start menu. Run the Python Integrated Development
Environment (IDLE) by selecting Start ➤Programs ➤ Python2
➤ IDLE (Python GUI).
• If you feel a bit lost, simply select Help ➤ IDLE Help from the
menu, and you get a simple description of the various menu
items and basic usage. For more documentation on IDLE,
check out http://www.python.org/idle.
• If you press F1, or select Help ➤ Python Docs from the
menu, you will get the full Python documentation. (The
document there of most use to you will probably be
the“Library Reference.”) All the documentation is searchable.
The Difference Between Brackets, Braces, and Parentheses:
( ) → Parentheses
[ ] → Brackets
{ } → Braces
● Braces are used for different purposes. If you just want a list to
contain some elements and organize them by index numbers
(starting from 0), just use the [] and add elements as necessary.
● {} are special in that you can give custom id's to values like a =
{"John": 14}. Now, instead of making a list with ages and
remembering whose age is where, you can just access John's age by
a["John"].
● The [ ] is called a list and { } is called a dictionary (in Python).
● Dictionaries are basically a convenient form of list which allow you
to access data in a much easier way.
● ( ) parentheses is used to enclose method parameters; like print
(“hello”)
Values and Types:
Keywords define the language’s rules and structure, and they cannot
be used as variable names. Python has thirty-one keywords:
Built-in Data Types
● In programming, data type is an important concept.
● Variables can store data of different types, and different types can do
different things.
● Since everything is an object in Python programming, data types are
actually classes and variables are instance (object) of these classes.
● Python has the following data types built-in by default, in these categories:
● Text Type: str
● Numeric Types: int, float, complex
● Sequence Types: list, tuple,
● Mapping Type: dict
● Set Types: set
● Boolean Type: bool
Python Numbers
● Integers, floating point numbers and complex numbers fall under Python numbers category.
>>>a = 5
>>>print(a, "is of type", type(a))
>>>a = 2.0
Output
>>>print(a, "is of type", type(a))
5 is of type <class 'int'>
>>>a = 1+2j
2.0 is of type <class 'float'>
print(a, "is complex number?", isinstance(1+2j,complex))
(1+2j) is complex number?
True
● Integers can be of any length, it is only limited by the memory available.
● A floating-point number is accurate up to 15 decimal places. Integer and floating points
● List is an ordered sequence of items. It is one of the most used datatype in Python and is
very flexible. All the items in a list do not need to be of the same type.
● Declaring a list is pretty straight forward. Items separated by commas are enclosed
within brackets [ ].
>>>a = [1, 2, 3]
>>>a[2] = 4
>>>print(a)
[1, 2, 4]
Python Strings
● String is sequence of Unicode characters. We can use single quotes or double quotes to
represent strings. Multi-line strings can be denoted using triple quotes, ''' or """.
string''' A multiline
print(s) string
● Set is an unordered collection of unique items. Set is defined by values separated by comma
>>>a = {5,2,3,1,4}
# printing set variable
Output
>>>print("a = ", a)
a = {1, 2, 3, 4, 5}
# data type of variable a
<class 'set'>
>>>print(type(a))
● Sets have unique values. They eliminate duplicates.
>>>a = {1,2,2,3,3,3}
>>print(a)
Output
{1, 2, 3}
Type conversion:
● Sometimes, you may need to perform conversions between the built-in types. To
convert between types, you simply use the type-name as a function.
● Like int(), float(), str(), etc.
● There are several built-in functions to perform conversion from one data type to
another.
>>> float(5)
5.0
Conversion from float to int will truncate the value (make it closer to zero).
>>> int(10.6)
10
>>> int(-10.6)
-10
-----------------------------------------------------------------------------------------------
>>> float('2.5')
2.5
>>> str(25)
'25'
>>> int('1p')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1p'
---------------------------------------------------------------------
● >>> set([1,2,3])
● {1, 2, 3}
● >>> tuple({5,6,7})
● (5, 6, 7)
● >>> list('hello')
● ['h', 'e', 'l', 'l', 'o']
To convert to dictionary, each element must be a pair:
>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}
• Operators and Operands:
• Operators are special symbols that represent computations like addition and
multiplication. The values the operator uses are called operands.
• Operators are used to perform operations on variables and values.
● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators For example:
● Identity operators >>> 2+3
● Membership operators 5
● Bitwise operators
Here, + is the operator that performs addition. 2
and 3 are the operands and 5 is the output of the
operation.
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication,
etc.
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
Comparison operators
Comparison operators are used to compare values. It returns either True or False according to the condition.
> Greater than - True if left operand is greater than the right x>y
< Less than - True if left operand is less than the right x<y
>= Greater than or equal to - True if left operand is greater than or x >= y
equal to the right
<= Less than or equal to - True if left operand is less than or equal x <= y
to the right
Logical operators
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
is and is not are the identity operators in Python. They are used to check if two values (or variables) are located on the
same part of the memory. Two variables that are equal does not imply that they are identical.
is not True if the operands are not identical (do not refer to x is not
# Output: False
x1 = 5 the same object) True
print(x1 is not y1)
y1 = 5
x2 = 'Hello' # Output: True
y2 = 'Hello' print(x2 is y2)
x3 = [1,2,3]
# Output: False
y3 = [1,2,3]
print(x3 is y3)
Membership operators
in and not in are the membership operators in Python. They are used to test whether a
value or variable is found in a sequence (string, list, tuple, set and dictionary).
In a dictionary we can only test for presence of key, not the value.
# Output: True
print('H' in x)
# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
# Output: False
print('a' in y)
Statements
● 1. abs()
● The abs() is one of the most popular Python built-in functions, which returns
the absolute value of a number. A negative value’s absolute is that value is
positive.
● >>> abs(-7)
● 7
● >>> abs(7)
● 7
● 2. chr()
● chr() Built In function returns the character in python for an ASCII
value.
● >>> chr(65)
● ‘A’
● >>> chr(97)
● ‘a’
● >>> chr(9)
● ‘\t’
● >>> chr(48)
● ‘0’
● 3. float()
● This Python Built In function converts an int or a
compatible value into a float.
● >>> float(2)
● 2.0
● >>> float('3')
● 3.0
● 4. int()
● int() converts a value to an integer.
● >>> int('7')
● 7
● 5. len()
● We’ve seen len() so many times by now. It returns the
length of an object.
● >>> len({1,2,2,3})
● 3
● 6. list()
● list() creates a list from a sequence of values.
● >>> list({1,3,2,2})
● [1, 2, 3]
● 7. max()
● A no-brainer, max() returns the item, in a sequence, with
the highest value of all.
● >>> max(2,3,4)
● 4
● >>> max([3,5,4])
● 5
● 8. min()
● min() returns the lowest value in a sequence.
● >>> min(3,5,1)
● 1
● 9. oct()
● oct() converts an integer to its octal representation.
● >>> oct(7)
● ‘0o7’
● >>> oct(8)
● ‘0o10’
● 10 .pow()
● pow() takes two arguments- say, x and y. It then returns
the value of x to the power of y.
● >>> pow(3,4)
● 81
● >>> pow(7,0)
● 1
● 11. round()
● round() rounds off a float to the given number of digits
(given by the second argument).
● >>> round(3.777,2)
● 3.78
● 12. set()
● Of course, set() returns a set of the items passed to it.
● >>> set([2,2,3,1])
● {1, 2, 3}
● 13. sorted()
● Like we’ve seen before, sorted() prints out a sorted
version of an iterable. It does not, however, alter the
iterable.
● >>> sorted([1,3,2])
● [1, 2, 3]
● 14. str()
● str() takes an argument and returns the string equivalent
of it.
● >>> str('Hello')
● ‘Hello’
● >>> str(7)
● ‘7’
● >>> str(8.7)
● ‘8.7’
● 15. help()
● To get details about any module, keyword, symbol, or
topic, we use the help() function.
●
● 16. dict()
● dict(), as we have seen it, creates a python dictionary.
● >>> dict()
● {}
● >>> dict([(1,2),(3,4)])
● {1: 2, 3: 4}
● 17.complex()
● complex() function creates a complex number. We have
seen this is our article on Python Numbers.
● >>> complex(3)
● (3+0j)
● >>> complex(3.5)
● (3.5+0j)
● >>> complex(3+5j)
● (3+5j)
● 18. bool()
● bool() converts a value to Boolean.
● >>> bool(0.5)
● True
● >>> bool('')
● False
● 19. all()
● The all() function takes a container as an argument. This
Built in Functions returns True if all values in a python
iterable have a Boolean value of True. An empty value
has a Boolean value of False.
● >>> all((1,0,0))
● False
● >>> all((1,1,1))
● True
● 20. any()
● Like all(), it takes one argument and returns True if, even
one value in the iterable has a Boolean value of True.
● >>> any((1,0,0))
● True
Delete Statement
del x
print(x)
● Delete the first item in a list:
● x = ["apple", "banana", "cherry"]
del x[0]
print(x)
● {} Parentheses (grouping)
● f(args…) Function call
● x[index:index] Slicing
● x[index] Subscription
● x.attribute Attribute reference
● ** Exponent
● ~x Bitwise not
● +x, -x Positive, negative
● *, /, % Product, division, remainder
● +, – Addition, subtraction
● <<, >> Shifts left/right
● & Bitwise AND
● ^ Bitwise XOR
● | Bitwise OR
● in, not in, is, is not, <, <=, >, >=,
● <>, !=, == Comparisons, membership, identity
● not x Boolean NOT
● and Boolean AND
● or Boolean OR
● lambda Lambda expression
Comments in Python