Python Unit 1 Chapter 1
Python Unit 1 Chapter 1
• To run the program, select Run Module from the Run menu (or simply hit function key F5).
• If you have entered the program code correctly, the program should execute as shown in Figure 1-30.
• If, however, you have mistyped part of the program resulting in a syntax error (such as mistyping print), you will get an error
message similar to that in Figure 1-31.
Features of PYTHON Programming:
1. A simple language which is easier to learn:
Python has a very a simple and elegant syntax. It’s much easier to read and write python programs compare to other languages like c,
c++, java and c#.
2. Free and Open Source:
We can freely use and distribute python, even for commercial use. Not only can we use and distribute software’s written in it, we can
even make changes to the python’s source code.
3. Portability:
We can move python programs from one platform to another and run it without any changes. It runs seamlessly on almost all
platforms including windows, Mac OS and LINUX.
4. Extensible and Embeddable:
Suppose an application requires high performance. We can easily combine pieces of c/c++ or other languages programs with python
code.
5. Vast support of libraries:
Python has large collection of in-built functions known as standard library functions. Python also supports various third-party
software like NUMPY(supports for large, multi-dimensional arrays and matrices) and else.
6. Developer Productivity:
Compared to other programming languages, python is a dynamically typed language, which means there is no need to declare
variable explicitly.
EXAMPLE: a=10
b=5
Sum=a+b
Literals/Constants:
What Is a Literal? A literal is a sequence of one or more characters that stands for itself.
Types of Literals:
1. Numeric Literals:
• A numeric literal is a literal containing only the digits 0–9, an optional sign character ( + or - ), and a possible decimal
point. (The letter e is also used in exponential notation, shown in the next subsection). If a numeric literal contains a decimal
point, then it denotes an integer value (e.g., 10) otherwise it denotes a floating-point value , or “ float ” (e.g., 10.24).
Commas are never used in numeric literals .
• Below Figure gives additional examples of numeric literals in Python.
Workout examples:
>>> print('Hello') >>>print('Hello") >>> print('Let's Go')
??? ??? ???
>>>print("Hello") >>>print("Let's Go!') >>>print("Let's go!")
??? ??? ???
The Representation of Character Values:
• Python has means for converting between a character and its encoding. The ord function gives the UTF(Unicode
Transmission Format)-8 (ASCII) encoding of a given character.
• For example, ord('A') is 65.
• The chr function gives the character for a given encoding value, thus chr(65) is 'A'.
num k id(num) k k
Variable Assignment and Keyboard Input:
• The value of a variable can come from the user by use of the input function.
>>>name = input('What is your first name?')
What is your first name? John
• In this case, the variable name is assigned the string 'John'. If the user hit return without entering any value, name would be
assigned to the empty string ('').
• All input is returned by the input function as a string type. For the input of numeric values, the response must be converted to
the appropriate type. Python provides built-in type conversion functions int () and float () are used for this purpose.
line = input('How many credits do you have?')
num_credits = int(line)
line= input('What is your grade point average?')
gpa = float(line)
• Here, the entered number of credits, say '24', is converted to the equivalent integer value, 24, before being assigned to
variable num_credits. For input of the gpa, the entered value, say '3.2', is converted to the equivalent floating-point value,
3.2. Note that the program lines above could be combined as follows,
num_credits = int(input('How many credits do you have? '))
gpa = float(input('What is your grade point average? '))
Identifier:
An identifier is the name used to find a variable, function, class or other objects. All identifiers just obey the following rules:
a. Is a sequence of characters that consists of letter, digits and underscore.
b. Can be of any length
c. Starts with a letter which can be either lower/upper case
d. Can start with an underscore ‘_’
e. Cannot start with a digit
f. Cannot be a keyword.
Some examples of identifiers:
Keywords and Other Predefined Identifiers in Python:
• A keyword is an identifier that has predefined meaning in a programming language. Therefore, keywords cannot be used as
“regular” identifiers. Doing so will result in a syntax error
>>>and = 10 Syntax Error: invalid syntax
• The keywords in Python are listed in Figure. To display the keywords, type help() in the Python shell, and then type
keywords (type 'q' to quit).
• Note that numeric strings can also be converted to a numeric type. In fact, we have already been doing this when using int or
float with the input function,
num_credits = int(input('How many credits do you have? '))
Control Structures:
Control structure importance
Boolean expressions
Selection control and iterative control
Control structures:
What Is a Control Structure?
Control flow is the order that instructions are executed in a program. A control statement is a statement that
determines the control flow of a set of instructions i.e it decides the sequence of in which the instruction in a program are to be
executed. A control statement can either comprise of one or more instructions. Three fundamental forms of control in
programming are sequential, selection and iterative control.
Sequential control is an implicit form of control in which instructions are executed in the order that they are written.
A program consisting of only sequential control is referred to as a “straight-line program.”
Selection control is provided by a control statement that selectively executes instructions, while iterative control is
provided by an iterative control statement that repeatedly executes instructions. Each is based on a given condition.
Collectively a set of instructions and the control statements controlling their execution is called a control structure .
The three forms of control are shown below:
• Relational expressions are a type of Boolean expression, since they evaluate to a Boolean result. These operators not only apply
to numeric values, but to any set of values that has an ordering, such as strings.
• Note the use of the comparison operator , = = , for determining if two values are equal. This, rather than the (single) equal sign,
= , is used since the equal sign is used as the assignment operator. This is often a source of confusion for new programmers,
num = 10 variable num is assigned the value 10
num = = 10 variable num is compared to the value 10
Also, ! = is used for inequality simply because there is no keyboard character for the # symbol.
String values are ordered based on their character encoding, which normally follows a lexographical
( dictionary ) ordering . For example, 'Alan' is less than 'Brenda' since the Unicode (ASCII) value for 'A' is 65,
and 'B' is 66. However, 'alan' is greater than (comes after ) 'Brenda' since the Unicode encoding of lowercase
letters (97, 98, . . .) comes after the encoding of uppercase letters (65, 66, . . .).
EXAMPLES:
>>>10 == 20 >>>'2' < '9' >>>'Hello' == "Hello"
??? ??? ???
>>>10 != 20 >>>'12' < '9‘ >>>'Hello' < 'Zebra'
??? ??? ???
>>>10 <= 20 >>>'12' > '9‘ >>>'hello‘< 'ZEBRA'
??? ??? ???
2. Membership Operators:
Python provides a convenient pair of membership operators . These operators can be used to easily determine if a
particular value occurs within a specified list of values. The membership operators are given in Figure.
The in operator is used to determine if a specific value is in a given list, returning True if found, and False otherwise.
The not in operator returns the opposite result. The list of values surrounded by matching parentheses in the figure are called
tuples in Python.
• The membership operators can also be used to check if a given string occurs within another string ,
>>> 'Dr.' in 'Dr. Madison‘ --- True
• As with the relational operators, the membership operators can be used to construct Boolean expressions.
3. Boolean Operators:
George Boole, in the mid-1800s, developed what we now call Boolean algebra . His goal was to develop an algebra
based on true/false rather than numerical values. Boolean algebra contains a set of Boolean ( logical ) operators , denoted by
and, or, and not in Python. These logical operators can be used to construct arbitrarily complex Boolean expressions. The
Boolean operators are shown in Figure.
Logical and is true only when both its operands are true—otherwise, it is false. Logical or is true when either or both
of its operands are true, and thus false only when both operands are false. Logical not simply reverses truth values—not False
equals True, and not True equals False.
For example, in mathematics, to denote that a value is within a certain range is written as
1 <=num <= 10
This expression does not make sense. Let’s assume that num has the value 15. The expression would then be
evaluated as follows,
1 <= num <= 10 ➝ 1 <= 15 <= 10 ➝ True <=10 ➝ ?!?
It does not make sense to check if True is less than or equal to 10. The correct way of denoting the condition is by use
of the Boolean and operator,
1 <=5 num and num <= 10
In some languages (such as Python), Boolean values True and False have integer values 1 and 0, respectively.
So the above expression can be written as follows:
1<=num<=10 1<=15<=10 True <=10 1<=10 True
This would not be the correct result for this expression, however. Let’s see what we get when we do evaluate this
expression in the Python shell,
>>> num = 15
>>> 1 <=num <= 10
False
Note: Boolean literals True and false are never be quoted.
4. Operator Precedence and Boolean Expressions:
Operator precedence also applies to Boolean operators. Since Boolean expressions can contain arithmetic as well as
relational and Boolean operators, the precedence of all operators needs to be collectively applied. An updated operator
precedence table is given in Figure.
• As before, in the table, higher-priority operators are placed above lower-priority ones. Thus, we see that all arithmetic
operators are performed before any relational or Boolean operator ,
In addition, all of the relational operators are performed before any Boolean operator,
And as with arithmetic operators, Boolean operators have various levels of precedence. Unary Boolean operator not has higher
precedence than and, and Boolean operator and has higher precedence than or.
As with arithmetic expressions, it is good programming practice to use parentheses, even if not needed, to add clarity and
enhance readability. Thus, the above expressions would be better written by denoting at least some of the subexpressions,
The if statement may include 1 statement or n statements enclosed within the if block. First the test expression is evaluated. If
the test expression is TRUE, the statement of if block are executed, otherwise these statements will be skipped and the
execution will jump to statement x.
Note: A header in python is a specific keyword followed by a colon. In the figure above, the if statement has a header i.e “if
test_expression:” having keyword if. The group of statements following a header is called suite/block. After the header all
instructions are intended at the same level. While four spaces is commonly used for each level of indentation, any of no of
spaces may be used.
EXAMPLES:
1. Program to implement a number if it is positive 2. Program to determine whether a person is eligible to vote
A header in Python is a specific keyword followed by a colon. In the figure, the if-else statement contains two
headers, “if which == 'F':” containing keyword if, and “else:” consisting only of the keyword else. Headers that are part of the
same compound statement must be indented the same amount—otherwise, a syntax error will result.
Basic LOOP Structures/Iterative Statements:
Python supports basic loop structures through iterative statements. Iterative statements are decision control
statements that are used to repeat the execution of a list of statements. Python language supports two types of iterative
statements they are while loop and for loop.
1. While loop:
The while loop provides a mechanism to repeat one or more statements while a particular condition is True. Below
figure shows the syntax and general form of representation of a while loop. Note in the while loop, the condition is tested
before any of the statements in the statement block is executed. If the condition is True, only then the statements will be
executed otherwise if the condition if False, the control will jump to statement y. that is the immediate statement outside the
while loop block.
A while loop is also referred to as a top-checking loop since control condition is placed as the first line of the code. If the
control condition evaluates to False, then the statements enclosed in the loop are never executed.
EXAMPLE:
1. Program to print 10 no’s using a while loop 2. Program to calculate the sum and average of first 10 no’s
3. Program to print 20Horizontal asterisks(*) 4. Program to calculate the sum of no’s from m to n
2. For Loop:
Like the while loop, the for loo provides a mechanism to repeat a task until a particular condition is true. The for loop
is usually known as a determinate or definite loop because the programmer knows exactly how many times the loop will repeat.
The number of times the loop has to be executed can be determined mathematically checking the logic of the loop.
The for … in statement is a looping statement used in python to iterate over a sequence of objects ie. Go through
each item in a sequence in a for loop can be given as in below figure:
When a for loop is used, a range of sequence is specified (only one). The items of the sequence are assigned to the
loop control variable one after the other. The for loop is executed for each item in the sequence. With every iteration of the
loop, a check is made to identify whether the loop control variable has been assigned all the values in the range. If all the
values have been assigned, the statement block of the loop is executed else the comprising statement block of the for loop are
skipped and the control jumps to the immediate statement following the for loop body.
Every iteration of the loop must make the loop control variable closer to the end of the range. So with every iteration,
the loop variable must be updated. Updating the loop variable makes it point to the next item in the sequence.
The range() Function:
The range() function in python is used to iterate over a sequence of number. The syntax is as:
The range() function produces a sequence of numbers starting with beginning and ending with one less than the number end.
The step argument is optional. By default every number in the range is incremented by 1 but we can specify a different using
step. It can be both negative and positive, but not zero.
EXAMPLE: Program to print n no’s using the range() in a for loop
Key points to be remember:
Input Error Checking: The while statement is well suited for input error checking in a program.
• Infinite loops: An infinite loop is an iterative control structure that never terminates (or eventually terminates with a system
error). Infinite loops are generally the result of programming errors. For example, if the condition of a while loop can never be
false, an infinite loop will result when executed.
• Such infinite loops can cause a program to “hang,” that is, to be
unresponsive to the user. In such cases, the program must be
terminated by use of some special keyboard input (such as ctrl-C) to interrupt the execution.
EXAMPLE:
while True:
print(‘looping’)
Definite vs. Indefinite Loops:
• A definite loop is a program loop in which the number of times the loop will iterate can be determined before the loop is
executed.
• An indefinite loop is a program loop in which the number of times that the loop will iterate cannot be determined before the
loop is executed.
The Break Statement:
The break statement is used to terminate the execution of the nearest enclosing loop in which it appears. The break
statement is widely used with for loop and while loop. While compiler encounters a break statement, the control passes to the
statement that follows the loop in which the break statement appears. Syntax: break.
EXAMPLE: