0% found this document useful (0 votes)
10 views15 pages

Introduction to Python Programming

This document provides an overview of Python programming, covering topics such as high-level languages, program structure, debugging, and types of errors. It explains key concepts like variables, expressions, statements, operators, and control flow using loops. Additionally, it introduces the Collatz sequence as an example of iteration in programming.

Uploaded by

vikasm0427
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views15 pages

Introduction to Python Programming

This document provides an overview of Python programming, covering topics such as high-level languages, program structure, debugging, and types of errors. It explains key concepts like variables, expressions, statements, operators, and control flow using loops. Additionally, it introduces the Collatz sequence as an example of iteration in programming.

Uploaded by

vikasm0427
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module- 1

The way of the program

The Python programming language

●​ Python is an example of a high-level language


●​ High-level languages are portable, meaning that they can run on different kinds
of computers with few or no modifications.
●​ The engine that translates and runs Python is called the Python Interpreter. There
are two ways to use it: immediate mode and script mode. In immediate mode, you
type Python expressions into the Python Interpreter window, and the interpreter
immediately shows the result.
○​ The >>> is called the Python prompt
●​ Alternatively, you can write a program in a file and use the interpreter to execute
the contents of the file. Such a file is called a script. Scripts have the advantage
that they can be saved to disk, printed, and so on.

What is a program?

●​ A program is a sequence of instructions that specifies how to perform a


computation.
●​ A few basic instructions appear in just about every language:
■​ input Get data from the keyboard, a file, or some other device such
as a sensor.
■​ output Display data on the screen or send data to a file or other
device such as a motor.
■​ 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.
What is debugging?

●​ Programming is a complex process, and because it is done by human beings, it


often leads to errors.
●​ Programming errors are called bugs and the process of tracking them down and
correcting them is called debugging.
●​ Three kinds of errors can occur in a program: syntax errors, runtime errors, and
semantic errors.

Syntax errors

●​ Python can only execute a program if the program is syntactically correct;


otherwise, the process fails and returns an error message.
●​ Syntax refers to the structure of a program and the rules about that structure.
●​ For example, in English, a sentence must begin with a capital letter and end with a
period. this sentence contains a syntax error.

Runtime errors

●​ The second type of error is a runtime error, so called because the error does not
appear until you run the program.
●​ These errors are also called exceptions because they usually indicate that
something exceptional has happened.

Semantic errors

●​ The third type of error is the semantic error.


●​ If there is a semantic error in your program, it will run successfully, in the sense
that the computer will not generate any error messages, but it will not do the
right thing. It will do something else.
●​ The problem is that the program you wrote is not the program you wanted to
write. The meaning of the program (its semantics) is wrong.
Experimental debugging

●​ Debugging is also like an experimental science. Once you have an idea what is
going wrong, you modify your program and try again.
●​ If your hypothesis was correct, then you can predict the result of the
modification, and you take a step closer to a working program.
●​ If your hypothesis was wrong, you have to come up with a new one.
●​ For example, Linux is an operating system kernel that contains millions of lines
of code, but it started out as a simple program Linus Torvalds used to explore the
Intel 80386 chip.

Variables, expressions and statements

Values and data types

●​ A value is one of the fundamental things — like a letter or a number — that a


