Unit 1Python Notes
Unit 1Python Notes
What is Python?
And while you may know the python as a large snake, the name of the Python programming
language comes from an old BBC television comedy sketch series called Monty Python's Flying
Circus.
Why Python?
How does it happen that programmers, young and old, experienced and novice, want to use it?
How did it happen that large companies adopted Python and implemented their flagship products
using it?
There are many reasons – we've listed some of them already, but let's enumerate them again in a
more practical manner:
it's easy to learn – the time needed to learn Python is shorter than for many other
languages; this means that it's possible to start the actual programming faster;
it's easy to teach – the teaching workload is smaller than that needed by other languages;
this means that the teacher can put more emphasis on general (language-independent)
programming techniques, not wasting energy on exotic tricks, strange exceptions and
incomprehensible rules;
it's easy to use for writing new software – it's often possible to write code faster when
using Python;
it's easy to understand - it's also often easier to understand someone else's code faster if
it is written in Python;
it's easy to obtain, install and deploy – Python is free, open and multiplatform; not all
languages can boast that.
Launch IDLE, create a new Python source file, fill it with this code, name the file and save it.
Now run it. If everything goes okay, you'll see the text contained within the quotation marks in
the IDLE console window.
print("Hello, world!")
As you can see, this first program consists of the following parts:
The word print that you can see here is a function name.
Python functions, on the other hand, are more versatile. Depending on the individual needs, they
may accept any number of arguments ‒ as many as necessary to perform their tasks. Note: When
we said any number, that includes zero ‒ some Python functions don't need any argument.
In spite of the number of needed/provided arguments, Python functions strongly demand the
presence of a pair of parentheses ‒ opening and closing ones, respectively.
If you want to deliver one or more arguments to a function, you place them inside the
parentheses. If you're going to use a function which doesn't take any argument, you still have to
have the parentheses.
The only argument delivered to the print() function in this example is a string:
As you can see, the string is delimited with quotes ‒ in fact, the quotes make the string.
The backslash (\) has a very special meaning when used inside strings ‒ this is called the escape
character.
The word escape should be understood specifically ‒ it means that the series of characters in the
string escapes for the moment (a very short moment) to introduce a special inclusion. In other
words, the backslash doesn't mean anything in itself, but is only a kind of announcement, that the
next character after the backslash has a different meaning too.
The letter n placed after the backslash comes from the word newline.
Both the backslash and the n form a special symbol named a newline character, which urges the
console to start a new output line.
Output:
There is one print() function invocation, but it contains three arguments. All of them are strings.
The arguments are separated by commas. We've surrounded them with spaces to make them
more visible.
a print() function invoked with more than one argument outputs them all on one line;
the print() function puts a space between the outputted arguments on its own initiative.
Positional arguments
Now that you know a bit about print() function customs, we're going to show you how to change
them.
Eg:
print("My name is", "Python.")
print("Monty Python.")
The way in which we are passing the arguments into the print() function is the most common in
Python, and is called the positional way. This name comes from the fact that the meaning of the
argument is dictated by its position.
Keyword arguments
Python offers another mechanism for the passing of arguments, which can be helpful when you
want to convince the print() function to change its behavior a bit.
The mechanism is called keyword arguments. The name stems from the fact that the meaning of
these arguments is taken not from its location (position) but from the special word (keyword)
used to identify them.
The print() function has two keyword arguments that you can use for your purposes. The first is
called end.
1. end.
Output:
My name is Python. Monty Python.
In our example, we have made use of the end keyword argument, and set it to a string containing
one space.
As the end argument has been set to nothing, the print() function outputs nothing too, once its
positional arguments have been exhausted.
2. sep
Output:
My-name-is-Monty-Python.
The print() function now uses a dash, instead of a space, to separate the outputted arguments.
Note: the sep argument's value may be an empty string, too. Try it for yourself.
Eg:
print("Programming","Essentials","in", sep="***", end="...")
print("Python")
Output
Programming***Essentials***in...Python
Python literals
Literals – the data in itself
You use literals to encode data and to put them into your code.
Eg:- print("2")
print(2)
Output
2
2
Through this example, you encounter two different types of literals:
a string,
and an integer number
Strings
Strings are used when you need to process text (like names of all kinds, addresses, novels, etc.),
not numbers.
You already know a bit about them, e.g., that strings need quotes the way floats need points.
However, there is a catch. The catch is how to encode a quote inside a string which is already
delimited by quotes.
1. The escape character, which you should remember is played by the backslash. The
backslash can escape quotes too. A quote preceded by a backslash changes its meaning ‒
it's not a delimiter, but just a quote.
Output:
2. Python can use an apostrophe instead of a quote. Either of these characters may delimit
strings, but you must be consistent.
If you open a string with a quote, you have to close it with a quote.
If you start a string with an apostrophe, you have to end it with an apostrophe.
This example will work too:
print('I like "Monty Python"')
Output:
I like "Monty Python"
Operators - data manipulation tools
Basic operators
An operator is a symbol of the programming language, which is able to operate on the values.
For example, just as in arithmetic, the + (plus) sign is the operator which is able to add two
numbers, giving the result of the addition.
Not all Python operators are as obvious as the plus sign, though, so let's go through some of the
operators available in Python, and we'll explain which rules govern their use, and how to
interpret the operations they perform.
We'll begin with the operators which are associated with the most widely recognizable arithmetic
operations:
+, -, *, /, //, %, **
Exponentiation
print(2 ** 3)
print(2 ** 3.)
print(2. ** 3)
print(2. ** 3.)
Output:
8
8.0
8.0
8.0
Note: we've surrounded the double asterisks with spaces in our examples. It's not compulsory,
but it improves the readability of the code.
Remember: It's possible to formulate the following rules based on above output:
Multiplication
print(2 * 3)
print(2 * 3.)
print(2. * 3)
print(2. * 3.)
Output
6
6.0
6.0
6.0
Division
The value in front of the slash is a dividend, the value behind the slash, a divisor.
print(6 / 3)
print(6 / 3.)
print(6. / 3)
print(6. / 3.)
Output
2.0
2.0
2.0
2.0
A // (double slash) sign is an integer division operator. It differs from the standard / operator in
two details:
its result lacks the fractional part ‒ it's absent (for integers), or is always equal to zero (for
floats); this means that the results are always rounded;
it conforms to the integer vs. float rule.
print(6 // 3)
print(6 // 3.)
print(6. // 3)
print(6. // 3.)
Output
2
2.0
2.0
2.0
Note: As you can see, integer by integer division gives an integer result. All other cases
produce floats.
print(6 // 4)
print(6. // 4)
Output
1
1.0
Note: The result of integer division is always rounded to the nearest integer value that is
less than the real (not rounded) result.
print(-6 // 4)
print(6. // -4)
Output
-2
-2.0
Remainder (modulo)
Note: The result of the operator is a remainder left after the integer division.
print(14 % 4)
Output
print(12 % 4.5)
Output
3.0
Addition
The addition operator is the + (plus) sign, which is fully in line with mathematical standards.
print(-4 + 4)
print(-4. + 8)
Output
0
4.0
The subtraction operator is obviously the - (minus) sign, although you should note that this
operator also has another meaning ‒ it can change the sign of a number.
But the minus operator may be used in a different (unary) way ‒ take a look at the last line of the
snippet below:
print(-4 - 4)
print(4. - 8)
print(-1.1)
Output
-8
-4.0
-1.1
By the way: there is also a unary + operator. You can use it like this:
print(+2)
Python precisely defines the priorities of all operators, and assumes that operators of a higher
priority perform their operations before the operators of a lower priority.
For eg: 2+3*5 results in 17 but not 25, because * has higher priority than +.
Operators and their bindings
The binding of the operator determines the order of computations performed by some operators
with equal priority, put side by side in one expression.
Most of Python's operators have left-sided binding, which means that the calculation of the
expression is conducted from left to right.
print(9 % 6 % 2)
Output
Eg: print(2 ** 2 ** 3)
Output
256
List of priorities
Priority Operator
1 (Highest) ~, +, - Unary
2 **
3 *, /, //, %
4 +, - Binary
5 <<, >>
6 <, <=, >, >=
7 ==, !=
8 &
9 |
10 (Lowest) =, +=, -=, *=, /=, %=, &=, ^=, |=, >>=, <<=
Operators and parentheses
In accordance with the arithmetic rules, subexpressions in parentheses are always calculated first.
You can use as many parentheses as you need, and they're often used to improve the
readability of an expression, even if they don't change the order of the operations.
Variables
It offers special "boxes" (or "containers" as we may call them) for storing, and these boxes are
called variables ‒ the name itself suggests that the content of these containers can be varied in
(almost) any way.
a name;
a value (the content of the container)
Variable names
If you want to give a name to a variable, you must follow some strict rules:
the name of the variable must be composed of upper-case or lower-case letters, digits,
and the character _ (underscore)
the name of the variable must begin with a letter;
the underscore character is a letter;
upper- and lower-case letters are treated as different (a little differently than in the real
world – Alice and ALICE are the same first names, but in Python they are two different
variable names, and consequently, two different variables);
the name of the variable must not be any of Python's reserved words (the keywords –
we'll explain more about this soon).
Python does not impose restrictions on the length of variable names, but that doesn't mean that a
long variable name is always better than a short one.
Keywords
Take a look at the list of words that play a very special role in every Python program.
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
They are called keywords or (more precisely) reserved keywords. They are reserved because you
mustn't use them as names: neither for your variables, nor functions, nor any other named entities
you want to create.
The meaning of the reserved word is predefined, and mustn't be changed in any way.
A variable comes into existence as a result of assigning a value to it. Unlike in other
languages, you don't need to declare it in any special way.
If you assign any value to a nonexistent variable, the variable will be automatically created.
You don't need to do anything else.
The creation (in other words, its syntax) is extremely simple: just use the name of the desired
variable, then the equal sign (=) and the value you want to put into the variable.
Eg: var = 1
print(var)
Output
1
The first of them creates a variable named var, and assigns a literal with an integer value
equal to 1.
The second prints the value of the newly created variable to the console.
How to use a variable
You're allowed to use as many variable declarations as you need to achieve your goal, like this:
var = 1
account_balance = 1000.0
client_name = 'John Doe'
print(var, account_balance, client_name)
print(var)
Output
Note:-You can use the print() function and combine text and variables using the + operator to
output strings and variables. For example:
var = "3.8.5"
print("Python version: " + var)
Output
It assigns the value of its right argument to the left, while the right argument may be an
arbitrarily complex expression involving literals, operators and already defined variables.
var = 1
print(var)
var = var + 1
print(var)
Output
1
2
The first line of the snippet creates a new variable named var and assigns 1 to it.
The third line assigns the same variable with the new value taken from the variable itself,
summed with 1.
In effect, the value of variable var has been incremented by one, which has nothing to do with
comparing the variable with any value.
Comments
A remark inserted into the program, which is omitted at runtime, is called a comment.
In Python, a comment is a piece of text that begins with a # (hash) sign and extends to the end of
the line.
If you want a comment that spans several lines, you have to put three apostrophe (‘) in front and
end of the comment line. Just like here:
‘’’ a=10;
print(“Hello”) ‘’’
If you'd like to quickly comment or uncomment multiple lines of code, select the line(s) you
wish to modify and use the following keyboard shortcut: CTRL + / (Windows) or CMD + / (Mac
OS).
The input() function is able to read data entered by the user and to return the same data to the
running program.
The program can manipulate the data, making the code truly interactive.
Virtually all programs read and process data. A program which doesn't get a user's input is a deaf
program.
print("Tell me anything...")
anything = input()
print("Hmm...", anything, "... Really?")
The program prompts the user to input some data from the console (most likely using a
keyboard, although it is also possible to input data using voice or image);
the input() function is invoked without arguments (this is the simplest way of using the function);
the function will switch the console to input mode; you'll see a blinking cursor, and you'll be able
to input some keystrokes, finishing off by hitting the Enter key; all the inputted data will be sent
to your program through the function's result;
Note: you need to assign the result to a variable; this is crucial ‒ missing out this step will cause
the entered data to be lost;
then we use the print() function to output the data we get, with some additional remarks.
Output
Tell me anything...
hi
Hmm... hi ... Really?
The input() function with an argument Modified above example a bit, look at the code:
Note: the input() function is invoked with one argument ‒ it's a string containing a message;
the message will be displayed on the console before the user is given an opportunity to enter
anything.
The result of the input() function is a string. A string containing all the characters the user
enters from the keyboard. It is not an integer or a float. This means that you mustn't use it as an
argument of any arithmetic operation, e.g., you can't use this data to square it, divide it by
anything, or divide anything by it.
Enter a number: 34
Traceback (most recent call last):
File "main.py", line 4, in
something = anything ** 2.0
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'float'
Enter a number:
You tried to apply the ** operator to 'str' (string) accompanied with 'float'.
This is prohibited in input method.
Type casting (type conversions)
Python offers two simple functions to specify a type of data and solve this problem ‒ here they
are: int() and float().
the int() function takes one argument (e.g., a string: int(string)) and tries to convert it
into an integer; if it fails, the whole program will fail too (there is a workaround for this
situation, but we'll show you this a little later);
the float() function takes one argument (e.g., a string: float(string)) and tries to convert it
into a float (the rest is the same).
This is very simple and very effective. Moreover, you can invoke any of the functions by passing
the input() results directly to them. There's no need to use any variable as an intermediate
storage.
Output
Enter a number: 20
20.0 to the power of 2 is 400.0
String operators
Strings are sequence of characters.
The + (plus) sign, when applied to two strings, becomes a concatenation operator:
string + string
It simply concatenates (glues) two strings into one.
In contrast to its arithmetic sibling, the concatenation operator is not commutative, i.e., "ab" +
"ba" is not the same as "ba" + "ab".
Output
May I have your first name, please? mani
May I have your last name, please? pati
Thank you.
The * (asterisk) sign, when applied to a string and number (or a number and string, as it remains
commutative in this position) becomes a replication operator:
string * number
number * string
It replicates the string the same number of times specified by the number.
For example:
== (equal equal) operator :- It is a binary operator with left-sided binding. It needs two
arguments and checks if they are equal.
2==2. returns true. Luckily, Python is able to convert the integer value into its real equivalent,
and consequently, the answer is True.
Eg:
Output
True
False
Inequality: the not equal to operator (!=)
The != (not equal to) operator compares the values of two operands, too. Here is the difference:
if they are equal, the result of the comparison is False. If they are not equal, the result of the
comparison is True.
Eg:
You can also ask a comparison question using the > (greater than) operator.
Eg:
a =10
b=20
print(a>b)
Output
False
The greater than operator has another special, non-strict variant, but it's denoted differently than
in classical arithmetic notation: >= (greater than or equal to).
Eg:
a =10
b=10
print(a>=b)
Output
True
Conditions and conditional execution
if
marks=40
if(marks>40):
print('congrats passed');
if-else
marks=int(input('Enter the marks:'))
if marks>35: #suite or block (both print statements are the part of same block)
print('Result=Passed')
print('Congratulations')
else:
print('Result=Fail')
print('Better luck next time')
if-else-if or (elif)
marks=int(input('Enter the marks :'))
if marks<35:
print('Result is Failed')
elif marks<50:
print('Result is pass')
elif marks<60:
print('Result is second class')
elif marks<70:
print('Result is First class')
else:
print('Result is Distinction')
Loops in Python
Looping your code with while
while
instruction
If you notice some similarities to the if instruction, that's quite all right. Indeed, the syntactic
difference is only one: you use the word while instead of the word if.
The semantic difference is more important: when the condition is met, if performs its
statements only once; while repeats the execution as long as the condition evaluates to True.
if you want to execute more than one statement inside one while loop, you must (as
with if) indent all the instructions in the same way;
an instruction or set of instructions executed inside the while loop is called the loop's
body;
if the condition is False (equal to zero) as early as when it is tested for the first time, the
body is not executed even once (note the analogy of not having to do anything if there is
nothing to do);
the body should be able to change the condition's value, because if the condition
is True at the beginning, the body might run continuously to infinity – notice that doing a
thing usually decreases the number of things to do).
An infinite loop
An infinite loop, also called an endless loop, is a sequence of instructions in a program which
repeat indefinitely (loop endlessly.)
while True:
print("I'm stuck inside a loop.")
This loop will infinitely print "I'm stuck inside a loop." on the screen.
Eg:- A program that reads a sequence of numbers and counts how many numbers are even and
how many or odd. Program terminates when zero is entered.
odd_numbers = 0
even_numbers = 0
# 0 terminates execution.
while number != 0:
# Check if the number is odd.
if number % 2 == 1:
# Increase the odd_numbers counter.
odd_numbers += 1
else:
# Increase the even_numbers counter.
even_numbers += 1
# Read the next number.
number = int(input("Enter a number or type 0 to stop: "))
# Print results.
print("Odd numbers count:", odd_numbers)
print("Even numbers count:", even_numbers)
Output:
counter = 5
while counter != 0:
print("Inside the loop.", counter)
counter -= 1
print("Outside the loop.", counter)
Output:
Inside the loop. 5
Inside the loop. 4
Inside the loop. 3
Inside the loop. 2
Inside the loop. 1
Outside the loop. 0
for i in range(100):
# do_something()
pass
There are some new elements. Let us tell you about them:
the for keyword opens the for loop; note – there's no condition after it; you don't have to think
about conditions, as they're checked internally, without any intervention;
any variable after the for keyword is the control variable of the loop; it counts the loop's turns,
and does it automatically;
the in keyword introduces a syntax element describing the range of possible values being
assigned to the control variable;
the range() function (this is a very special function) is responsible for generating all the desired
values of the control variable; in our example, the function will create (we can even say that it
will feed the loop with) subsequent values from the following set: 0, 1, 2 .. 97, 98, 99; note: in
this case, the range() function starts its job from 0 and finishes it one step (one integer number)
before the value of its argument;
note the pass keyword inside the loop body – it does nothing at all; it's an empty instruction – we
put it here because the for loop's syntax demands at least one instruction inside the body (by the
way – if, elif, else and while express the same thing)
for i in range(10):
print("The value of i is currently", i)
Output
The value of i is currently 0
The value of i is currently 1
The value of i is currently 2
The value of i is currently 3
The value of i is currently 4
The value of i is currently 5
The value of i is currently 6
The value of i is currently 7
The value of i is currently 8
The value of i is currently 9
Note:
the loop has been executed ten times (it's the range() function's argument)
the last control variable's value is 9 (not 10, as it starts from 0, not from 1)
The range() function invocation may be equipped with two arguments, not just one:
Ouptut
The value of i is currently 2
The value of i is currently 3
The value of i is currently 4
The value of i is currently 5
The value of i is currently 6
The value of i is currently 7
The first value shown is 2 (taken from the range()'s first argument.)
The last is 7 (although the range()'s second argument is 8).
More about the for loop and the range() function with three arguments
Output
The value of i is currently 2
The value of i is currently 5
The third argument is an increment – it's a value added to control the variable at every loop turn
(as you may suspect, the default value of the increment is 1).
break – exits the loop immediately, and unconditionally ends the loop's operation; the program
begins to execute the nearest instruction after the loop's body;
continue – behaves as if the program has suddenly reached the end of the body; the next turn is
started and the condition expression is tested immediately.
Eg:
# break - example
print("The break instruction:")
for i in range(1, 6):
if i == 3:
break
print("Inside the loop.", i)
print("Outside the loop.")
# continue - example
Output
The break instruction:
Inside the loop. 1
Inside the loop. 2
Outside the loop.
Both loops, while and for, have one interesting (and rarely used) feature.
The loop's else branch is always executed once, regardless of whether the loop has entered its
body or not.
Eg:
Output
1
2
3
4
else: 5
Eg:
for i in range(5):
print(i)
else:
print("else:", i)
Ouput
0
1
2
3
4
else: 4
One logical conjunction operator in Python is the word and. It's a binary operator with a
priority that is lower than the one expressed by the comparison operators. It allows us to
code complex conditions without the use of parentheses like below:
The result provided by the and operator can be determined on the basis of the truth table.
The or operator
A disjunction operator is the word or. It's a binary operator with a lower priority than and.
It's a unary operator performing a logical negation. Its operation is simple: it turns truth into
falsehood and falsehood into truth.
This operator is written as the word not, and its priority is very high: the same as the
unary + and –
Bitwise operators.
There are four operators that allow you to manipulate single bits of data. They are called bitwise
operators.
A ~A
0 1
1 0
Note: the arguments of these operators must be integers; we must not use floats here.
Python offers yet another operation relating to single bits: shifting. This is applied only
to integer values, and you mustn't use floats as arguments for it.
Eg:
var = 17
var_right = var >> 1
var_left = var << 2
print(var, var_left, var_right)
Output
17 68 8
Note:-Shifting a value one bit to the left thus corresponds to multiplying it by two;
respectively, shifting one bit to the right is like dividing by two (notice that the rightmost bit is
lost).