You are on page 1of 106

INT102

Topics to be Covered
• History of Python

• Introduction to Python programming language

• Introduction to programs and debugging

• Formal and natural language


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, and Unix shell and other
scripting languages
• Python is a great language for the beginner-level programmers and
supports the development of a wide range of applications from
simple text processing to WWW browsers to games
History of Python
VERSIONS OF PYTHON
• Python 1.0 - January 1994
• Python 1.5 - December 31, 1997
• Python 1.6 - September 5, 2000
• Python 2.0 - October 16, 2000
• Python 2.1 - April 17, 2001
• Python 2.2 - December 21, 2001
• Python 2.3 - July 29, 2003
• Python 2.4 - November 30, 2004
• Python 2.5 - September 19, 2006
• Python 2.6 - October 1, 2008
• Python 2.7 - July 3, 2010
History of Python
• Python 3.0 - December 3, 2008
• Python 3.1 - June 27, 2009
• Python 3.2 - February 20, 2011
• Python 3.3 - September 29, 2012
• Python 3.4 - March 16, 2014
• Python 3.5 - September 13, 2015
• Python 3.6- December 23,2016
• Python 3.7- June 27,2018
Introduction of Python programming language
• Python is a powerful high-level, object-oriented programming
language created by Guido van Rossum.
• It has simple easy-to-use syntax, making it the perfect language for
someone trying to learn computer programming for the first time.
• Python is a general-purpose language. It has wide range of
applications from Web development to scientific and mathematical
computing to desktop graphical user Interfaces .
• The syntax of the language is clean and length of the code is relatively
short. It's fun to work in Python because it allows you to think about
the problem rather than focusing on the syntax.
Introduction of Python programming language
Basic Features of Python
• Python is Interpreted − Python is processed at runtime by the interpreter. You do
not need to compile your program before executing it. This is similar to PERL and
PHP.

• Python is Interactive − You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.

• Python is Object-Oriented − Python supports Object-Oriented style or technique


of programming that encapsulates code within objects.

• 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.
Introduction of Python programming language
• 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
Introduction to programs and debugging
•Sequence of instructions that specify how to perform a computation.
•Basic instructions in almost every program:
•Input: Get data from keyboard, or file or some other device.
•Output: Display data on the screen or send data to a file or other device.
•Math: Perform basic mathematical operations like addition and
multiplication.
•Conditional Execution: Check for certain conditions and execute the
appropriate sequence of statements.
•Repetition: Perform some action repeatedly , usually with some variation
Introduction to programs and debugging
What is Debugging?
• Debugging is the routine process of locating and removing computer program
bugs, errors or abnormalities, which is methodically handled by software
programmers via debugging tools. Debugging checks, detects and corrects errors
or bugs to allow proper program operation according to set specifications

• It is a systematic process of spotting and fixing the number of bugs, or defects, in


a piece of software so that the software is behaving as expected.
Introduction to programs and debugging
Types of Errors to be Debug
Errors also known as bugs in the world of programming may occur unwillingly
which may prevent the program to compile and run correctly as per the
expectation of the programmer. Basically there are three types of errors in
programming:
1 Runtime Errors
2 Compile Errors
3 Logical Errors
Runtime Errors- runtime errors are those errors that occur during the execution of
a program and generally occur due to some illegal operation performed in the
program.

e.g. print(radius)

In this example, we forget to define the radius variable. Python knows what you
want it to do, but since no radius has been defined, an error occurs.

Other Examples of some illegal operations that may produce runtime errors are:
Dividing a number by zero
Trying to open a file which is not created
Lack of free memory space
Compile Errors- Compile errors are those errors that occur at the time of
compilation of the program. Compile errors may be further classified as Syntax
Error, Semantic Errors.
Syntax errors:
• As we do more and more programming, we will naturally encounter a lot of errors
(or bugs).
• Causing, understanding, and fixing errors is an important part of programming.
• Python will do its best to run anything that you tell it to run, but if it can't
understand what you're asking, then it won't run the program.
• All the same, Python will try to tell you a little bit of information about what went
wrong, in order to help you try to fix it.
Syntax Errors- When the rules of the c programming language are not followed,
the compiler will show syntax errors.
For example, consider the statement,

