Professional Documents
Culture Documents
Module I
When running the print function, Python first evaluates the expression and
then displays its value.
1. print was used to display some text. In Python code, a string is
always enclosed in quotation marks. However, the print function
displays a string without the quotation marks.
Eg: print('Hi there')
2. You can also write a print function that includes two or more
expressions separated by commas. In such a case, the print function
evaluates the expressions and displays their results, separated by
single spaces, on one line.
Eg: print (2+2, "hello")
Input Function
As you create programs in Python, you’ll often want your programs to ask
the user for input. You can do this by using the input function. This function
>>> name
'Soumya V N'
The input function always builds a string from the user’s keystrokes and
returns it to the program. After inputting strings that represent numbers, the
programmer must convert them from strings to the appropriate numeric
types. In Python, there are two type conversion functions for this purpose,
called int (for integers) and float (for floating-point numbers).
Eg: >>> first=int(input("enter the first number: "))
enter the first number: 12
>>> second=int(input("enter the second number: "))
enter the second number: 34
>>> print "the sum is", first+second
the sum is 46
Data Types
When we use data in a computer program, we do need to keep in mind the
type of data we’re using. We also need to keep in mind what we can do with
(what operations can be performed on) particular data.
In programming, a data type consists of a set of values and a set of
operations that can be performed on those values.
A literal is the way a value of a data type looks to a programmer. The
programmer can use a literal in a program to mention a data value.
Integers: the integers include 0, all of the positive whole numbers, and all of the
negative whole numbers. Represented by using ―int‖. The most common
implementation of the int data type in many programming languages consists of
the integers from –2,147,483,648 (–231) to 2,147,483,647 (231 – 1).
Character Sets: In Python, character literals look just like string literals and are of
the string type. But they also belong to several different character sets, among them
the ASCII set and the Unicode set. (The term ASCII stands for American Standard
Code for Information Interchange.) Python’s ord and chr functions convert
characters to their numeric ASCII codes and back again, respectively.
A variable associates a name with a value, making it easy to remember and use the
value later in a program. The rule for naming variables are:
A variable name must begin with either a letter or an underscore ( _).
It can contain any number of letters, digits, or other underscores.
Names, such as if, def, and import, are reserved for other purposes and thus
cannot be used for variable names.
Python programmers typically use lowercase letters for variable names, but in the
case of variable names that consist of more than one word, it’s common to begin
each word in the variable name (except for the first one) with an uppercase letter.
For example, the name interestRate is slightly easier to read than the name
interestrate. Programmers use all uppercase letters for the names of variables that
contain values that the program never changes. Such variables are known as
symbolic constants. Examples of symbolic constants in the tax calculator case
study are TAX_RATE and STANDARD_DEDUCTION.
Variables receive their initial values and can be reset to new values with an
assignment statement. The form of an assignment statement is the following:
The Python interpreter first evaluates the expression on the right side of the
assignment symbol and then binds the variable name on the left side to this value.
When this happens to the variable name for the first time, it is called defining or
initializing the variable. Note that the = symbol means assignment, not equality.
After you initialize a variable, subsequent uses of the variable name in expressions
are known as variable references. When the interpreter encounters a variable
reference in any expression, it looks up the associated value.
Keywords
Keywords are the reserved words in Python.
Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Expressions
Expressions provide an easy way to perform operations on data values to
produce other data values.
When entered at the Python shell prompt, an expression’s operands are
evaluated, and its operator is then applied to these values to compute the
value of the expression.
Type conversion
When working with the input of numbers, you must use a type conversion
function.
A type conversion function is a function with the same name as the data
type to which it converts.
Because the input function returns a string as its value, you must use the
function int or float to convert the string to a number before performing
arithmetic, as in the following example:
>>>radius=float (input ("Enter the radius :"))
Enter the radius: 3.2
>>>3.14*radius**2
32.153600000000004
Note that when the exponent reaches 10, the output of the second column
shifts over by a space and looks ragged. The output would look neater if the
left columns were left-justified and the right columns were right-justified.
The first line of code right-justifies the string by padding it with two spaces
to its left. The next line of code left-justifies by placing two spaces to the
string’s right.
The simplest form of this operation is the following:
This version contains a format string, the format operator %, and a single
data value to be formatted.
The format string can contain string data and other information about the
format of the datum.
To format the string data value in our example, we used the notation
%<field width>s in the format string.
When the field width is positive, the datum is right-justified; when the field
width is negative, you get left-justification.
If the field width is less than or equal to the datum’s print length in
characters, no justification is added.
Example:
The format information for a data value of type float has the form:
The first statement assigns an input value to the variable length. The
next statement attempts to print the value of the variable lenth. Python
responds that this name is not defined.
o To use a resource from a module, you write the name of a module as a qualifier,
followed by a dot (.) and the name of the resource.
o If you are going to use only a couple of a module’s resources frequently, you can
avoid the use of the qualifier with each reference by importing the individual
resources, as follows:
Control Statements:
Statements that allow the computer to select an action to perform in a
particular action or to repeat a set of actions.
Two types of control statements are there:
o Selection structure
o Iteration structure
if-else Statements:
o The if-else statement is the most common type of selection statement.
o It is also called a two-way selection statement, because it directs the
computer to make a choice between two alternative courses of action.
o Here is the Python syntax for the if-else statement:
if statement:
o This type of control statement is also called a one-way selection
statement, because it consists of a condition and just a single sequence
of statements.
o If the condition is True, the sequence of statements is run. Otherwise,
control proceeds to the next statement following the entire selection
statement.
o Here is the syntax for the if statement:
Multi-Way if Statements:
o Occasionally, a program is faced with testing several conditions that
entail more than two alternative courses of action.
o The process of testing several conditions and responding accordingly
can be described in code by a multi-way selection statement.
o The multi-way if statement considers each condition until one
evaluates to True or they all evaluate to False.
o When a condition evaluates to True, the corresponding action is
performed and control skips to the end of the entire selection
statement. If no condition evaluates to True, then the action after the
trailing else is performed.
o The syntax of the multi-way if statement is the following:
Iteration
Also known as loops, which repeat an action.
Each repetition of the action is known as a pass or an iteration.
There are two types of loops
those that repeat an action a predefined number of times (definite
iteration)
those that perform the action until the program determines that it
needs to stop (indefinite iteration).
The for Loop
The control statement that most easily supports definite iteration.
The form of this type of loop is:
The first line of code in a loop is sometimes called the loop header.
integer expression in the header denotes the number of iterations that the
loop performs.
The colon (:) ends the loop header.
Example 3: When Python executes the type of for loop, it actually counts
from 0 to the value of the header’s integer expression minus 1.
To count from an explicit lower bound, the programmer can supply a second
integer expression in the loop header. When two arguments are supplied to
range, the count ranges from the first argument to the second argument
minus 1.
The next code segment uses this variation to simplify the code in the loop
body:
Clearly, something eventually has to happen within the body of the loop to
make the loop’s continuation condition become false. Otherwise, the loop
will continue forever, an error known as an infinite loop. At least one
statement in the body of the loop must update a variable that affects the
value of the condition.
The while loop is also called an entry-control loop, because its condition is
tested at the top of the loop. This implies that the statements within the loop
can execute zero or more times.
Lazy evaluation
*******************
Exercises
1. Describe what happens when the programmer enters the string ―Greetings!‖ in the Python
shell.
2. Write a line of code that prompts the user for his or her name and saves the user’s input
in a variable called name.
3. What is a Python script?
4. Explain what goes on behind the scenes when your computer runs a Python program.
5. Suppose your script attempts to print the value of a variable that has not yet been
assigned a value. How does the Python interpreter react?
6. Miranda has forgotten to complete an arithmetic expression before the end of a line of
code. How will the Python interpreter react?
************************