Upto Control Structures
Upto Control Structures
Upto Control Structures
Topics to be Covered
• History of Python
• Python is Interactive − You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
• 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.
• 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
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,
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.
• 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
• 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.
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.
• 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
• Keywords define the language’s rules and structure and they can’t be
used as variable names.
– 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
• 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
• 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
• 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
>>> 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