print “Gee golly”

In this example, we forget to use the parenthesis that are required by print(...).
Python does not understand what you are trying to do. It will give error.
• A syntax error happens when Python can't understand what you are saying.
A run-time error happens when Python understands what you are saying, but
runs into trouble when following your instructions.

• In English, a syntax error would be like the sentence


Please cat dog monkey

• The grammar of this sentence does not make sense. From the perspective of
English grammar, it is missing a verb (action).
• In English, a run-time error would be like the sentence

Please eat the piano.

• The sentence makes sense from a grammatical perspective — there is a verb and
noun in the right place — so you know what you are being asked to do. But, you
will encounter problems once you start trying to eat the piano.
• This is called a run-time error because it occurs after the program starts running.
Semantic Errors (Logical) -Semantic errors are reported by the compiler when the
statements written in the c program are not meaningful to the compiler.

For example, consider the statement, b+c=a; In the above statement we are trying
to assign value of a in the value obtained by summation of b and c which has no
meaning in programming. The correct statement will be a=b+c;
Logical Errors-Logical errors are the errors in the output of the program. The
presence of logical errors leads to undesired or incorrect output and are caused due
to error in the logic applied in the program to produce the desired output.
• Also, logical errors could not be detected by the compiler, and thus, programmers
has to check the entire coding of a program line by line
• Your program might run without crashing (no syntax or run-time errors), but still
do the wrong thing. For example, perhaps you want a program to calculate
the average of two numbers: the average of x and y is defined as
Why doesn't this program work?
but the program prints 5.0 instead! The error this time has to do with the
"order of operations" in arithmetic. When you write x + y / 2, this has
the same mathematical meaning as x + (y/2) =3 + (4/2) = 3 + 2 =5 .

To fix the problem, the third line of our program should be written
as average = (x + y) / 2, which makes clear to Python that we really
want the value , where we add first and divide afterwards.

Logic errors can be difficult to spot, especially in a longer program, but


as we get better at writing code you will also get better at avoiding logic
errors.
Task 1:
Fix the syntax error in the following program, so that it prints out the sum of all the
numbers from 1 to 10. You can change at most one character.

print(1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 +)
Task 2: Hello Joe
Fix the run-time error in the following program, so that it prints out Hello on the
first line and Joe on the second line. You can change at most two characters

print("Hello")
username = Joe
print(username)
Formal and natural language
• Natural Languages are the languages that people speak, such as English,
Spanish, French. They were not designed by people; they evolved naturally.

• Formal Languages are languages that are designed by people for specific
applications.

• Programming languages are formal languages that have been designed to


express computations.

• Formal languages tend to have strict rules about syntax. For example, 3+3=6
is a syntactically correct mathematical statement, but 3=+6$ is not

• Parsing is a process to figure out what the structure of the sentence is.
Difference between Natural and Formal Languages
Ambiguity:
Natural languages are full of ambiguity.
Formal languages are designed to be nearly or completely unambiguous.
Redundancy: Natural languages are more redundant as compared to formal
languages.
Literalness: Natural languages are full of idiom and metaphor. If I say, “The other
shoe fell," there is probably no shoe and nothing falling.
Formal languages mean exactly what they say.
Variables, Keywords, Expressions,
Statements
Topics to be Covered

• Value and Variables


• Keywords
• Exressions
• Statements
• Operators and order of operations
Value and Variable
• Value is a one of the fundamental thing, that a program manipulates.
• Variable is a name that refers to a value that maybe changed in the
program.
• The assignment statement creates new variables and gives them
values:
• >>> message = “Hi, How are you?"
• >>> m = 15
• >>> pi = 3.1415
Identifiers
• Identifiers are the names that identify the elements such as variables and functions
in a program. All identifiers must obey some rules
1. An identifier is a sequence of characters that consists of letters, digits and
underscores(_).
2. An identifier must start with a letter or an underscore. It cannot start with a
digit.
3. An identifier cannot be a keyword. Keywords, also called reserved words, have
special meanings in Python.
E.g. import is a keyword, which tells the python interpreter to import a module
to the program.
Rules for naming an Identifier
1. An identifier name is any combination of alphabets, digits or
underscores.

