Notes_module 1
Notes_module 1
PYTHON BASICS
1. input: Get data from the keyboard, a file, the network, or some other device.
2. output: Display data on the screen, save it in a file, send it over the network, etc.
4. conditional execution: Check for certain conditions and run theappropriate code.
Introduction to python
Python is a widely used general-purpose, high level programming language. It was created by Guido van
Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis
on code readability, and its syntax allows programmers to express their concepts in fewer lines of code.
Python is a general purpose, dynamic, high level and interpreted programming language. It supports Object
Oriented programming approach to develop applications. It is simple and easy to learn and provides lots of
high-level data structures.
Python Features
Python provides many useful features which make it popular and valuable from the other programming
languages. It supports object-oriented programming, procedural programming approaches and provides
dynamic memory allocation. Python's features include −
• 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.
• Interactive Mode − Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
• 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 than shell scripting.
Apart from the above-mentioned features, Python has a big list of good features, few are listed below −
Running Python
One of the challenges of getting started with Python is that you might have to install Python and related software
on your computer. If you are comfortable with the command-line interface, you will have no trouble installing
Python.
There are two versions of Python, called Python 2 and Python 3.The Python interpreter is a program that reads
and executes Python code.Depending on your environment, you might start the interpreter by clicking on an
icon, or by typing python on a command line. When it starts, you should see output like this:
>>>
The first three lines contain information about the interpreter and the operating system it’s running on, so it might
be different for you. But you should check that the version number, which is 3.4.0 in this example, begins with
3, which indicates that you are running Python 3. If it begins with 2, you are running (you
guessed it) Python 2. The last line is a prompt that indicates that the interpreter is ready for you to enter code.
If you type a line of code and hit Enter, the interpreter displays the result:
>>> 1 + 1
>>print('Hello,World!')
The quotation marks in the program mark the beginning and end of the text
to be displayed; they don’t appear in the result The parentheses indicate that print is a functionIn Python 2,
the print statement is slightly different; it is not a function, so
itdoesn’t use parentheses.
Arithmetic operators
Python provides operators, which are special symbols that represent computations like addition and
multiplication.
examples:
>>> 40 + 2
42
>>> 43 – 1
42
>>> 6 * 7
42
>>> 84 / 2
42.0
42
A value is one of the basic things a program works with like a letter or a
number
2 is an integer,
If you are not sure what type a value has, the interpreter can tell you:
>>>type('Hello,World!') <class‘str’>
What about values like '2' and '42.0‘ ? They look like numbers, but they are in
They’re stringsWhen you type a large integer, you might be tempted to use commas
Python
>>> 1,000,000
(1, 0, 0)
Debugging:
Programmers make mistakes. Programming errors are called bugs and the process of tracking them down is
called debugging. Learning to debug can be frustrating, but it is a valuable skill that is useful for many activities
beyond programming.
One of the most powerful features of a programming language is the ability to manipulate variables.
gives it a value:
A common way to represent variables on paper is to write the name with an arrow pointing to its value is called
a state diagram because it shows what state each of the variables is in
Variable names:
Programmers generally choose names for their variables that are meaningful—they document what the
variable is used for
An expression is a combination of values, variables, and operators.A value all by itself is considered an
expressionFollowing are all legal expressions:
>>> 42
42
>>>n
17
>>> n + 25
42
When you type an expression at the prompt, the interpreter evaluates it, which means that it finds the value of
the expression.
In this example, n has the value 17 and n + 25 has the value 42.
A statement is a unit of code that has an effect, like creating a variable or displaying a value.
>>> n = 17
A statement is a unit of code that has an effect, like creating a variable or displaying a value.
>>> n = 17
>>>print(n)
The first line is an assignment statement that gives a value to n. The second
line is a print statement that displays the value of n. When you type a statement, the interpreter executes it,
which means that it does whatever the statement says. In general, statements don’t have values.
Script mode
One of the benefits of working with an interpreted language is that you can test bits of code in interactive mode
before you put them in a script. But there are differences between interactive mode and script mode that can
be confusing.
The alternative is to save code in a file called a Script and then run the interpreter in Script mode to execute
the script.
Order of operations
When more than one operator appears in an expression, the order of evaluation depends
on the rules of precedence. For mathematical operators, Python follows mathematical
• 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,
expression easier to read, as in (minute * 100) / 60, even if it doesn’t change the
result.
• Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is
3, not 27.
• Multiplication and Division have the same precedence, which is higher than
Addition and Subtraction, which also have the same precedence. So 2*3-1 is 5, not
• Operators with the same precedence are evaluated from left to right (except exponentiation).
So in the expression degrees / 2 * pi, the division happens first and the
Comments
• what the program is doing. These notes are called comments, and they start with the # symbol:
Debugging
Syntax error: “Syntax” refers to the structure of a program and the rules about that structure.
For example, parentheses have to come in matching pairs, so (1 + 2) is legal, but 8)is a syntax error. If there
is a syntax error anywhere in your program, Python displays an error message and quits, and you will not be able
to run the program.
Runtime error: so called because the error does not appear until after the program has started running.
These errors are also called exceptions because they usually indicate thatsomething exceptional (and bad) has
happened.
Semantic error: “semantic”, which means related to meaning.
If there is a semantic error in your program, it will run without generating error messages, but it will not dothe
right thing. It will do something else.
Identifying semantic errors can be tricky because it requires you to work backward by looking at the outputof
the program and trying to figure out.
In Python, 2 + 2 is called an expression, which is the most basic kind of programming instruction in the language.
Expressions consist of values(such as 2) and operators (such as +), and they can always evaluate (that is, reduce)
down to a single value. That means you can use expressions anywhere in Python code that you could also use
a value.
>>>2 + 2
A single value with no operators is also considered an expression, though it evaluates only to itself, as shown
here:
>>>2
There are plenty of other operators you can use in Python expressions, too. For example, Table 1-1 lists all
the math operators in Python.
The order of operations (also called precedence) of Python math operators is similar to that of mathematics. The
** operator is evaluated first; the *, /, //, and % operators are evaluated next, from left to right; and the + and -
operators are evaluated last (also from left to right). You can use parentheses to override the usual precedence if
you need to. Enter the following expressions into the interactive shell
These rules for putting operators and values together to form expressions
are a fundamental part of Python as a programming language, just like the grammar rules that help us
communicate. Here’s an example:
The second line is difficult to parse because it doesn’t follow the rules of English. Similarly, if you type in a
bad Python instruction, Python won’t be able to understand it and will display a SyntaxError error message.
Remember that expressions are just values combined with operators, and they always evaluate down to a single
value. A data type is a category for values, and every value belongs to exactly one data type. The mostcommon
data types in Python are listed in Table 1-2. The values -2 and 30,for example, are said to be integer values. The
integer (or int) data type indicates values that are whole numbers. Numbers with a decimal point, such as 3.14,
are called floating-point numbers (or floats). Note that even though the value 42is an integer, the value 42.0
would be a floating-point number.
Python programs can also have text values called strings, or strs(pronounced “stirs”). Always surround your
string in single quote (') characters(as in 'Hello' or 'Goodbye cruel world!') so Python knows where the string
begins and ends. You can even have a string with no characters in it, '',called a blank string. If you ever see
the error message Syntax Error: EOL while scanning string literal, you probably forgot the final single quote
character at the end of the string, such as in this example:
>>>'Hello world!
The meaning of an operator may change based on the data types of the values next to it. For example, + is the
addition operator when it operates on two integers or floating-point values. However, when + is used on two
string
values, it joins the strings as the string concatenation operator. Enter the following into the interactive shell:
>>>'Alice' + 'Bob'
'AliceBob'
The expression evaluates down to a single, new string value that combines the text of the two strings. However,
if you try to use the + operator on a string and an integer value, Python will not know how to handle this, and
it will display an error message.
>>>'Alice' + 42
The error message Can't convert 'int' object to str implicitly means that Python thought you were trying to
concatenate an integer to the string 'Alice'. Your code will have to explicitly convert the integer to a string,
because Python cannot do this automatically. (Converting data types will be explained in “Dissecting Your
Program” on page 22 when talking about the str(), int(), and float() functions.)
The * operator is used for multiplication when it operates on two integer or floating-point values. But when the
* operator is used on one string value and one integer value, it becomes the string replication operator. Enter a
string multiplied by a number into the interactive shell to see this in action.
>>>'Alice' * 5
'AliceAliceAliceAliceAlice'
The expression evaluates down to a single string value that repeats the original a number of times equal to
the integer value. String replication is a useful trick, but it’s not used as often as string concatenation.
The * operator can be used with only two numeric values (for multiplication) or one string value and one integer
value (for string replication). Otherwise, Python will just display an error message.
>>>'Alice' * 'Bob'
Traceback (most recent call last):
'Alice' * 'Bob'
A variable is like a box in the computer’s memory where you can store a single value. If you want to use the
result of an evaluated expression later in your program, you can save it inside a variable.
Assignment Statements
You’ll store values in variables with an assignment statement. An assignment statement consists of a variable
name, an equal sign (called the assignmentoperator), and the value to be stored. If you enter the assignment
statement
spam = 42, then a variable named spam will have the integer value 42 stored in it.
A variable is initialized (or created) the first time a value is stored in it u. After that, you can use it in expressions
with other variables and values v. When a variable is assigned a new value w, the old value is forgotten, which
is why spam evaluated to 42 instead of 40 at the end of the example. This is called overwriting the variable.
Enter the following code into the interactive shell to try overwriting a string:
>>>spam = 'Hello'
>>>spam
'Hello'
>>>spam = 'Goodbye'
>>>spam
'Goodbye'
Variable Names
Table 1-3 has examples of legal variable names. You can name a variable anything as long as it obeys the
following three rules:
2. It can use only letters, numbers, and the underscore (_) character.
open the file editor in IDLE, select File4New Window. The window that appears should contain a cursor
awaiting your input, but it’s different from the interactive shell, which runs Python instructions as soon as
you press enter. The file editor lets you type in many instructions, save the file, and run the program. Here’s how
you can tell the difference between the two:
1. The interactive shell window will always be the one with the >>> prompt.
2.The file editor window will not have the >>> prompt.
Now it’s time to create your first program! When the file editor window opens, type the following into it:
print('Hello world!')
3.myName = input()
print(len(myName))
myAge = input()
With your new program open in the file editor, let’s take a quick tour of the Python instructions it uses by looking
at what each line of code does.
Comments
Python ignores comments, and you can use them to write notes or remind yourself what the code is trying to
do. Any text for the rest of the line following a hash mark (#) is part of a comment. Sometimes, programmers
will put a # in front of a line of code to temporarily remove it while testing a program. This is called commenting
outcode, and it can be useful when you’re trying to figure out why a program doesn’t work. You can remove the
# later when you are ready to put the line back in. Python also ignores the blank line after the comment.
The print() function displays the string value inside the parentheses on the screen.
1.print('Hello world!')
The line print('Hello world!') means “Print out the text in the string 'Hello world!'.” When Python executes this
line, you say that Python is calling the print() function and the string value is being passed to the function. A
value that is passed to a function call is an argument. Notice that the quotes are not printed to the screen. They
just mark where the stringbegins and ends; they are not part of the string value.You can also use this function to
put a blank line on the screen; just call print() withnothing in between the parentheses.
The input() function waits for the user to type some text on the keyboard and press enter.
1.myName = input()
This function call evaluates to a string equal to the user’s text, and the previous line of code assigns the
myName variable to this string value.
The following call to print() actually contains the expression 'It is good to meet you, ' + myName between the
parentheses.
Remember that expressions can always evaluate to a single value. If 'Al' is the value stored in myName on the
previous line, then this expression evaluatesto 'It is good to meet you, Al'. This single string value is then passed
to
You can pass the len() function a string value (or a variable containing a string), and the function evaluates to
the integer value of the number of characters in that string.
>>>len('hello')
46
>>>len('')
If you want to concatenate an integer such as 29 with a string to pass to print(), you’ll need to get the value '29',
which is the string form of 29. The str() function can be passed an integer value and will evaluate to a string
value version of it, as follows:
>>>str(29)
'29'
I am 29 years old.
Because str(29) evaluates to '29', the expression 'I am ' + str(29) +' years old.' evaluates to 'I am ' + '29' + ' years
old.', which in turnevaluatesto 'I am 29 years old.'. This is the value that is passed to theprint() function.
The str(), int(), and float() functions will evaluate to the string, integer, and floating-point forms of the value
you pass, respectively. Try converting what happens.
>>>str(0)
'0'
>>>str(-3.14)
'-3.14'
>>>int('42')
42
>>>int('-99')
-99
>>>int(1.25)
>>>int(1.99)
>>>float('3.14')
3.14
>>>float(10)
The previous examples call the str(), int(), and float() functions and pass them values of the other data types
to obtain a string, integer, or floating-point form of those values. The str() function is handy when you have an
integer or float that you want to concatenate to a string. The int() function is also helpful if you have a number
as a string value that you want to use in some mathematics. For example, the input() function always returns a
string, even if the user enters a number. Enter spam = input() into the interactive shell and enter101 when
it waits for your text.
>>>spam = input()
101
>>>spam
'101'
10.0
The value stored inside spam isn’t the integer 101 but the string '101'. If you want to do math using the value
in spam, use the int() function to get the integer form of spam and then store this as the new value in spam.
>>>spam = int(spam)
>>>spam
101
FLOW CONTROL
Flow control statements can decide which Python instructions to execute under which conditions. Figure
shows a flowchart for what to do if it’s raining. Follow the path made by the arrows from Start to End.
The Boolean data type has only two values: True and False.When entered as Python code, the Boolean values
True and False lack the quotes you place around strings, and they always start with a capital T or F, with the rest
of the word in lowercase.
2. If you don’t use the proper case or you try to use True and False for variable names python will give you
an error message.
2.2 Comparison Operators
Also called relational operators, used to compare two values and evaluate down to a single Boolean value. These
operators evaluate to True or False depending on the values you give them.
The expression 42 == '42‘ evaluates to False because Python considers the integer 42 to be different from the
string '42'. The <,>, <=, and >= operators, on the other hand, work properly only with integer and floating-point
values.
The == operator (equal to) asks whether two values are the same as each other.The = operator (assignment) puts
the value on the right into the variable on the left.
Boolean operators are used to compare Boolean values(True/False). Like comparison operators(<,>,<=,>=,==,!=),
they evaluate these expressions down to a Boolean value.The and and or operators always take two Boolean
values (or expressions), so they’re considered binary operators.
The and operator evaluates an expression to True if both Boolean values are True; otherwise, it evaluates to
False. or operator evaluates an expression to True if either of the two Boolean values is True. If both are
False, it evaluates to False.
A truth table shows every possible result of a Boolean operator.
Expression AND OR
The not operator operates on only one Boolean value (or expression). This makes it a unary operator. The not
operator simply evaluates to the opposite Boolean value. You can nest not operators
The comparison operators(=,>,<,…) evaluate to Boolean values (True /False ), you can use them in
expressions with the Boolean operators(and, or, not ).
The computer will evaluate the left expression first, and then it will evaluate the right expression. When it knows
the Boolean value for each, Flow Control it will then evaluate the whole expression down to one Boolean value.
computer’s evaluation process for (4 < 5) and (5 < 6) as the following:
It also uses multiple Boolean operators in an expression, along with the comparison operators:
The Boolean operators have an order of operations just like the math operators do. After any math and comparison
operators evaluate, Python evaluates the not operators first, then the and operators, and then the or operators.
Flow control statementsstatements often start with a part called the condition and are always followed by a
block of code called the clause.
Conditions:
Boolean expressions are considered as conditions, Conditions always evaluate down to a Boolean value, True
or False. A flow control statement decides what to do based on whether its condition is True or False. Every flow
control statements uses conditions which decides what to do whether its condition is True or False.
Blocks of Code:
Lines of Python code can be grouped together in blocks. when a block begins and ends from the indentation of
the lines of code. There are three rules for blocks.
1. The first block of code starts at the line print ('Hello, Mary') and contains all the lines after it.
2. Inside this block is another block, which has only a single line in it: print('Access Granted.').
The program execution (or simply, execution) is a term for the current instruction being executed. Python started
executing instructions at the top of the program going down, one after another.
The statements represent the diamonds you saw in the flowchart they are the actual decision makers of our
programs.
if Statement:
if statement is the most common type of flow control statement. An if statement’s clause will execute if the
statement’s condition is True. The clause is skipped if the condition is False. An if statement could be read as,
“If this condition is true, execute the code in the clause.ifstatement consists of the following:
1. The if keyword
2. A condition (that is, an expression that evaluates to True or False)
3. A colon
4. Starting on the next line, an indented block of code (called the if clause)
Flow control statements end with a colon and are followed by a new block of codeExample tochecks
whether someone’s name is Alice. Here the block is in the print('Hi, Alice.')
If condition is evaluated to True, the code inside the body ofif is executed.If condition is evaluated to False, the
code inside the body of if is skipped.For example, let’s say you have some code that checks to see whether
someone’s name is Alice.
else Statements:
An if clause can optionally be followed by an else statement. The else clause is executed only when the if
statement’s condition is False.
Only one of the if or else clauses will execute, where you want one of many possible clauses to execute. The elif
statement is an “else if” statement that always follows an if or another elif statement. It provides another condition
that is checked only if all of the previous conditions were False.
Added two more elif statements to make the name checker greet a person with different answers based on age.
Let’s re-create the Alice program to use if, elif, and else clauses.
This type of flow control structure would be “If the first condition is true, do this. Else, if the second condition
is true, do that. Otherwise, do something else.” When you use if, elif, and else statements together, remember
these rules about how to order them to avoid bugs First, there is always exactly one if statement. Any elif
statements you need should follow the if statement. Second, if you want to be sure that at least one clause is
executed, close the structure with an else statement.
while Loop Statements(while loop or just the loop)
In while statement a block of code execute over and over .The code in a while clause will be executed as long
as the while statement’s condition is True.
• A colon
While statement looks similar to an if statement. The difference is at the end of an if clause, the program execution
continues after the if statement. But at the end of a while clause, the program execution jumps backto the start
of the while statement. Look at an if statement and a while loop that use the same condition and take the same
actions based on that condition. Here is the code with an if statement
These statements are similar—both if and while check the value of spam, and if it’s less than 5, they print a
message. The code with the if statement checks the condition, and it prints Hello, world. only once if that condition
is true.
The code with the while loop, will print it five times. The loop stops after fiv prints because the integer in
spam increases by one at the end of each loop iteration, which means that the loop will execute five times
before spam < 5 is False.
In the while loop, the condition is always checked at the start of each iteration If the condition is True, then
the clause is executed, and afterward, the condition is checked again. The first time the condition is found to
be False, the while clause is skipped.
An Annoying while Loop:
First, the program sets the name variable to an empty string. The name!= 'your name' condition will evaluate to
True and the program execution will enter the while loop’s clause . The code inside this asks the user totype
their name, which is assigned to the name variable. Since this is the last line of the block, the execution moves
back to the start of the while loop and reevaluates the condition.
If the value in name is not equal to the string 'your name', then the condition is True, and the execution enters the
while clause again. But once the user types your name, the condition of the while loop will be 'your name'!
= 'your name', which evaluates to False. The condition is now False, and instead of the program execution
reentering the while loop’s clause, Python skips past it and continues running the rest of the program.If you never
enter your name, then the while loop’s condition will never be False, and the program will just keep asking forever
break Statements
The break statement is used to terminate the loop immediately when it is encountered. It is a shortcut to break
the program execution of while loop. If the execution reaches a break statement, it immediately exits the while
loop’s clause. In code, a break statement simply contains the break keyword.
It uses a break statement to escape the loop. The first line creates an infinite loop; it is a while loop whose condition
is always True. This program asks the user to enter your name. Now, however, while the executionis still inside
the while loop, if statement checks whether name is equal to 'your name'.
If this condition is True, the break statement is run, and the execution moves out of the loop to print('Thank you!').
Otherwise, if statement’s clause that contains the break statement is skipped, which puts the executionat the
end of the while loop. At this point, the program execution jumps back to the start of the while statementto
recheck the condition.
continue Statements:
continue statements are used inside loops. When the program execution reaches a continue statement, the program
execution immediately jumps back to the start of the loop and reevaluates the loop’s condition.
Let’s use continue to write a program that asks for a name and password.
If the user enters any name besides Joe, the continue statement causes the program execution to jump back to the
start of the loop. When the program reevaluates the condition, the execution will always enter the loop, since the
condition is simply the value True.
Once the user makes it past that if statement, they are asked for a password w. If the password entered is swordfish,
then the break statement is run, and the execution jumps out of the while loop to print Access granted . Otherwise,
the execution continues to the end of the while loop, where it then jumps back to the startof the loop.
for Loops and the range() Function: ( 2.10 Loops for iteration)
In computer programming, loops are used to repeat a block of code. There are 2 types of loops in Python:
• for loop
• while loop
The while loop keeps looping while its condition is True, but if you want to execute a block of code only a
certain number of times for loop statement and the range() function is used.
In code, a for statement looks something like for i in range(5): and includes the following:
• A variable name
• The in keyword
• A colon
• Starting on the next line, an indented block of code (called the for clause)
Let’s create a new program called fiveTimes.py using for loop in action.
The code in the for loop’s clause is run five times. The first time it is run, the variable i is set to 0. The print()
call in the clause will print Jimmy Five Times (0). Range(5) results in five iterations through the clause, with i
being set to 0, then 1, then 2, then 3, and then 4. The variable i will go up to, but will not include, the integer
passed to range()
Write a program to add up all the numbers from 0 to 100.
while loop to do the same thing as a for loop; for loops are just more concise. Let’s rewrite fiveTimes.py to use
a while loop equivalent of a for loop.
Some functions can be called with multiple arguments separated by a comma, and range() is one of them. This
lets you change the integer passed to range() to follow any sequence of integers, including starting at a number
other than zero. The first argument will be where the for loop’s variable starts, and the second argument will be
up to, but not including, the number to stop at.
The range() function can also be called with three arguments. The first two arguments will be the start and stop
values, and the third will be the step argument. The step is the amount that the variable is increased by after each
iteration. A negative number can also be used for the step argument to make the for loop countdown instead of
up.
print(), input(), and len() functions are basic built-in fuctions of python. Python also comes with a set of
modules called the standard library. Each module is a Python program that contains a related group of functions
that can be embedded in our programs. For example, the math module has mathematics related functions; the
random module has random number–related functions, and so on. Before you can use the functions in a module,
we need to import the module with an import statement. In code, an import statement consists of the following:
The random.randint() function call evaluates to a random integer value between the two integers that you pass
it. Since randint() is in the random module, first type random. in front of the function name to tell Python to
look for this function inside the random module. Here’s an example of an import statement that imports four
different modules: import random, sys, os, math
from import Statements
An alternative form of the import statement is composed of the from keyword, followed by the module name,the
import keyword, and a star; for example
The last flow control concept is how to terminate the program. It is possible to cause the program to terminate,
or exit, by calling the sys.exit() function. Since this function is in the sys module, you have to import sysbefore
your program can use it.
This program has an infinite loop with no break statement inside. The only way this program will end is if the user
enters exit, causing sys.exit() to be called. When response is equal to exit, the program ends. Since the response
variable is set by the input() function, the user must enter exit in order to stop the program.
Develop a program to read the student details like Name, USN, and Marks in three subjects. Display the student
details, total marks and percentage with suitable messages.