program manipulates.
●​ These values are classified into different classes, or data types: 4 is an integer, and
"Hello, World!" is a string, so-called because it contains a string of letters. You
(and the interpreter) can identify strings because they are enclosed in quotation
marks.
●​ If you are not sure what class a value falls into, Python has a function called type
which can tell you.
●​ Strings belong to the class str and integers belong to the class int. Numbers with a
decimal point belong to a class called float.
●​ Strings in Python can be enclosed in either single quotes (') or double quotes ("),
or three of each (''' or """)
●​ Triple quoted strings can even span multiple lines.

Variables

●​ One of the most powerful features of a programming language is the ability to


manipulate variables.
●​ A variable is a name that refers to a value.
●​ The assignment statement gives a value to a variable.
●​ The assignment token, =, should not be confused with equals, which uses the
token ==.
●​ The assignment statement binds a name, on the left-hand side of the operator, to
a value, on the right-hand side. Basically, an assignment is an order, and the
equals operator can be read as a question mark.
●​ You can assign a value to a variable, and later assign a different value to the same
variable.

Variable names and keywords

●​ Variable names can be arbitrarily long. They can contain both letters and digits,
but they have to begin with a letter or an underscore.
●​ Case matters. Bruce and bruce are different variables.
●​ The underscore character ( _) can appear in a name. It is often used in names with
multiple words, such as my_name or price_of_tea_in_china.
●​ Keywords define the language’s syntax rules and structure, and they cannot be
used as variable names.

Statements

●​ A statement is an instruction that the Python interpreter can execute.


●​ Some other kinds of statements that we’ll see shortly are: for statements, if
statements,and import statements.

Evaluating expressions

●​ An expression is a combination of values, variables, operators, and calls to


functions.
●​ len is a built-in Python function that returns the number of characters in a string.
●​ The evaluation of an expression produces a value, which is why expressions can
appear on the right hand side of assignment statements.

Operators and operands

●​ Operators are special tokens that represent computations like addition,


multiplication and division. The values the operator uses are called operands.
●​ The tokens +,-, and *, and the use of parenthesis for grouping, mean in Python
what they mean in mathematics.
●​ The asterisk (*) is the token for multiplication, and ** is the token for
exponentiation.
●​ In Python 3, the division operator / always yields a floating point result.
●​ The second, called floor division uses the token //. Its result is always a whole
number.
●​
Type converter functions

●​ int, float and str convert their arguments into types int, float and str respectively.
We call these type converter functions.
●​ The int function can take a floating point number or a string, and turn it into an
int.
●​ For floating point numbers, it discards the decimal portion of the number — a
process we call truncation towards zero on the number line.
●​ Strings cannot be converted to integers.
●​ The type converter float can turn an integer, a float, or a syntactically legal string
into a float.
●​ The type converter str turns its argument into a string

Order of operations

●​ The order of evaluation depends on the rules of precedence:


1.​ Parentheses have the highest precedence and can be used to force an
expression to evaluate in the order you want. Since expressions in
parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can
also use parentheses to make an expression easier to read, as in (minute *
100) / 60, even though it doesn’t change the result.
2.​ Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4,
and 3*1**3 is 3 and not 27.
3.​ Multiplication and both Division operators have the same precedence,
which is higher than Addition and Subtraction, which also have the same
precedence. So 2*3-1 yields 5 rather than 4, and 5-2*2 is 1, not 6.
4.​ Operators with the same precedence are evaluated from left-to-right. In
algebra we say they are left-associative. So in the expression 6-3+2, the
subtraction happens first, yielding 3. We then add 2 to get the result 5. If
the operations had been evaluated from right to left, the result would have
been 6-(3+2), which is 1. (The acronym PEDMAS could mislead you to
thinking that division has higher precedence than multiplication, and
addition is done ahead of subtraction- don’t be misled. Subtraction and
addition are at the same precedence, and the left-to-right rule applies.)
Operations on strings

●​ The + operator does work with strings, but for strings, the + operator represents
concatenation, not addition.
●​ Concatenation means joining the two operands by linking them end-to-end.

fruit = "banana"
baked_good = " nut bread"
print(fruit + baked_good)

The output of this program is banana nut bread. The space before the word nut is part of
the string, and is necessary to produce the space between the concatenated strings.
●​ The * operator also works on strings; it performs repetition. For example, 'Fun'*3
is 'FunFunFun'. One of the operands has to be a string; the other has to be an
integer.
●​
Input

●​ There is a built-in function in Python for getting input from the user:
name = input("Please enter your name: ")
●​ The user of the program can enter the name and click OK, and when this happens
the text that has been entered is returned from the input function, and in this
case assigned to the variable name.

Composition

●​ One of the most useful features of programming languages is their ability to take
small building blocks and compose them into larger chunks.
●​ Let’s put these together in a small four-step program that asks the user to input a
value for the radius of a circle, and then computes the area of the circle from the
formula.

response = input("What is your radius? ")


r = float(response)
area = 3.14159 * r**2
print("The area is ", area)

●​ Now let's compose the first two lines into a single line of code, and compose the
second two lines into another line of code.
r = float( input("What is your radius? ") )
print("The area is ", 3.14159 * r**2)
●​ We could write it all in one statement:
print("The area is ", 3.14159*float(input("What is your radius?"))**2)

The modulus operator

●​ The modulus operator works on integers (and integer expressions) and gives the
remainder when the first number is divided by the second.
●​ In Python, the modulus operator is a percent sign (%).
●​ The syntax is the same as for other operators. It has the same precedence as the
multiplication operator.
>>> q = 7 // 3
>>> print(q)
OUTPUT: 2
>>> r = 7 % 3
>>> print(r)
OUTPUT: 1

Iteration
●​ Repeated execution of a set of statements is called iteration.

Assignment

●​ It is legal to make more than one assignment to the same variable.


●​ A new assignment makes an existing variable refer to a new value (and stop
referring to the old value).
●​ It is especially important to distinguish between an assignment statement and a
Boolean expression that tests for equality.
●​ Because Python uses the equal token (=) for assignment, it is tempting to interpret
a statement like a = b as a Boolean test.
●​ Note too that an equality test is symmetric, but assignment is not. For example, if
a == 7 then 7 == a. But in Python, the statement a = 7 is legal and 7 = a is not.
Updating variables

●​ When an assignment statement is executed, the right-hand side expression (i.e.


the expression that comes after the assignment token) is evaluated first.
●​ This produces a value.
●​ Then the assignment is made, so that the variable on the left-hand side now refers
to the new value.
n=5
n=3*n+1

Line 2 means get the current value of n, multiply it by three and add one, and assign the
answer to n, thus making n refer to the value. So after executing the two lines above, n
will point/refer to the integer 16.

runs_scored = 0
... runs_scored = runs_scored + 1

●​ Updating a variable by adding 1 to it —is very common. It is called an increment of


the variable; subtracting 1 is called a decrement.
●​ Sometimes programmers also talk about bumping a variable, which means the
same as incrementing it by 1.
●​ This is commonly done with the += operator.
runs_scored = 0
... runs_scored += 1

The for loop

●​ The for loop processes each item in a list. Each item in turn is (re-)assigned to the
loop variable, and the body of the loop is executed.
for friend in ["Joe", "Zoe", "Zuki", "Thandi", "Paris"]:
invite = "Hi " + friend + ". Please come to my party!"
`​ ​ print(invite)
●​ Running through all the items in a list is called traversing the list, or traversal.
●​ Let us write some code now to sum up all the elements in a list of numbers.
numbers = [5, 6, 32, 21, 9]
running_total = 0
for number in numbers:
running_total = running_total + number
print(running_total)
The while statement

n=6
current_sum = 0
i=0
while i <= n:
current_sum += i
i += 1
print(current_sum)

Here is precise flow of execution for a while statement:


●​ Evaluate the condition, yielding a value which is either False or True.
●​ If the value is False, exit the while statement and continue execution at the next
statement
●​ If the value is True, execute each of the statements in the body and then go back
to the while statement. The body consists of all of the statements indented below
the while keyword.
Notice that if the loop condition is False the first time we get loop, the statements in the
body of the loop are never executed. The body of the loop should change the value of one
or more variables so that eventually the condition becomes false and the loop
terminates. Otherwise the loop will repeat forever, which is called an infinite loop.

The Collatz 3n + 1 sequence

●​ The “computational rule” for creating the sequence is to start from some given n,
and to generate the next term of the sequence from n, either by halving n,
(whenever n is even), or else by multiplying it by three and adding 1. The sequence
terminates when n reaches 1.

n = 1027371
while n != 1:
print(n, end=", ")
if n % 2 == 0:​​ ​ # n is even
n = n // 2
else:​ ​ ​ ​ # n is odd
n=n*3+1
print(n, end=".\n")

Notice first that the print function on line 4 has an extra argument end=", ". This tells the
print function to follow the printed string with whatever the programmer chooses (in
this case, a comma followed by a space), instead of ending the line. So each time
something is printed in the loop, it is printed on the same output line, with the numbers
separated by commas. The call to print(n, end=".\n") at line 9 after the loop terminates
will then print the final value of n followed by a period and a newline character. The
condition for continuing with this loop is n != 1, so the loop will continue running until it
reaches its termination condition, (i.e. n == 1). Each time through the loop, the program
outputs the value of n and then checks whether it is even or odd. If it is even, the value of
n is divided by 2 using integer division. If it is odd, the value is replaced by n * 3 + 1. Since
n sometimes increases and sometimes decreases, there is no obvious proof that n will
ever reach 1, or that the program terminates. For some particular values of n, we can
prove termination. For example, if the starting value is a power of two, then the value of
n will be even each time through the loop until it reaches 1. The previous example ends
with such a sequence, starting with 16. See if you can find a small starting number that
needs more than a hundred steps before it terminates. Particular values aside, the
interesting question was first posed by a German mathematician called Lothar Collatz:
the Collatz conjecture (also known as the 3n + 1 conjecture), is that this sequence
terminates for all positive values of n. So far, no one has been able to prove it or disprove
it!

With fast computers we have been able to test every integer up to very large values, and
so far, they have all eventually ended up at 1. But who knows? Perhaps there is some
as-yet untested number which does not reduce to 1. You’ll notice that if you don’t stop
when you reach 1, the sequence gets into its own cyclic loop: 1, 4, 2, 1, 4, 2, 1, 4 . . . So one
possibility is that there might be other cycles that we just haven’t found yet.

Tables

●​ For some operations, computers use tables of values to get an approximate


answer and then perform computations to improve the approximation.
●​ In some cases, there have been errors in the underlying tables, most famously in
the table the Intel Pentium processor chip used to perform floating-point
division.
●​ Although a log table is not as useful as it once was, it still makes a good example
of iteration.
●​ The following program outputs a sequence of values in the left column and 2
raised to the power of that value in the right column:
​ ​ for x in range(13):​ # Generate numbers 0 to 12
print(x, "\t", 2**x)
●​ The string "\t" represents a tab character. The backslash character in "\t"
indicates the beginning of an escape sequence.
●​ Escape sequences are used to represent invisible characters like tabs and
newlines. The sequence \n represents a newline.
●​ As characters and strings are displayed on the screen, an invisible marker called
the cursor keeps track of where the next character will go.
●​ After a print function, the cursor normally goes to the beginning of the next line.
●​ The tab character shifts the cursor to the right until it reaches one of the tab stops.
●​ Tabs are useful for making columns of text line up.

Two-dimensional tables

●​ A two-dimensional table is a table where you read the value at the intersection of
a row and a column.
●​ A multiplication table is a good example.

for i in range(1, 7):


print(2 * i, end=" ")
print()

Here we’ve used the range function, but made it start its sequence at 1. As the loop
executes, the value of i changes from 1 to 6. When all the elements of the range
have been assigned to i, the loop terminates. Each time through the loop, it
displays the value of 2 * i, followed by three spaces. Again, the extra end=" "
argument in the print function suppresses the newline, and uses three spaces
instead. After the loop completes, the call to print at line 3 finishes the current
line, and starts a new line.
The output of the program is: 2 4 6 8 10 12

The break statement

●​ The break statement is used to immediately leave the body of its loop.
●​ The next statement to be executed is the first one after the body:
for i in [12, 16, 17, 24, 29]:
​ ​ ​ ​ if i % 2 == 1:​ ​ # If the number is odd
​ ​ ​ ​ break # ... immediately exit the loop
print(i)
print("done")
This prints:
12
16
done

The continue statement

●​ This is a control flow statement that causes the program to immediately skip the
processing of the rest of the body of the loop, for the current iteration.
●​ But the loop still carries on running for its remaining iterations:
for i in [12, 16, 17, 24, 29, 30]:
if i % 2 == 1:
continue
​ ​ ​ ​ ​ print(i)
print("done")

This prints:
12
16
24
30
done

Paired Data

●​ Making a pair of things in Python is as simple as putting them into


parentheses, like this:
​ ​ year_born = ("Paris Hilton", 1981)
●​ We can put many pairs into a list of pairs:
celebs = [("Brad Pitt", 1963), ("Jack Nicholson", 1937), ("Justin Bieber", 1994)]

Nested Loops for Nested Data

●​ Now we’ll come up with an even more adventurous list of structured data.
●​ In this case, we have a list of students.
●​ Each student has a name which is paired up with another list of subjects that they
are enrolled for:
students=[ ("John",["CompSci","Physics"]), ("Vusi",["Maths","CompSci","Stats"]),
("Jess",["CompSci","Accounting","Economics","Management"]),
("Sarah",["InfSys","Accounting","Economics","CommLaw"]),
("Zuki",["Sociology","Economics","Law","Stats","Music"])]

#Count how many students are taking CompSci


counter=0
for name,subjects in students:
for s in subjects: #A nested loop!
if s=="CompSci":
counter+=1
print("ThenumberofstudentstakingCompSciis",counter)

Functions

●​ In Python, a function is a named sequence of statements that belong together.


●​ Their primary purpose is to help us organize programs into chunks that match
how we think about the problem.
●​ There can be any number of statements inside the function, but they have to be
indented from the def.
●​ In the examples in this book, we will use the standard indentation of four spaces.
●​ Function definitions are the second of several compound statements we will see,
all of which have the same pattern:
1. A header line which begins with a keyword and ends with a colon.
2. A body consisting of one or more Python statements, each indented the same
amount — the Python style guide recommends 4 spaces — from the header line.

Functions that require arguments

●​ Most functions require arguments: the arguments provide for generalization.


For example, if we want to find the absolute value of a number, we have to indicate
what the number is.
Python has a built-in function for computing the absolute value:
>>> abs(-5)
OUTPUT: 5
●​ Some functions take more than one argument. For example the built-in function
pow takes two arguments, the base and the exponent. Inside the function, the
values that are passed get assigned to variables called parameters.
>>> pow(2, 3)
8
>>> pow(7, 4)
2401

Functions that return values

●​ All the functions in the previous section return values.


●​ Calling each of these functions generates a value, which we usually assign to a
variable or use as part of an expression.
●​ A function that returns a value is called a fruitful function in this book.
●​ The opposite of a fruitful function is void function — one that is not executed for
its resulting value, but is executed because it does something useful. (Languages
like Java, C#, C and C++ use the term “void function”, other languages like Pascal
call it a procedure.)

def final_amount(p, r, n, t):


""" Apply the compound interest formula to p to produce the final amount. """
a = p * (1 + r/n) ** (n*t)
return a # This is new, and makes the function fruitful.
# now that we have the function above, let us call it.
toInvest = float(input("How much do you want to invest?"))
fnl = final_amount(toInvest, 0.08, 12, 5)
print("At the end of the period you'll have", fnl)

●​ The return statement is followed by an expression.


●​ This expression will be evaluated and returned to the caller as the “fruit” of
calling this function.
IMPORTANT QUESTIONS

1. Define syntax error, runtime error, and semantic error with examples.

2. Write a Python program to generate the Collatz 3n+1 sequence.

3. Explain various methods to import modules in Python with examples.

4. Differentiate between for loop and while loop with examples.

5. Write a Python program to calculate factorial using a function.

6. Explain the role of the input() function with an example.

7. Discuss type conversion functions in Python.

8. Write a program to print the multiplication table of a given number using loops.

9. Explain the concept of variables and keywords in Python.

10. Write a Python program to check whether a given number is prime.

11. Explain order of operations in Python with an example.

12. Write a Python function to compute the sum of first N natural numbers.

13. Discuss break and continue statements with examples.

14. Write a program to display Fibonacci sequence up to N terms.

15. Explain local and global variables with an example.

16. Write a function that returns both the sum and product of two numbers.

17. Explain experimental debugging in Python.

18. Write a Python program to find the largest number among three numbers using if-elif-else.

19. Discuss the difference between statements and expressions.

20. Write a Python program to compute the GCD of two numbers.

You might also like