2. The first character in the identifier name must be an alphabet or


underscore. It cannot start with a digit.

3. No blanks or special symbol other than an underscore can be used in an


identifier name.

4. Keywords are not allowed to be used as identifiers.


Some Identifiers
Mechanical; both are different
mechanical;
FORMULA1;
engine_1;

Wrong identifiers name


1_engine;
break;
@car-roof;
Variable
• Variables are the names that reference values stored in memory.
• Variable names must be meaningful.
• It contains both numbers and letters, but they have to begin with a letter.
• Case sensitive.
• The underscore (_) character can appear in a name.
• Eg.
– >>> tro o es = " ig parade“ >>> more$ = 1000000
– SyntaxError: invalid syntax SyntaxError: invalid syntax
– >>> lass = "Co puter Progra i g “
>>> radius=10.5
– SyntaxError: invalid syntax Valid variable
Keywords
• Keywords, also called reserved words, have special meanings in Python

• Keywords define the language’s rules and structure and they can’t be
used as variable names.

• Python has twenty-nine keywords.


List of Python Keywords
and def exec if not return

assert delete finally import or try

break elif for in pass while

class else from is print yield

continu except global lambda raise


e
Keywords
Python in its language defines an inbuilt module keyword which
handles certain operations related to keywords. A function
iskeyword() checks if a string is keyword or not. Returns true if a
string is keyword, else returns false.

>>> import keyword


>>> keyword.iskeyword("true")
False
Statements
• A statement is an instruction that the Python interpreter can execute.
• When you type a statement on the command line, Python executes it and displays the
result, if there is one.
• A script usually contains a sequence of statements. If there is more than one
statement, the results appear one at a time as the statements execute.
• The statement for assigning a value to a variable is called an assignment statement.
• In Python, the equal sign(=) is used as the assignment operator.
• Syntax: variable=expression
Evaluating Expressions
• An expression is a combination of values, variables, and operators.
• If you type an expression on the command line, the interpreter evaluates it and
displays the result:
– >>> 1 + 1
– 2
• A value all by itself is considered an expression, and so is a variable.
>>> 17 >>> x=2
17 >>>x
2
Simultaneous Assignments
Python also supports simultaneous assignments like this:
var1,var2…………..,varn=exp1,exp2…………….,expn
>>> a,b,c=4,5,6
>>> a
4
>>> b
5
>>> c
6
Example code
Write a python code to swap two numbers.
>>>X=1
>>>Y=3
>>>Temp=X
>>>X=Y
>>>Y=Temp X=1 before Y=3

Can be written as: after


X=3 Y=1
>>>X=1
>>>Y=3
>>>X,Y=Y,X
Example
What is the maximum possible value of an integer in Python ?
In Python, value of an integer is not restricted by the number of bits
and can expand to the limit of the available memory.
>>> x=10000000000000000000000000000
>>> x
10000000000000000000000000000
Python2 vs. Python3
As a side ote, i P tho , there is o l o e t pe int for all t pe of
i tegers. I P tho .7. there are two separate t pes int whi h is
it a d lo g int that is sa e as int of P tho . , i.e., a store
arbitrarily large numbers.
• x = 10
• print(type(x))
• x = 10000000000000000000000000000000000000000000
• print(type(x))
Python2 vs. Python3

Output in Python 2.7 :


<type 'int'>
<type 'long'>
Output in Python 3 :
<type 'int'>
<type 'int'>
Operators and Operands
• Operators are special symbols that represent computations like
addition and multiplication.
• The values the operator uses are called operands
• When both of the operands are integers, the result must also be an
integer, and by convention, integer division always rounds down.
• +, -, *, /, %, **,//
• ** is used for exponential.
• / is also used for float division
• // is used to integer division
Example
>>>10%3
1
>>>2**3
8
>>> 2/3
0.6666666666666666
>>> 2.0/3
0.6666666666666666
>>> 2.0/3.0
0.6666666666666666
Example
>>> 10/3
3.33333
>>> 10//3
3
>>> 2//3
0
>>> 2.0//3
0.0
>>> 2.0//10.0
0.0
Order of Operations
• When more than one operator appears in an expression, the order of evaluation depends on the rules
of precedence.
– Parentheses have the highest precedence and can be used to force an expression to evaluate in the
order you want.

– Exponentiation has the next highest precedence.

– Multiplication ,Float Division, Integer Division and remainder have the same precedence, which
is higher than Addition and Subtraction, which also have the same precedence.

– Operators with the same precedence are evaluated from left to right.
Task 1: determine the final values of all variables at the end of the program.

first = 2
second = 3
third = first * second
second = third - first
first = first + second + third
third = second * first
Task 2: What is the value of x after these commands execute?

x = 10
x=x+x
x=x-5
Operations on Strings
• the + operator represents concatenation.
• For Example:
– fruit = "banana"
– akedGood = " ut read
– print (fruit + bakedGood)
• The * operator also works on strings; it performs repetition.
• For eg:
– "Fun"*3 is "FunFunFun"
Composition
• One of the most useful features of programming languages is their
ability to take small building blocks and compose them

Comments
• It is a good idea to add notes to your programs to explain in natural
language what the program is doing. These notes are called comments.
• they are marked with the # symbol:
•For eg:
# compute the percentage of the hour that has elapsed
percentage = (minute * 100) / 60
Questions ??
Solved Exercise

Q1. There are 5280 feet in a mile. Write a Python statement that
calculates and prints the number of feet in 13 miles

Python Code:
>>> feetInMiles=5280 #storing value in variable
>>> feetIn13Miles=feetInMiles*13 #calculating feet and storing in variable
>>> feetIn13Miles #type variable to check the result
68640 #result
Solved Exercise
Q2. Write a Python statement that calculates and prints the number of
seconds in 7 hours, 21 minutes and 37 seconds.
>>> hrs=7 #storing value in variable1
>>> mins=21 #storing value in variable2
>>> sec=37 #storing value in variable3
>>> TotalSec=(hrs*60*60)+(mins*60)+sec #calculation statement
>>> TotalSec # type variable to check the result
26497 #result
Practice Programs
Q3. Write a Python statement that calculates and prints the area in
inches of a rectangle with length and breadth as 4 and 7 inches.
Q4. The circumference of a circle is 2πr where r is the radius of the
circle. Write a Python statement that calculates and prints the
circumference in inches of a circle whose radius is 8 inches. Assume that
the constant π=3.14.
Q5. Write a single Python statement that combines the three strings
"My name is", "Joe" and "Warren" (plus a couple of other small strings)
into one larger string "My name is Joe Warren." and prints the result.
Q1. There are 5280 feet in a mile. Write a Python statement that calculates
and prints the number of feet in 13 miles.
Q2. Write a Python statement that calculates and prints the number of seconds in 7
hours, 21 minutes and 37 seconds.
Q3. Write a Python statement that calculates and prints the area in inches of a
rectangle with length and breadth as 4 and 7 inches.
Q4. The circumference of a circle is 2πr where r is the radius of the circle. Write a
Python statement that calculates and prints the circumference in inches of a circle
whose radius is 8 inches. Assume that the constant π=3.14.
Q5. Write a single Python statement that combines the three strings "My name is",
"Joe" and "Warren" (plus a couple of other small strings) into one larger string "My
name is Joe Warren." and prints the result.
INT102
Conditionals
and
Iterations
The modulus operator

• The modulus operator works on integers (and integer expressions)


and yields the remainder when the first operand is divided by the
second.
• In Python, the modulus operator is a percent sign (%).
Example
• The syntax is the same as for other operators:
>>> quotient = 7 / 3
>>> print uotie t
2
>>> remainder = 7 % 3
>>> print e ai de
1
• So 7 divided by 3 is 2 with 1 left over.
Uses

• Check whether one number is divisible by another if x % y is zero,


then x is divisible by y.
• you can extract the right-most digit or digits from a number.
• For example,
x % 10 yields the right-most digit of x (in base 10). Similarly x % 100
yields the last two digits.
Boolean expressions

• A Boolean expression is an expression that is either true or false.


• One way to write a Boolean expression is to use the operator ==,
which compares two values and produces a Boolean value:
>>> 5 == 5
True
>>> 5 == 6
False
• True and False are special values that are built into Python.
Boolean expressions examples

• import random
• n1=random.randint(1,9)
• n2=random.randint(1,9)
• ans=eval(input("What is "+str(n1)+" + "+str(n2)+" "))
• print("Your ans is ",n1+n2==ans)
• Print(int(true))
Displays 1
• Print(int(false))
Displays 0
• Print(bool(0))
Displays false
• Print(bool(4))
Displays true
Comparison Operators

• x != y # x is not equal to y
• x>y # x is greater than y
• x<y # x is less than y
• x >= y x=<y # x is greater than or equal to y
• x <= y # x is less than or equal to y
NOTE: = is a assig e t ope ato a d == is a o pa iso ope ato .
Also, there is no such thing as =< or =>.
Logical operators

• There are three logical operators:


 and,
 or
 not
• For example, x > 0 and x < 10 is true only if x is greater than 0 and less
than 10.
• n%2 == 0 or n%3 == 0
• not(x > y) is true if (x > y) is false, that is, if x is less than or equal to y.
Logical operators example

• Print(bool(5>0 and 4>0))


• Displays true
• Print(bool(5>0 and 4<0))
• Displays false
• Print(bool(5>0 or 4>0))
• Displays true
• Print(bool(5>0 or 4<0))
• Displays true
Logical operators example

• X=true
• Y=false
• Pi t a d is , a d #output: false
• Pi t o is , o #output: t ue
• Pi t ot is , ot #output: false


Identity operators

• Identity operators compare the memory locations of two objects.


There are two Identity operators as explained below
Bitwise Operators
Membership Operators
Continue…

• Any nonzero number is interpreted as true."


>>> x = 5
>>> x and 1
1
>>> y = 0
>>> y and 1
0
• Q1. WAP to read the marks of 5 subjects through keyboard. Find out
the aggregate and percentage of marks obtained by the student.
Assume maximum marks that can be obtained by a student in each
subject as 100.
• Q2. WAP to read a four digit number through keyboard and calculate
the sum of its digits.
• Q3. Read a distance in meters and a time in seconds through the
keyboard. WAP to calculate the speed of a car in meter/second.
Keyboard Input
• input(): built in function to get data from keyboard.
• Takes data in the form of string.
• Eg:
>>> input1 = input ()
What are you waiting for?
>>> print input1
What are you waiting for?
• Before calling input, it is a good idea to print a message telling the user
what to input. This message is called a prompt.
• A prompt can be supplied as an argument to input.
• Eg:
>>> name = input ("What...is your name? ")
What...is your name? Arthur, King of the Britons!
>>> print name
Arthur, King of the Britons!
• If we expect the response to be an integer, then type conversion needs
to be done.
• Eg:
prompt = "What is the airspeed velocity of an unladen swallow?"
speed =int(input(prompt))
Conditional Execution

• To write useful programs we need the ability to check conditions and


change the behaviour of the program accordingly.
• Different conditional statements in python are:
– IF
– IF ---Else (Alternative Execution)
– IF--- ELIF---- ELSE (Chained Conditionals)
– Nested Conditionals
If Condition
• If x > 0:
p i t " is positi e
• The Boolean expression after the if statement is called the condition. If
it is true, then the indented statement gets executed. If not, nothing
happens.
• Structure of If
– HEADER:
FIRST STATEMENT
...
LAST STATEMENT
If Condition
• There is no limit on the number of statements that can appear in the
body of an if statement, but there has to be at least one.
• Occasionally, it is useful to have a body with no statements (usually as a
place keeper for code you haven't written yet). In that case, you can use
the pass statement, which does nothing.
If Condition example

• If a > 0:
p i t a is positi e
Alternative Execution
• A second form of the if statement is alternative execution, in which
there are two possibilities and the condition determines which one gets
executed.
• Eg:
if x%2 == 0:
p i t , "is e e
else:
p i t , "is odd
• The alternatives are called branches.
If else Condition example

• r=eval(input("Enter input "))


• if(r<0):
• print("Wrong input")
• else:
• print("true value")

Continue….

• Since the condition must be true or false, exactly one of the


alternatives will be executed. The alternatives are called branches,
because they are branches in the flow of execution.
Chained Conditionals
• Sometimes there are more than two possibilities and we need more
than two branches.
if x < y:
print x, "is less than", y
elif x > y:
print x, "is greater than", y
else:
print x, "and", y, "are e ual
NOTE: There is no limit of the number of elif statements, but the last
branch has to be an else statement
Nested conditionals
• One conditional can also be nested within another.
if x == y:
print x, "and", y, "are equal"
else:
if x < y:
print x, "is less than", y
else:
print x, "is greater than", y
if 0 < x and x < 10:
p i t " is a positi e si gle digit.

• Python provides an alternative syntax that is similar to mathematical


notation:
if 0 < x < 10:
print "x is a positive single digit."
Shortcuts for Conditions
• Numeric value 0 is treated as False
• Empty sequence "", [] is treated as False
• Everything else is True
if m%n:
(m,n) = (n,m%n)
else:
gcd = n
Wrapping of IF-ELSE into one function.
• Function is a block of code that performs a specific function.
• I p tho , fu tio is defi ed ke o d def .
• For example:
def printParity(x):
if x%2 == 0:
print x, "is even"
else:
print x, "is odd
• For any value of x, printParity displays an appropriate message. When
you call it, you can provide any integer expression as an argument.
Example

>>> printParity(17)
17 is odd
>>> y = 17
>>> printParity(y+1)
18 is even
Example
Calling of function depending upon input enter by user:
Example:
if choice == 'A':
functionA()
elif choice == 'B':
functionB()
elif choice == 'C':
functionC()
else:
print "Invalid choice."
Avoid Nested If

• For example, We can rewrite the following code using a single


conditional:
if 0 < x:
if x < 10:
print "x is a positive single digit.
Better way:
if 0 < x and x < 10:
print "x is a positive single digit."
Q1. WAP to find even and odd numbers
Q2. WAP to find whether number is a prime number or not.
Q3. Write a Python program to check whether an alphabet is a
vowel or consonant.
Q4. Write a Python program to check a triangle is equilateral,
isosceles or scalene.
Note :An equilateral triangle is a triangle in which all three
sides are equal.
A scalene triangle is a triangle that has three unequal sides.
An isosceles triangle is a triangle with (at least) two equal
sides.
The Return Statement

• The return statement allows you to terminate the execution of a


function before you reach the end.
• Example
def evenodd(x):
if x%2:
return(True)
else:
return(False)
ITERATION
Doing the Same Thing Many Times

• It䇻s possible to do something repeatedly by just writing it all out


• Print 䇺hello䇻 5 times
>>> print('Hello!')
Hello
>>> print('Hello!')
Count n Hello
times >>> print('Hello!')
Hello
>>> print('Hello!')
Hello
Statements >>> print('Hello!')
Hello
Iteration and Loops
• A loop repeats a sequence of statements
• A definite loop repeats a sequence of statements a predictable number
of times

>>> for x in range(5): print('Hello!')


...
Hello
Count n Hello
times Hello
Hello
Hello
Statements
The for Loop
• Python䇻s for loop can be used to iterate a definite number of times
for <variable> in range(<number of times>): <statement>
• Use this syntax when you have only one statement to repeat
for <variable> in range(<number of times>):
<statement-1>
<statement-2>

<statement-n> >>> for x in range(3):
... print('Hello!')
... print('goodbye')
•Use indentation to format two or ...
Hello!
more statements below the loop goodbye
Hello!
header goodbye
Hello!
goodbye
Using the Loop Variable
• The loop variable picks up the next value in a sequence on each pass
through the loop
• The expression range(n) generates a sequence of ints from 0
through n - 1
loop variable

>>> for x in range(5): print(x)


...
0
1
2
3
4
>>> list(range(5)) # Show as a list
[0, 1, 2, 3, 4]
Counting from 1 through n

• The expression range(low, high) generates a sequence of ints from low


through high - 1

>>> for x in range(1, 6): print(x)


...
1
2
3
4
5
Counting from n through 1

• The expression range(high, low, step) generates a sequence of ints


from high through low+1.

>>> for x in range(6, 1, -1): print(x)


...
6
5
4
3
2
Skipping Steps in a Sequence

• The expression range(low, high, step) generates a sequence of ints


starting with low and counting by step until high - 1 is reached or
exceeded
>>> for x in range(1, 6, 2): print(x)
...
1
3
5
>>> list(range(1, 6, 2)) # Show as a list
[1, 3, 5]
Using a Loop in a Real Problem
• An investor deposits $10,000 with the Get-Rich-Quick agency and
receives a statement predicting the earnings on an annual percentage
rate (APR) of 6% for a period of 5 years. Write a program that prints the
beginning principal and the interest earned for each year of the period.
The program also prints the total amount earned and the final principal.
• Pseudocode: principal = 10000
rate = .06
term = 5
totalinterest = 0
for each year in term
print principal
interest = principal * rate
print interest
principal = principal + interest
totalinterest = totalinterest + interest
print totalinterest
print principal
While Loop
A for loop is used when a program knows it needs to repeat a block of
code for a certain number of times.
A while loop is used when a program needs to loop until a particular
condition occurs.
Flow of Execution for WHILE Statement
Looping Until User Wants To Quit
Range Function
• Range returns an immutable sequence objects of integers between
the given start integer to the stop integer.
• range() constructor has two forms of definition:
– range(stop)
– range(start, stop, step)
• start - integer starting from which the sequence of integers is to be returned
• integer before which the sequence of integers is to be returned.
The range of integers end at stop - 1.
– step (Optional) - integer value which determines the increment between each integer in
the sequence
Exercise
1. Write a password guessing program to keep track of how many
times the user has entered the password wrong. If it is more than 3
times, print "You have been denied access." and terminate the
program. If the password is correct, print "You have successfully
logged in." and terminate the program.
2. Write a program that asks for two numbers. If the sum of the
numbers is greater than 100, print "That is a big number" and
terminate the program.
3. Write a Python program that accepts a word from the user and
reverse it.
4. Write a python program to find those numbers which are divisible
by 7 and multiples of 5, between 1500 and 2700.
5. Write a Python program to get the Fibonacci series between 0 to 50.
6. Write a Python program which iterates the integers from 1 to 50. For multiples of
three print "Fizz" instead of the number and for the multiples of five print "Buzz".
Fo u e s hi h a e ultiples of oth th ee a d fi e p i t "FizzBuzz
7. Write a Python program to print alphabet pattern 'A'.
8. W ite a P tho p og a to p i t alpha et patte 'D‘.
9. Write a Python program to check whether an alphabet is a vowel or consonant.
10. Write a Python program to check a triangle is equilateral, isosceles or scalene.
Note :An equilateral triangle is a triangle in which all three sides are equal.
A scalene triangle is a triangle that has three unequal sides.
An isosceles triangle is a triangle with (at least) two equal sides.

You might also like