SlideShare a Scribd company logo
VKS-LEARNING HUB
PYTHON
VKS-LEARNING HUB
What is Python…?
Python is an easy to learn, open-source, object-oriented,
general-purpose programming language.
Python is developed by Guido van Rossum in 1991.
1. Free and Open Source : It is freely available without any
cost. It is open source means its source-code is also available
which you can modify, improve .
2. Easy to use – Due to simple syntax rule
3. Interpreted language – Code execution & interpretation line
by line
4. Cross-platform language – It can run on windows, linux, mac
5. Expressive language – Less code to be written as it itself
express the purpose of the code.
6. Extensive libraries- have many built-in and external libraries
support
Features of Python
VKS-LEARNING HUB
What can I do with Python…?
• Graphical User Interface Programming
• System programming
• Internet Scripting
• Component Integration
• Database Programming
• Gaming, Images, XML , Robot and more…..
VKS-LEARNING HUB
4
• code or source code: The sequence of instructions in a program.
• syntax: The set of legal structures and commands that can be used in a
particular programming language.
• output: The messages printed to the user by a program.
• console: The text box onto which output is printed.
– Some source code editors pop up the console as an external window,
and others contain their own console window.
Programming basics
VKS-LEARNING HUB
5
Compiling and interpreting
• Many languages require you to compile (translate) your program into a form
that the machine understands.
• Python is instead directly interpreted into machine instructions.
compile execute
output
source code
Hello.java
byte code
Hello.class
interpret
output
source code
Hello.py
VKS-LEARNING HUB
Python IDE
A computer understands only the machine language.
It does not understand programs written in any other
programming language like Python. Therefore, for
program execution, each instruction of the program
(written in Python) is first interpreted into machine
language by a software called the Python
Interpreter, and then it is executed by the computer.
So, if we wish to run a Python program on a
computer, we should first install Python Interpreter
on it.
VKS-LEARNING HUB
 The process of programming starts with the problem to be solved. When
there is a problem to be solved, we have to think computationally to
formulate the problem well, find its well-defined solution, write the program
to represent the solution, and execute the program. We need a text editor
(Like Notepad, Notepad2, Notepad++, etc) to type the program.
 After the program is typed, we need an Interpreter to interpret and
execute/run the program.
 Sometimes the program has some bugs (errors in a program are called
bugs), and we need to debug the program. If these bugs are difficult to
identify, we need some debugging tools on the computer to help us.
 Sometimes we also need some help with the language code and features
to write our program correctly. A professional programmer may need many
more tools to develop, test, and organize his/her programs.
 A software that provides all these tools as a bundle is called an IDE
(Integrated Development Environment). When we install Python on our
computer, we actually install the Python IDE. Python IDE is called IDLE
(Integrated Development and Learning Environment).
VKS-LEARNING HUB
Step 1 — Downloading the Python Installer
1.Go to the official Python download page for Windows.
https://www.python.org/downloads/windows/
2.Find a stable Python 3 release. This tutorial was tested
with Python version 3.10.10.
3.Click the appropriate link for your system to download
the executable file: Windows installer (64-
bit) or Windows installer (32-bit).
VKS-LEARNING HUB
Step 2 — Running the Executable Installer
 After the installer is downloaded, double-click the .exe file, for example python-
3.10.10-amd64.exe, to run the Python installer.
 Select the Install launcher for all users checkbox, which enables all users of the
computer to access the Python launcher application.
 Select the Add python.exe to PATH checkbox, which enables users to launch
Python from the command line.
VKS-LEARNING HUB
 if you’re just getting started with Python and you want to install it with default
features as described in the dialog, then click Install Now and go to
 Step 4 - Verify the Python Installation. To install other optional and advanced
features, click Customize installation and continue.
 The Optional Features include common tools and resources for Python and you
can install all of them, even if you don’t plan to use them.
VKS-LEARNING HUB
Select some or all of the following
options:
1.Click Next.
2.The Advanced Options dialog
displays.
3.Click Install to start the installation.
After the installation is complete,
a Setup was successful message displays.
VKS-LEARNING HUB
IDLE – Development Environment
• IDLE helps you
program in Python
by:
– color-coding your
program code
– debugging
– auto-indent
– interactive shell
VKS-LEARNING HUB
Initially we will learn the basics of Python in the interactive mode by using IDLE
Python shell. Python IDLE looks like:
VKS-LEARNING HUB
>>>is the Python prompt. If something is typed and it is syntactically correct,
then Python will display some output on the screen, otherwise it will display an error
message. Some examples are given below:
>>> 10
Displays 10 on the screen.
In Python 10 is int (integer – a number without any digit after the decimal point). We
can use type() to check the data type.
>>> type(10)
Displays <class 'int'> on the screen. In Python data type and class can be used
interchangeably.
VKS-LEARNING HUB
>>> 25.6
Displays 25.6 on the screen
In Python 25.6 is float (floating point – a number without at least one digit after the
decimal point).
We can use type() to check the data type.
>>> type(25.6)
Displays <class 'float'> on the screen.
>>> 'FAIPS'
Displays 'FAIPS' on the screen.
>>> "FAIPS"
Displays 'FAIPS' on the screen.
In Python 'FAIPS' / "FAIPS" is str (string – sequence characters enclosed within '/").
We can use type() to check the data type.
VKS-LEARNING HUB
Displays <class 'str'> on the screen.
A string has to be enclosed within ' or ". But represent a string by starting with ' and
ending " or viceversa will be flagged as syntax error.
>>> 'FAIPS"
Will display following error message on the screen:
SyntaxError: EOL while scanning string literal
>>> "FAIPS'
Will display following error message on the screen:
SyntaxError: EOL while scanning string literal
>>> type( “FAIPS” )
VKS-LEARNING HUB
>>> 5+2j
Displays (5+2j) on the screen.
In Python (5+2j) is complex (complex number: 5 is the real part and 2j is the
imaginary part).
We can use type() to check the data type.
>>> type(5+2j)
Displays <class 'complex'> on the screen. Data type complex is not in the
syllabus.
VKS-LEARNING HUB
Fundamental / Primitive / Built-in data types of Python and Literals (constants):
Data Type Literals(Constant)
int (Integer) 0,1,2,3,20,3000,4567,-4,-45,-10000,…..
float(floating point) 2.3,4.5.66.78,989.567,-56.89,0,9,-
0,67……..
Str(string) ‘AMIT’ , “Rohini”, “****”, ‘2.56’,
‘Kuwait’, “FAIPS-DPS”,
“No#1”, “49 South St, PO Box-9951”
bool True, False more will be discussed later
along logical expression
Complex(complex) 5+6j, 2-5j, ….
VKS-LEARNING HUB
Operator Operands Result Remark
+ >>> 10+20
>>> 2.5+3.8
>>> 3.6+8
>>> 'MAN'+'GO
30
6.3
11.6
MANGO
int + int is int (adds two numbers)
float + float is float (adds two numbers)
float + int is float (adds two numbers)
Joins two strings (concatenation)
- >>> 35-17
>>> 7.2-3.8
>>> 8-4.2
18
3.4
3.8
int - int is int (subtracts two numbers)
float - float is float (subtracts two
numbersint - float is float (subtracts two
numbers)
* >>> 5*4
>>> 3.5*4.5
>>> 4*2.5
20
15.75
10.0
int * int is int (multiplies two numbers)
float * float is float (multiplies two
numbers)
int * float is float (multiplies two numbers)
Real
Division
/
>>> 12/4
>>> 2/3
>>> 12.5/2.5
>>> 8.3/12.6
>>> 10/3.5
3.0
0.6667
5.0
0.6588
2.857
int / int is float (divides two numbers)
int / int is float (divides two numbers)
float / float is float (divides two numbers)
float / float is float (divides two numbers)
int / float is float (divides two numbers)
Arithmetic Operators
VKS-LEARNING HUB
Variable (Object) in Python
A variable is name given to a memory location to store value
in the computer’s main storage (in RAM).
It is a name used in the program that represents data (value).
The program can always access the current value of the
variable by referring to its name.
In Python variable is created when it is assigned a value.
It means, in Python to create a variable, a value must be
assigned to it.
In Python, every variable is an Object.
VKS-LEARNING HUB
Rules for naming a Python variable (identifier)
 Variable name should start either with an alphabet (letter) or an
underscore. Variable name starting with _ (underscore) has special
meaning.
 Variable name may contain more than one characters. Second
characters onwards we may use alphabet or digit or underscore.
 No special characters are allowed in a variable name except underscore.
 A variable name in Python is case sensitive. Uppercase and lowercase
letters are distinct.
.
 A variable name cannot be a keyword.
False, True, and, break, class, def, elif, else, for, if, import, in, not, or, return and while
are commonly used keywords and hence cannot be a variable name.
Sum, sum, SUM, suM, Sum and sUm
are treated as six different variable names in Python
VKS-LEARNING HUB
Creating Python variable
• As mentioned earlier, a variable is a name given to a memory location to
store a value.
• To use a variable,variable must be created.
• To create a variable, a value should be assigned to it.
• Every variable that is being created, some value must be assigned to it.
Data type of a variable depends on the data type of the constant
• (expression) that is being assigned to the variable.
Rule for creating variable
VarName=Value
VarName1, VarName2, VarName3=Value1, Value2, Value3
VKS-LEARNING HUB
Python programs must be written with a particular structure.
The syntax must be correct, or the interpreter will generate error messages and not
execute the program.
For example print(“VKS-Learning Hub“ )
We will consider two ways in which we can run this statement
1. enter the program directly into IDLE’s interactive shell
2. enter the program into IDLE’s editor, save it, and run it.
To start IDLE from the Microsoft Windows Start menu.
The IDLE interactive shell will open with >>> prompt.
You may type the above one line Python program directly
into IDLE and press enter to execute the program.
the result will be display using the IDLE interactive shell.
VKS-LEARNING HUB
Since it does not provide a way to save the code you enter, the interactive shell is not
the best tool for writing larger programs. The IDLE interactive shell is useful for
experimenting with small snippets of Python code
IDLE’s editor. IDLE has a built in editor.
From the IDLE menu, select New Window,
Editor will open a file . Type the text print(“VKS-Learning-Hub”) into the
editor.
You can save your program using the Save option in the File menu as
shown in Figure. Save the code to a file named try1.py. The
extension .py is the extension used for Python source code.
We can run the program from within the IDLE editor by pressing
the F5 function key or from the editor’s Run menu: Run→Run
Module. The output appears in the IDLE interactive shell window.
If program is not saved it give message to save first before run
VKS-LEARNING HUB
print(“VKS-Learning Hub")
This is a Python statement. A statement is a command that the interpreter
executes. This statement
prints the message VKS-Learning Hub on the screen. A statement is the
fundamental unit of
execution in a Python program. Statements may be grouped into larger chunks
called blocks, and blocks can make up more complex statements. Higher-order
constructs such as functions and methods are composed of blocks. The statement
print(“VKS-Learning Hub") makes use of a built in function named print
VKS-LEARNING HUB
If you try to enter each line one at a time into the IDLE interactive shell, the program’s
output will be intermingled with the statements you type. In this case the best approach
is to type the program into an editor, save the code you type to a file, and then execute
the program. Most of the time we use an editor to enter and run our Python programs.
The interactive interpreter is most useful for experimenting with small snippets of
Python code.
VKS-LEARNING HUB
input() function of Python
We have already discussed use of assignment operator (=)
to store value in a variable. Now we will learn
how to use input() function to store value in a variable by
inputting data from a keyboard.
Syntax for input()
VarName= input(['Prompt'])
Prompt is an optional string. If Prompt is present, Prompt
will appear on the screen and input() function waits for
some input from the keyboard.
If Prompt is absent input() function only waits for some input
from the keyboard.
VKS-LEARNING HUB
It is important that no whitespace (spaces or tabs) come before the beginning of each
statement.
In Python the indentation of statements is significant and must be done properly. If
we try to put a single space before a statement in the interactive shell
The interpreter reports a
similar error when we attempt
to run a saved Python program
if the code contains such
extraneous indentation.
VKS-LEARNING HUB
Python Character Set
Category Example
Letters A-Z, a-z
Digits 0-9
Special
Symbols
Space + - * / **  () [] {} // = != == < > . ‘ “ ‘’’ “””
, ; : % ! & # <= >= @ >>> << >> _(underscore)
White
Spaces
Blank space, tabs, carriage return, new line,
form-feed
Other
Characters
All other ASCII and Unicode characters
VKS-LEARNING HUB
Token
Smallest Individual unit in a program is known as a Token or
a Lexical unit.
• Keyword
• Identifiers (Names)
• Literals
• Operators
• Punctuators
VKS-LEARNING HUB
Keywords
• A keyword is a word having special meaning reserved by the
programming language.
We cannot use a keyword as variable name, function name or any other identifier.
In Python, keywords are case sensitive.
All the keywords except True, False and None are in lowercase and they must be
written as it is. The list of all the keywords are given below.
Keyword can not be redefined
VKS-LEARNING HUB
Python Identifiers
• Identifier is the name given to entities like class,
functions, variables etc. in Python. It helps differentiating
one entity from another. Identifiers can be redefined
• Identifiers can be a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore (_). Names
like myClass, var_1 and print_this_to_screen, all are valid example.
• An identifier cannot start with a digit. 1variable is invalid,
but variable1 is perfectly fine.
• Keywords cannot be used as identifiers.
• We cannot use special symbols like !, @, #, $, % etc. in our identifier.
• Identifier can be of any length.
Rules for writing identifiers
VKS-LEARNING HUB
Valid Identifiers
• Myfile
• School_46
• _don_
• _fall_down
• Up_and_down_22
• BREAK
• WHILE
Invalid Identifiers
• Data-rec
• 48LIC
• break
• My.file
• First name
• while
VKS-LEARNING HUB
Int (integer) , -4, -3, -2, -1, 0, 1, 2, 3, 4, …
Float (floating point -3.7, -1.0, -0/8, 0, 0.3, 1.8, 2.0, 3.9, …
Complex 10+2j, 2.5+3.2j, -3-6j, -7.2-6.3j
Bool(Boolean) False(0), True(1) both are keywords
Str (String) 'AMIT', '2.65', '***', 'GH-14/783, Paschim Vihar',
"RUPA", "1995", "$$$", "49 South St, PO Box-9951"
literal is a program element whose value remains
same (constant) through the execution of the
Python script. Examples of different types of
literals are given below:
VKS-LEARNING HUB
Strings
Single Line
String
“hello world”
Multi Line
String
“””Allahabad
Uttar Pradesh”””
“hello
World”
Character "C“ ‘2’
A String Literal is a sequence of character surrounded by
quotes( Single or double or triple).
VKS-LEARNING HUB
Example
strings = "This is Python"
char = "C"
multiline_str = """This is a multiline string with more than one line code."""
unicode = u"u00dcnicu00f6de"
raw_str = r"raw n string“s
print(strings)
print(char)
print(multiline_str)
print(unicode)
print(raw_str)
Demo1.py
• To calculate length of string use len() function
VKS-LEARNING HUB
Boolean Literals
• There are two kinds of Boolean literal: True and False.
Example: demo3.py
x = (1 == True)
y = (1 == False)
a = True + 4
b = False + 10
print("x is", x)
print("y is", y)
print("a:", a)
print("b:", b)
VKS-LEARNING HUB
Operators
– Arithmetic Operator (+, -, *, /, %, **, //)
– Relational Operator (<, >, <=, >=, ==, !=)
– Logical Operator (and, or, not)
– Assignment Operator (=, +=, -=, *=, /=, %=,**=, //=)
– Identity Operator (is, not is)
– Membership Operator (in, not in)
Operator: Operators are used in Python to carry out various functions.
Mostly operators are used in arithmetic calculations and in logical
(Boolean) expressions. Examples of operators are given below:
VKS-LEARNING HUB
VKS-LEARNING HUB
Unary operator: An operator that needs one operand.
Examples: Unary -, unary + and not
Binary operator: An operator that needs two
operands.
Most of the operators of Python are
binary operators.
Operators and, or and not are also keywords.
Examples: Binary +, /, +=, *=, >=, !=, and, or
VKS-LEARNING HUB
Delimiter
Delimiter: are special symbol(s) that perform three special
roles in Python: grouping, punctuation and assignment.
List of Python delimiters are given below:
• = += -= *= /= //= %= **= assignment (also used as
shorthand operator)
• ( ) [ ] { } grouping (More about grouping later)
• . , : ; punctuation
() uses with function name but not for grouping
. used in a float literal, calling function from a module, calling
function of an object
, used to assign multiple values to multiple variables in a
single statement
: used in if statement, loops, function header ...
VKS-LEARNING HUB
expressions
• An expressions is any legal combination of
symbols(operators) that represent a value
• 15
• 2.9
• A=a+b
• A+4
• D>5
• F=(3+5)/2
VKS-LEARNING HUB
Python Statement
• Instructions that a Python interpreter can execute are called statements.
• For example, a = 2 is an assignment statement
• if statement, for statement, while statement etc. are other kinds of statements.
Multi-line statement
In Python, end of a statement is marked by a newline character. But we can make a
statement extend over multiple lines with the line continuation character ().
For example:
a = 1 + 2 + 3 + 
4 + 5 + 6 + 
7 + 8 + 9
Multiple Statement in Single Line
We could also put multiple statements in a single line using semicolons, as
follows
a = 1; b = 2; c = 3
VKS-LEARNING HUB
Python Indentation
• Most of the programming languages like C, C++, Java use
braces { } to define a block of code. Python uses
indentation.
• A code block (body of a function, loop, class etc.) starts
with indentation and ends with the first unindented line.
• The amount of indentation is up to you, but it must be
consistent throughout that block.
• Generally four whitespaces are used for indentation and
is preferred over tabs.
VKS-LEARNING HUB
Python Comments
Single Line Comment:
• In Python, we use the hash (#) symbol to start writing a
comment.
#This is a comment
#print out Hello
print('Hello')
Multi-line comments
• Another way of doing this is to use triple quotes, either ''' or """.
"""This is also a
perfect example of
multi-line comments""“
print(“Hello”)
VKS-LEARNING HUB
46
• print : Produces text output on the console.
• Syntax:
print ("Message“)
print (Expression)
– prints the given text message or expression value on the
console, and moves the cursor down to the next line.
print( Item1, Item2, ..., ItemN)
– Prints several messages and/or expressions on the same
line.
print
VKS-LEARNING HUB
Python Input and output
• Printing in a single line with multiple print()
a=25
b=15
c=20
print(a, end=‘ ’)
print(b, end=‘ ‘)
print(c, end=‘ ‘)
print( ) #for line change
print(a, b, c, sep=“:”)
VKS-LEARNING HUB
By default print statement ends with new line
print statement with character given with end parameter
print statement with separator character given with sep parameter
print statement with separator character not given default is space
VKS-LEARNING HUB
49
Variables
• variable: A named piece of memory that can
store a value.
– Usage:
• Compute an expression's result,
• store that result into a variable,
• and use that variable later in the program.
• assignment statement: Stores a value into a
variable.
– Syntax: name = value
– Examples: x = 5
gpa = 3.14
VKS-LEARNING HUB
Declaring Variables in Python
VKS-LEARNING HUB
• Variable Definition
print(x) // will give error because x is not define
Dynamic Typing: A variable pointing to a value of a
certain type can be made to point a value/object of
different type. This is called Dynamic Typing.
X=10
X=“hello”
• Caution with Dynamic Typing
Y=10
X=“hello”
Y=X/2 /// ERROR
VKS-LEARNING HUB
All expressions in Python have a type.
The type of an expression indicates the kind of expression it is.
An expression’s type is sometimes denoted as its class.
The built in type function reveals the type of any Python expression:
To Know variable type
Type(variable)
VKS-LEARNING HUB
53
• input : Reads input data from user.
– You can assign (store) the result of input into a variable. By
default every thing is text /string as input
– Example:
name= input(“Enter your Name“))
age = int(input("How old are you? “))
print ("Your Name is”,name,”and age is",
age)
print("You have", 65 - age, "years left for
retirement“)
Output:
Enter your Name Vinod
How old are you? 53
Your Name is Vinod and age is 53
You have 12 years left for retirement
input
VKS-LEARNING HUB
VKS-LEARNING HUB
Python Input and output
• Printing formatted string
age=10
print(“Your age is {} years”.format(age))
• Printing formatted string (old style)
a=10
b=13.25
c=“Gwalior”
print(“a=%d, b=%f and c =%s“, a, b, c)
VKS-LEARNING HUB
Some built-in functions of Python as given in the syllabus
abs() -Returns the magnitude of number. Return number without sign.
>>> abs(-34), abs(-2.5), abs(45), abs(7.25)
(34, 2.5, 45, 7.25)
>>> w,x,y,z=10,-20, 5.7, -6.2
>>> abs(w), abs(x), abs(y), abs(z)
(10, 20, 5.7, 6.2)
chr()- Returns the single character whose ASCII code or Unicode (integer) is
the parameter to the function. If
the parameter to chr() is float, then it is syntax error.
>>> x=97
>>> chr(x), chr(65)
('a', 'A')
>>> chr(1000)
' '
Ϩ
Displays Unicode character whose Unicode is 1000
>>> chr(67.2)
Displays syntax error because parameter is float.
VKS-LEARNING HUB
eval() - Evaluates an expression inside a string. An expression inside a
string could be either of int type or float
type or str type or bool type.
>>> eval('10+20'), eval('2.5+7.8')
(30, 10.3)
>>> a, b, c, d=7, 4, 4.5, 2.5
>>> eval('a*b'), eval('c*d')
(28, 11.25)
>>> eval("'DEL'+'HI'")
'DELHI'
len() - Returns the length of a string/list/tuple/dictionary. Data types
list/tuple/dictionary will be explained in
the Second Term. But for now, len() function will be used with only string.
>>> len('FAIPS, DPS-Kuwait'), len('')
(17, 0)
>>> x='49 South Street, PO Box-9951, Ahamdi-61010'
>>> len(x), len('India, '+'Delhi')
(42, 12)
VKS-LEARNING HUB
min() - Returns minimum value from the list of values passed as parameters to
the function. List may contain:
• All values are integer
• All values are floating point
• All values are numbers (either int or float))
• All values are string
But using min() with a list of values containing is either integers and strings or
floating points and strings will trigger syntax error.
>>> min(10, 20, 30, 15, 25) # OUTPUT 30
>>> min(2.5, 5.6, 7.8, 9.2, 4.8) # OUTPUT 9.2
>>> min(25, 54.6, 78, 91.2, 48) # OUTPUT 91.2
>>> a, b, c, d=22, 44, 55, 66
>>> min(a, b, c, d) # OUTPUT 66
>>> min('DDD', 'AAA', 'FFF', 'ZZZ', 'CCC') # OUTPUT 'ZZZ'
>>> a, b, c, d, e='GGG', 'TTT', 'DDD', 'BBB', 'FFF'
>>> min(a, b, c, d, e) # OUTPUT 'TTT'
>>> min(100, 'DDD', 400, 'AAA', 200,'FFF')
Displays syntax error list of values include integers and strings.
VKS-LEARNING HUB
min() - Returns minimum value from the list of values passed as parameters to
the function. List may contain:
• All values are integer
• All values are floating point
• All values are numbers (either int or float))
• All values are string
But using min() with a list of values containing is either integers and strings or
floating points and strings will trigger syntax error.
>>> min(10, 20, 30, 15, 25) # OUTPUT 10
>>> min(2.5, 5.6, 7.8, 9.2, 4.8) # OUTPUT 2.5
>>> min(25, 54.6, 78, 91.2, 48) # OUTPUT 25
>>> a, b, c, d=44, 22, 55, 66
>>> min(a, b, c, d) # OUTPUT 22
>>> min('DDD', 'AAA', 'FFF', 'ZZZ', 'CCC') # OUTPUT ‘AAA'
>>> a, b, c, d, e='GGG', 'TTT', 'DDD', 'BBB', 'FFF'
>>> min(a, b, c, d, e) # OUTPUT ‘BBB'
>>> min(100, 'DDD', 400, 'AAA', 200,'FFF')
Displays syntax error list of values include integers and strings.
VKS-LEARNING HUB
ord()
Returns the ASCII code / Unicode of the string containing single character.
>>> x='D'
>>> ord(x), ord('T')
(68, 84)
>>> ord('AB')
Displays syntax error because string contains more than one character.
pow()
Returns base raised to the power of exponent.
>>> pow(5, 4), pow(81, 0.5), pow(-1, 3), pow(8, 1/3)
(625, 9.0, -1, 2.0)
>>> a, b, c, d=81, 0.5, 7, 3.0
>>> pow(a, b), pow(c, d)
(9.0, 343.0)
>>> pow(25, 0.5), pow(25, 1/2), pow(25, 1//2)
(5.0, 5.0, 0)
VKS-LEARNING HUB
round()
Returns a number rounded to nearest integer or rounded to fixed number of
decimal places.
>>> round(10.7), round(7.2), round(9.5)
(11, 7, 10)
>>> a, b, c, d=25.3, 26.8, 23.5, 34.5
>>> round(a), round(b), round(c), round(d)
(25, 27, 24, 34)
>>> round(12.3475,2), round(7.2714,2), round(9.1754,2)
(12.35, 7.27, 9.18)
>>> a, b, c=-5.12345, -2.12382, -3.12356
>>> round(a,3), round(b,3), round(c,3)
(-5.123, -2.124, -3.124)
>>> round(1234.25,-1), round(1282.25,-3), round(1282.25,-2)
(1230.0, 1000.0, 1300.0)
VKS-LEARNING HUB
Python Floor Division and Remainder (Modulo) Operator
We have discussed floor division and remainder operator earlier with positive
numbers (operands). But when we use floor division and remainder operator with
negative numbers then things are little different. But before we discuss floor division
and remainder with negative numbers, we need to learn a small
concept called floor of a number.
What is a floor of a number? It is the closest integer value which is less
than or equal to the specified number.
For example, floor of positive numbers:
• What is the floor of 7.1? Answer is 7.
7.1 is greater than 7
• What is the floor of 7.0? Answer is 7.
7.0 is equal to 7
• What is the floor of 7.9? Answer is 7.
7.9 is greater than 7
For example, floor of negative numbers:
• What is the floor of -7.1? Answer is -8. -7.1 is greater than -8
• What is the floor of -7.0? Answer is -7. -7.0 is equal to -7.0
• What is the floor of -7.9? Answer is -8. -7.9 is greater than -8
VKS-LEARNING HUB
>>> 10/3
#Answer is 3.333333333333333
>>> 10//3
#Answer is 3
Why? This is because floor of 10/3 (3. 333333333333333) is 3.
>>> -10/3
#Answer is -3.333333333333333
>>> -10//3
#Answer is -4
>>> 10//-3
#Answer is -4
Why? This is because floor of -10/3 or floor of 10/-3 (-3. 333333333333333) is -4.
>>> -10/-3
#Answer is 3.333333333333333
>>> -10//-3
#Answer is 3
Why? This is because floor of -10/-3 (3. 333333333333333) is 3.
VKS-LEARNING HUB
In real division, there is a dividend (numerator), there is a divisor (denominator)
and a quotient but no remainder. But in Euclidian division, there is a dividend
(numerator), there is a divisor (denominator), a quotient and a remainder.
What is the relation between all the four components of Euclidian division?
Dividend = Quotient (Dividend // Divisor) * Divisor + Remainder
=> Remainder = Dividend - Quotient (Dividend // Divisor) * Divisor
>>> 10%3 #Answer is 1
Why? This is because Remainder = 10 - 10//3 * 3 = 1
>>> -10%3 #Answer is 2
Why? This is because Remainder = -10 - (-10//3) * 3 = 2
>>> 10%-3 #Answer is -2
Why? This is because Remainder = 10 - (10//-3) * 3 = -2
>>> -10%-3 #Answer is -1
Why? This is because Remainder = -10 - (-10//-3) * 3 = -1

More Related Content

DOCX
A Introduction Book of python For Beginners.docx
PDF
Sessisgytcfgggggggggggggggggggggggggggggggg
PPTX
PYTHON PROGRAMMING.pptx
PDF
Revision of the basics of python - KVSRO Patna.pdf
PDF
Chapter 1 Class 12 Computer Science Unit 1
PPT
Python Programming Language
PDF
Learnpython 151027174258-lva1-app6892
PDF
Revision of the basics of python1 (1).pdf
A Introduction Book of python For Beginners.docx
Sessisgytcfgggggggggggggggggggggggggggggggg
PYTHON PROGRAMMING.pptx
Revision of the basics of python - KVSRO Patna.pdf
Chapter 1 Class 12 Computer Science Unit 1
Python Programming Language
Learnpython 151027174258-lva1-app6892
Revision of the basics of python1 (1).pdf

Similar to VKS-Python Basics for Beginners and advance.pptx (20)

PPT
Introduction to Python For Diploma Students
PDF
computer science CLASS 11 AND 12 SYLLABUS.pdf
PDF
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
PPTX
Python basics
PDF
Python Programming
PPTX
Python Conditional and Looping statements.pptx
PPTX
python presntation 2.pptx
PPTX
Python (Data Analysis) cleaning and visualize
PPTX
2. Getting Started with Python second lesson .pptx
PPTX
Vks python
PPTX
Introduction to Python Programming .pptx
PPTX
lecture 2.pptx
PDF
Python basics
PDF
Python basics
PDF
Class_X_PYTHON_J.pdf
PPT
UNIT 1 PY .ppt - PYTHON PROGRAMMING BASICS
PPTX
python ppt | Python Course In Ghaziabad | Scode Network Institute
PPTX
Unit -1 CAP.pptx
PPTX
Chapter 1 Python Revision (1).pptx the royal ac acemy
PPTX
Introduction to learn and Python Interpreter
Introduction to Python For Diploma Students
computer science CLASS 11 AND 12 SYLLABUS.pdf
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Python basics
Python Programming
Python Conditional and Looping statements.pptx
python presntation 2.pptx
Python (Data Analysis) cleaning and visualize
2. Getting Started with Python second lesson .pptx
Vks python
Introduction to Python Programming .pptx
lecture 2.pptx
Python basics
Python basics
Class_X_PYTHON_J.pdf
UNIT 1 PY .ppt - PYTHON PROGRAMMING BASICS
python ppt | Python Course In Ghaziabad | Scode Network Institute
Unit -1 CAP.pptx
Chapter 1 Python Revision (1).pptx the royal ac acemy
Introduction to learn and Python Interpreter
Ad

More from Vinod Srivastava (8)

PPTX
Understanding Queue in Python using list 2019.pptx
PPTX
Introduction to Python loops while and for .pptx
PPTX
VKS-Python-FIe Handling text CSV Binary.pptx
PPTX
Python Exception handling using Try-Except-Finally
PPTX
Javascripting.pptx
PPTX
python-strings.pptx
PPT
User documentationinter
PPT
Graphics sw
Understanding Queue in Python using list 2019.pptx
Introduction to Python loops while and for .pptx
VKS-Python-FIe Handling text CSV Binary.pptx
Python Exception handling using Try-Except-Finally
Javascripting.pptx
python-strings.pptx
User documentationinter
Graphics sw
Ad

Recently uploaded (20)

PDF
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
DOCX
Factor Analysis Word Document Presentation
PDF
Global Data and Analytics Market Outlook Report
PDF
Introduction to Data Science and Data Analysis
PPTX
Pilar Kemerdekaan dan Identi Bangsa.pptx
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked 2025}
PPTX
Topic 5 Presentation 5 Lesson 5 Corporate Fin
PDF
Microsoft Core Cloud Services powerpoint
PPTX
Market Analysis -202507- Wind-Solar+Hybrid+Street+Lights+for+the+North+Amer...
PPTX
retention in jsjsksksksnbsndjddjdnFPD.pptx
PDF
Transcultural that can help you someday.
PPTX
QUANTUM_COMPUTING_AND_ITS_POTENTIAL_APPLICATIONS[2].pptx
PDF
Votre score augmente si vous choisissez une catégorie et que vous rédigez une...
PPTX
AI Strategy room jwfjksfksfjsjsjsjsjfsjfsj
PPTX
STERILIZATION AND DISINFECTION-1.ppthhhbx
PDF
How to run a consulting project- client discovery
PPT
ISS -ESG Data flows What is ESG and HowHow
PPTX
Copy of 16 Timeline & Flowchart Templates – HubSpot.pptx
PDF
annual-report-2024-2025 original latest.
PPTX
sac 451hinhgsgshssjsjsjheegdggeegegdggddgeg.pptx
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
Factor Analysis Word Document Presentation
Global Data and Analytics Market Outlook Report
Introduction to Data Science and Data Analysis
Pilar Kemerdekaan dan Identi Bangsa.pptx
Capcut Pro Crack For PC Latest Version {Fully Unlocked 2025}
Topic 5 Presentation 5 Lesson 5 Corporate Fin
Microsoft Core Cloud Services powerpoint
Market Analysis -202507- Wind-Solar+Hybrid+Street+Lights+for+the+North+Amer...
retention in jsjsksksksnbsndjddjdnFPD.pptx
Transcultural that can help you someday.
QUANTUM_COMPUTING_AND_ITS_POTENTIAL_APPLICATIONS[2].pptx
Votre score augmente si vous choisissez une catégorie et que vous rédigez une...
AI Strategy room jwfjksfksfjsjsjsjsjfsjfsj
STERILIZATION AND DISINFECTION-1.ppthhhbx
How to run a consulting project- client discovery
ISS -ESG Data flows What is ESG and HowHow
Copy of 16 Timeline & Flowchart Templates – HubSpot.pptx
annual-report-2024-2025 original latest.
sac 451hinhgsgshssjsjsjheegdggeegegdggddgeg.pptx

VKS-Python Basics for Beginners and advance.pptx

  • 2. VKS-LEARNING HUB What is Python…? Python is an easy to learn, open-source, object-oriented, general-purpose programming language. Python is developed by Guido van Rossum in 1991. 1. Free and Open Source : It is freely available without any cost. It is open source means its source-code is also available which you can modify, improve . 2. Easy to use – Due to simple syntax rule 3. Interpreted language – Code execution & interpretation line by line 4. Cross-platform language – It can run on windows, linux, mac 5. Expressive language – Less code to be written as it itself express the purpose of the code. 6. Extensive libraries- have many built-in and external libraries support Features of Python
  • 3. VKS-LEARNING HUB What can I do with Python…? • Graphical User Interface Programming • System programming • Internet Scripting • Component Integration • Database Programming • Gaming, Images, XML , Robot and more…..
  • 4. VKS-LEARNING HUB 4 • code or source code: The sequence of instructions in a program. • syntax: The set of legal structures and commands that can be used in a particular programming language. • output: The messages printed to the user by a program. • console: The text box onto which output is printed. – Some source code editors pop up the console as an external window, and others contain their own console window. Programming basics
  • 5. VKS-LEARNING HUB 5 Compiling and interpreting • Many languages require you to compile (translate) your program into a form that the machine understands. • Python is instead directly interpreted into machine instructions. compile execute output source code Hello.java byte code Hello.class interpret output source code Hello.py
  • 6. VKS-LEARNING HUB Python IDE A computer understands only the machine language. It does not understand programs written in any other programming language like Python. Therefore, for program execution, each instruction of the program (written in Python) is first interpreted into machine language by a software called the Python Interpreter, and then it is executed by the computer. So, if we wish to run a Python program on a computer, we should first install Python Interpreter on it.
  • 7. VKS-LEARNING HUB  The process of programming starts with the problem to be solved. When there is a problem to be solved, we have to think computationally to formulate the problem well, find its well-defined solution, write the program to represent the solution, and execute the program. We need a text editor (Like Notepad, Notepad2, Notepad++, etc) to type the program.  After the program is typed, we need an Interpreter to interpret and execute/run the program.  Sometimes the program has some bugs (errors in a program are called bugs), and we need to debug the program. If these bugs are difficult to identify, we need some debugging tools on the computer to help us.  Sometimes we also need some help with the language code and features to write our program correctly. A professional programmer may need many more tools to develop, test, and organize his/her programs.  A software that provides all these tools as a bundle is called an IDE (Integrated Development Environment). When we install Python on our computer, we actually install the Python IDE. Python IDE is called IDLE (Integrated Development and Learning Environment).
  • 8. VKS-LEARNING HUB Step 1 — Downloading the Python Installer 1.Go to the official Python download page for Windows. https://www.python.org/downloads/windows/ 2.Find a stable Python 3 release. This tutorial was tested with Python version 3.10.10. 3.Click the appropriate link for your system to download the executable file: Windows installer (64- bit) or Windows installer (32-bit).
  • 9. VKS-LEARNING HUB Step 2 — Running the Executable Installer  After the installer is downloaded, double-click the .exe file, for example python- 3.10.10-amd64.exe, to run the Python installer.  Select the Install launcher for all users checkbox, which enables all users of the computer to access the Python launcher application.  Select the Add python.exe to PATH checkbox, which enables users to launch Python from the command line.
  • 10. VKS-LEARNING HUB  if you’re just getting started with Python and you want to install it with default features as described in the dialog, then click Install Now and go to  Step 4 - Verify the Python Installation. To install other optional and advanced features, click Customize installation and continue.  The Optional Features include common tools and resources for Python and you can install all of them, even if you don’t plan to use them.
  • 11. VKS-LEARNING HUB Select some or all of the following options: 1.Click Next. 2.The Advanced Options dialog displays. 3.Click Install to start the installation. After the installation is complete, a Setup was successful message displays.
  • 12. VKS-LEARNING HUB IDLE – Development Environment • IDLE helps you program in Python by: – color-coding your program code – debugging – auto-indent – interactive shell
  • 13. VKS-LEARNING HUB Initially we will learn the basics of Python in the interactive mode by using IDLE Python shell. Python IDLE looks like:
  • 14. VKS-LEARNING HUB >>>is the Python prompt. If something is typed and it is syntactically correct, then Python will display some output on the screen, otherwise it will display an error message. Some examples are given below: >>> 10 Displays 10 on the screen. In Python 10 is int (integer – a number without any digit after the decimal point). We can use type() to check the data type. >>> type(10) Displays <class 'int'> on the screen. In Python data type and class can be used interchangeably.
  • 15. VKS-LEARNING HUB >>> 25.6 Displays 25.6 on the screen In Python 25.6 is float (floating point – a number without at least one digit after the decimal point). We can use type() to check the data type. >>> type(25.6) Displays <class 'float'> on the screen. >>> 'FAIPS' Displays 'FAIPS' on the screen. >>> "FAIPS" Displays 'FAIPS' on the screen. In Python 'FAIPS' / "FAIPS" is str (string – sequence characters enclosed within '/"). We can use type() to check the data type.
  • 16. VKS-LEARNING HUB Displays <class 'str'> on the screen. A string has to be enclosed within ' or ". But represent a string by starting with ' and ending " or viceversa will be flagged as syntax error. >>> 'FAIPS" Will display following error message on the screen: SyntaxError: EOL while scanning string literal >>> "FAIPS' Will display following error message on the screen: SyntaxError: EOL while scanning string literal >>> type( “FAIPS” )
  • 17. VKS-LEARNING HUB >>> 5+2j Displays (5+2j) on the screen. In Python (5+2j) is complex (complex number: 5 is the real part and 2j is the imaginary part). We can use type() to check the data type. >>> type(5+2j) Displays <class 'complex'> on the screen. Data type complex is not in the syllabus.
  • 18. VKS-LEARNING HUB Fundamental / Primitive / Built-in data types of Python and Literals (constants): Data Type Literals(Constant) int (Integer) 0,1,2,3,20,3000,4567,-4,-45,-10000,….. float(floating point) 2.3,4.5.66.78,989.567,-56.89,0,9,- 0,67…….. Str(string) ‘AMIT’ , “Rohini”, “****”, ‘2.56’, ‘Kuwait’, “FAIPS-DPS”, “No#1”, “49 South St, PO Box-9951” bool True, False more will be discussed later along logical expression Complex(complex) 5+6j, 2-5j, ….
  • 19. VKS-LEARNING HUB Operator Operands Result Remark + >>> 10+20 >>> 2.5+3.8 >>> 3.6+8 >>> 'MAN'+'GO 30 6.3 11.6 MANGO int + int is int (adds two numbers) float + float is float (adds two numbers) float + int is float (adds two numbers) Joins two strings (concatenation) - >>> 35-17 >>> 7.2-3.8 >>> 8-4.2 18 3.4 3.8 int - int is int (subtracts two numbers) float - float is float (subtracts two numbersint - float is float (subtracts two numbers) * >>> 5*4 >>> 3.5*4.5 >>> 4*2.5 20 15.75 10.0 int * int is int (multiplies two numbers) float * float is float (multiplies two numbers) int * float is float (multiplies two numbers) Real Division / >>> 12/4 >>> 2/3 >>> 12.5/2.5 >>> 8.3/12.6 >>> 10/3.5 3.0 0.6667 5.0 0.6588 2.857 int / int is float (divides two numbers) int / int is float (divides two numbers) float / float is float (divides two numbers) float / float is float (divides two numbers) int / float is float (divides two numbers) Arithmetic Operators
  • 20. VKS-LEARNING HUB Variable (Object) in Python A variable is name given to a memory location to store value in the computer’s main storage (in RAM). It is a name used in the program that represents data (value). The program can always access the current value of the variable by referring to its name. In Python variable is created when it is assigned a value. It means, in Python to create a variable, a value must be assigned to it. In Python, every variable is an Object.
  • 21. VKS-LEARNING HUB Rules for naming a Python variable (identifier)  Variable name should start either with an alphabet (letter) or an underscore. Variable name starting with _ (underscore) has special meaning.  Variable name may contain more than one characters. Second characters onwards we may use alphabet or digit or underscore.  No special characters are allowed in a variable name except underscore.  A variable name in Python is case sensitive. Uppercase and lowercase letters are distinct. .  A variable name cannot be a keyword. False, True, and, break, class, def, elif, else, for, if, import, in, not, or, return and while are commonly used keywords and hence cannot be a variable name. Sum, sum, SUM, suM, Sum and sUm are treated as six different variable names in Python
  • 22. VKS-LEARNING HUB Creating Python variable • As mentioned earlier, a variable is a name given to a memory location to store a value. • To use a variable,variable must be created. • To create a variable, a value should be assigned to it. • Every variable that is being created, some value must be assigned to it. Data type of a variable depends on the data type of the constant • (expression) that is being assigned to the variable. Rule for creating variable VarName=Value VarName1, VarName2, VarName3=Value1, Value2, Value3
  • 23. VKS-LEARNING HUB Python programs must be written with a particular structure. The syntax must be correct, or the interpreter will generate error messages and not execute the program. For example print(“VKS-Learning Hub“ ) We will consider two ways in which we can run this statement 1. enter the program directly into IDLE’s interactive shell 2. enter the program into IDLE’s editor, save it, and run it. To start IDLE from the Microsoft Windows Start menu. The IDLE interactive shell will open with >>> prompt. You may type the above one line Python program directly into IDLE and press enter to execute the program. the result will be display using the IDLE interactive shell.
  • 24. VKS-LEARNING HUB Since it does not provide a way to save the code you enter, the interactive shell is not the best tool for writing larger programs. The IDLE interactive shell is useful for experimenting with small snippets of Python code IDLE’s editor. IDLE has a built in editor. From the IDLE menu, select New Window, Editor will open a file . Type the text print(“VKS-Learning-Hub”) into the editor. You can save your program using the Save option in the File menu as shown in Figure. Save the code to a file named try1.py. The extension .py is the extension used for Python source code. We can run the program from within the IDLE editor by pressing the F5 function key or from the editor’s Run menu: Run→Run Module. The output appears in the IDLE interactive shell window. If program is not saved it give message to save first before run
  • 25. VKS-LEARNING HUB print(“VKS-Learning Hub") This is a Python statement. A statement is a command that the interpreter executes. This statement prints the message VKS-Learning Hub on the screen. A statement is the fundamental unit of execution in a Python program. Statements may be grouped into larger chunks called blocks, and blocks can make up more complex statements. Higher-order constructs such as functions and methods are composed of blocks. The statement print(“VKS-Learning Hub") makes use of a built in function named print
  • 26. VKS-LEARNING HUB If you try to enter each line one at a time into the IDLE interactive shell, the program’s output will be intermingled with the statements you type. In this case the best approach is to type the program into an editor, save the code you type to a file, and then execute the program. Most of the time we use an editor to enter and run our Python programs. The interactive interpreter is most useful for experimenting with small snippets of Python code.
  • 27. VKS-LEARNING HUB input() function of Python We have already discussed use of assignment operator (=) to store value in a variable. Now we will learn how to use input() function to store value in a variable by inputting data from a keyboard. Syntax for input() VarName= input(['Prompt']) Prompt is an optional string. If Prompt is present, Prompt will appear on the screen and input() function waits for some input from the keyboard. If Prompt is absent input() function only waits for some input from the keyboard.
  • 28. VKS-LEARNING HUB It is important that no whitespace (spaces or tabs) come before the beginning of each statement. In Python the indentation of statements is significant and must be done properly. If we try to put a single space before a statement in the interactive shell The interpreter reports a similar error when we attempt to run a saved Python program if the code contains such extraneous indentation.
  • 29. VKS-LEARNING HUB Python Character Set Category Example Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ** () [] {} // = != == < > . ‘ “ ‘’’ “”” , ; : % ! & # <= >= @ >>> << >> _(underscore) White Spaces Blank space, tabs, carriage return, new line, form-feed Other Characters All other ASCII and Unicode characters
  • 30. VKS-LEARNING HUB Token Smallest Individual unit in a program is known as a Token or a Lexical unit. • Keyword • Identifiers (Names) • Literals • Operators • Punctuators
  • 31. VKS-LEARNING HUB Keywords • A keyword is a word having special meaning reserved by the programming language. We cannot use a keyword as variable name, function name or any other identifier. In Python, keywords are case sensitive. All the keywords except True, False and None are in lowercase and they must be written as it is. The list of all the keywords are given below. Keyword can not be redefined
  • 32. VKS-LEARNING HUB Python Identifiers • Identifier is the name given to entities like class, functions, variables etc. in Python. It helps differentiating one entity from another. Identifiers can be redefined • Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_). Names like myClass, var_1 and print_this_to_screen, all are valid example. • An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine. • Keywords cannot be used as identifiers. • We cannot use special symbols like !, @, #, $, % etc. in our identifier. • Identifier can be of any length. Rules for writing identifiers
  • 33. VKS-LEARNING HUB Valid Identifiers • Myfile • School_46 • _don_ • _fall_down • Up_and_down_22 • BREAK • WHILE Invalid Identifiers • Data-rec • 48LIC • break • My.file • First name • while
  • 34. VKS-LEARNING HUB Int (integer) , -4, -3, -2, -1, 0, 1, 2, 3, 4, … Float (floating point -3.7, -1.0, -0/8, 0, 0.3, 1.8, 2.0, 3.9, … Complex 10+2j, 2.5+3.2j, -3-6j, -7.2-6.3j Bool(Boolean) False(0), True(1) both are keywords Str (String) 'AMIT', '2.65', '***', 'GH-14/783, Paschim Vihar', "RUPA", "1995", "$$$", "49 South St, PO Box-9951" literal is a program element whose value remains same (constant) through the execution of the Python script. Examples of different types of literals are given below:
  • 35. VKS-LEARNING HUB Strings Single Line String “hello world” Multi Line String “””Allahabad Uttar Pradesh””” “hello World” Character "C“ ‘2’ A String Literal is a sequence of character surrounded by quotes( Single or double or triple).
  • 36. VKS-LEARNING HUB Example strings = "This is Python" char = "C" multiline_str = """This is a multiline string with more than one line code.""" unicode = u"u00dcnicu00f6de" raw_str = r"raw n string“s print(strings) print(char) print(multiline_str) print(unicode) print(raw_str) Demo1.py • To calculate length of string use len() function
  • 37. VKS-LEARNING HUB Boolean Literals • There are two kinds of Boolean literal: True and False. Example: demo3.py x = (1 == True) y = (1 == False) a = True + 4 b = False + 10 print("x is", x) print("y is", y) print("a:", a) print("b:", b)
  • 38. VKS-LEARNING HUB Operators – Arithmetic Operator (+, -, *, /, %, **, //) – Relational Operator (<, >, <=, >=, ==, !=) – Logical Operator (and, or, not) – Assignment Operator (=, +=, -=, *=, /=, %=,**=, //=) – Identity Operator (is, not is) – Membership Operator (in, not in) Operator: Operators are used in Python to carry out various functions. Mostly operators are used in arithmetic calculations and in logical (Boolean) expressions. Examples of operators are given below:
  • 40. VKS-LEARNING HUB Unary operator: An operator that needs one operand. Examples: Unary -, unary + and not Binary operator: An operator that needs two operands. Most of the operators of Python are binary operators. Operators and, or and not are also keywords. Examples: Binary +, /, +=, *=, >=, !=, and, or
  • 41. VKS-LEARNING HUB Delimiter Delimiter: are special symbol(s) that perform three special roles in Python: grouping, punctuation and assignment. List of Python delimiters are given below: • = += -= *= /= //= %= **= assignment (also used as shorthand operator) • ( ) [ ] { } grouping (More about grouping later) • . , : ; punctuation () uses with function name but not for grouping . used in a float literal, calling function from a module, calling function of an object , used to assign multiple values to multiple variables in a single statement : used in if statement, loops, function header ...
  • 42. VKS-LEARNING HUB expressions • An expressions is any legal combination of symbols(operators) that represent a value • 15 • 2.9 • A=a+b • A+4 • D>5 • F=(3+5)/2
  • 43. VKS-LEARNING HUB Python Statement • Instructions that a Python interpreter can execute are called statements. • For example, a = 2 is an assignment statement • if statement, for statement, while statement etc. are other kinds of statements. Multi-line statement In Python, end of a statement is marked by a newline character. But we can make a statement extend over multiple lines with the line continuation character (). For example: a = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 Multiple Statement in Single Line We could also put multiple statements in a single line using semicolons, as follows a = 1; b = 2; c = 3
  • 44. VKS-LEARNING HUB Python Indentation • Most of the programming languages like C, C++, Java use braces { } to define a block of code. Python uses indentation. • A code block (body of a function, loop, class etc.) starts with indentation and ends with the first unindented line. • The amount of indentation is up to you, but it must be consistent throughout that block. • Generally four whitespaces are used for indentation and is preferred over tabs.
  • 45. VKS-LEARNING HUB Python Comments Single Line Comment: • In Python, we use the hash (#) symbol to start writing a comment. #This is a comment #print out Hello print('Hello') Multi-line comments • Another way of doing this is to use triple quotes, either ''' or """. """This is also a perfect example of multi-line comments""“ print(“Hello”)
  • 46. VKS-LEARNING HUB 46 • print : Produces text output on the console. • Syntax: print ("Message“) print (Expression) – prints the given text message or expression value on the console, and moves the cursor down to the next line. print( Item1, Item2, ..., ItemN) – Prints several messages and/or expressions on the same line. print
  • 47. VKS-LEARNING HUB Python Input and output • Printing in a single line with multiple print() a=25 b=15 c=20 print(a, end=‘ ’) print(b, end=‘ ‘) print(c, end=‘ ‘) print( ) #for line change print(a, b, c, sep=“:”)
  • 48. VKS-LEARNING HUB By default print statement ends with new line print statement with character given with end parameter print statement with separator character given with sep parameter print statement with separator character not given default is space
  • 49. VKS-LEARNING HUB 49 Variables • variable: A named piece of memory that can store a value. – Usage: • Compute an expression's result, • store that result into a variable, • and use that variable later in the program. • assignment statement: Stores a value into a variable. – Syntax: name = value – Examples: x = 5 gpa = 3.14
  • 51. VKS-LEARNING HUB • Variable Definition print(x) // will give error because x is not define Dynamic Typing: A variable pointing to a value of a certain type can be made to point a value/object of different type. This is called Dynamic Typing. X=10 X=“hello” • Caution with Dynamic Typing Y=10 X=“hello” Y=X/2 /// ERROR
  • 52. VKS-LEARNING HUB All expressions in Python have a type. The type of an expression indicates the kind of expression it is. An expression’s type is sometimes denoted as its class. The built in type function reveals the type of any Python expression: To Know variable type Type(variable)
  • 53. VKS-LEARNING HUB 53 • input : Reads input data from user. – You can assign (store) the result of input into a variable. By default every thing is text /string as input – Example: name= input(“Enter your Name“)) age = int(input("How old are you? “)) print ("Your Name is”,name,”and age is", age) print("You have", 65 - age, "years left for retirement“) Output: Enter your Name Vinod How old are you? 53 Your Name is Vinod and age is 53 You have 12 years left for retirement input
  • 55. VKS-LEARNING HUB Python Input and output • Printing formatted string age=10 print(“Your age is {} years”.format(age)) • Printing formatted string (old style) a=10 b=13.25 c=“Gwalior” print(“a=%d, b=%f and c =%s“, a, b, c)
  • 56. VKS-LEARNING HUB Some built-in functions of Python as given in the syllabus abs() -Returns the magnitude of number. Return number without sign. >>> abs(-34), abs(-2.5), abs(45), abs(7.25) (34, 2.5, 45, 7.25) >>> w,x,y,z=10,-20, 5.7, -6.2 >>> abs(w), abs(x), abs(y), abs(z) (10, 20, 5.7, 6.2) chr()- Returns the single character whose ASCII code or Unicode (integer) is the parameter to the function. If the parameter to chr() is float, then it is syntax error. >>> x=97 >>> chr(x), chr(65) ('a', 'A') >>> chr(1000) ' ' Ϩ Displays Unicode character whose Unicode is 1000 >>> chr(67.2) Displays syntax error because parameter is float.
  • 57. VKS-LEARNING HUB eval() - Evaluates an expression inside a string. An expression inside a string could be either of int type or float type or str type or bool type. >>> eval('10+20'), eval('2.5+7.8') (30, 10.3) >>> a, b, c, d=7, 4, 4.5, 2.5 >>> eval('a*b'), eval('c*d') (28, 11.25) >>> eval("'DEL'+'HI'") 'DELHI' len() - Returns the length of a string/list/tuple/dictionary. Data types list/tuple/dictionary will be explained in the Second Term. But for now, len() function will be used with only string. >>> len('FAIPS, DPS-Kuwait'), len('') (17, 0) >>> x='49 South Street, PO Box-9951, Ahamdi-61010' >>> len(x), len('India, '+'Delhi') (42, 12)
  • 58. VKS-LEARNING HUB min() - Returns minimum value from the list of values passed as parameters to the function. List may contain: • All values are integer • All values are floating point • All values are numbers (either int or float)) • All values are string But using min() with a list of values containing is either integers and strings or floating points and strings will trigger syntax error. >>> min(10, 20, 30, 15, 25) # OUTPUT 30 >>> min(2.5, 5.6, 7.8, 9.2, 4.8) # OUTPUT 9.2 >>> min(25, 54.6, 78, 91.2, 48) # OUTPUT 91.2 >>> a, b, c, d=22, 44, 55, 66 >>> min(a, b, c, d) # OUTPUT 66 >>> min('DDD', 'AAA', 'FFF', 'ZZZ', 'CCC') # OUTPUT 'ZZZ' >>> a, b, c, d, e='GGG', 'TTT', 'DDD', 'BBB', 'FFF' >>> min(a, b, c, d, e) # OUTPUT 'TTT' >>> min(100, 'DDD', 400, 'AAA', 200,'FFF') Displays syntax error list of values include integers and strings.
  • 59. VKS-LEARNING HUB min() - Returns minimum value from the list of values passed as parameters to the function. List may contain: • All values are integer • All values are floating point • All values are numbers (either int or float)) • All values are string But using min() with a list of values containing is either integers and strings or floating points and strings will trigger syntax error. >>> min(10, 20, 30, 15, 25) # OUTPUT 10 >>> min(2.5, 5.6, 7.8, 9.2, 4.8) # OUTPUT 2.5 >>> min(25, 54.6, 78, 91.2, 48) # OUTPUT 25 >>> a, b, c, d=44, 22, 55, 66 >>> min(a, b, c, d) # OUTPUT 22 >>> min('DDD', 'AAA', 'FFF', 'ZZZ', 'CCC') # OUTPUT ‘AAA' >>> a, b, c, d, e='GGG', 'TTT', 'DDD', 'BBB', 'FFF' >>> min(a, b, c, d, e) # OUTPUT ‘BBB' >>> min(100, 'DDD', 400, 'AAA', 200,'FFF') Displays syntax error list of values include integers and strings.
  • 60. VKS-LEARNING HUB ord() Returns the ASCII code / Unicode of the string containing single character. >>> x='D' >>> ord(x), ord('T') (68, 84) >>> ord('AB') Displays syntax error because string contains more than one character. pow() Returns base raised to the power of exponent. >>> pow(5, 4), pow(81, 0.5), pow(-1, 3), pow(8, 1/3) (625, 9.0, -1, 2.0) >>> a, b, c, d=81, 0.5, 7, 3.0 >>> pow(a, b), pow(c, d) (9.0, 343.0) >>> pow(25, 0.5), pow(25, 1/2), pow(25, 1//2) (5.0, 5.0, 0)
  • 61. VKS-LEARNING HUB round() Returns a number rounded to nearest integer or rounded to fixed number of decimal places. >>> round(10.7), round(7.2), round(9.5) (11, 7, 10) >>> a, b, c, d=25.3, 26.8, 23.5, 34.5 >>> round(a), round(b), round(c), round(d) (25, 27, 24, 34) >>> round(12.3475,2), round(7.2714,2), round(9.1754,2) (12.35, 7.27, 9.18) >>> a, b, c=-5.12345, -2.12382, -3.12356 >>> round(a,3), round(b,3), round(c,3) (-5.123, -2.124, -3.124) >>> round(1234.25,-1), round(1282.25,-3), round(1282.25,-2) (1230.0, 1000.0, 1300.0)
  • 62. VKS-LEARNING HUB Python Floor Division and Remainder (Modulo) Operator We have discussed floor division and remainder operator earlier with positive numbers (operands). But when we use floor division and remainder operator with negative numbers then things are little different. But before we discuss floor division and remainder with negative numbers, we need to learn a small concept called floor of a number. What is a floor of a number? It is the closest integer value which is less than or equal to the specified number. For example, floor of positive numbers: • What is the floor of 7.1? Answer is 7. 7.1 is greater than 7 • What is the floor of 7.0? Answer is 7. 7.0 is equal to 7 • What is the floor of 7.9? Answer is 7. 7.9 is greater than 7 For example, floor of negative numbers: • What is the floor of -7.1? Answer is -8. -7.1 is greater than -8 • What is the floor of -7.0? Answer is -7. -7.0 is equal to -7.0 • What is the floor of -7.9? Answer is -8. -7.9 is greater than -8
  • 63. VKS-LEARNING HUB >>> 10/3 #Answer is 3.333333333333333 >>> 10//3 #Answer is 3 Why? This is because floor of 10/3 (3. 333333333333333) is 3. >>> -10/3 #Answer is -3.333333333333333 >>> -10//3 #Answer is -4 >>> 10//-3 #Answer is -4 Why? This is because floor of -10/3 or floor of 10/-3 (-3. 333333333333333) is -4. >>> -10/-3 #Answer is 3.333333333333333 >>> -10//-3 #Answer is 3 Why? This is because floor of -10/-3 (3. 333333333333333) is 3.
  • 64. VKS-LEARNING HUB In real division, there is a dividend (numerator), there is a divisor (denominator) and a quotient but no remainder. But in Euclidian division, there is a dividend (numerator), there is a divisor (denominator), a quotient and a remainder. What is the relation between all the four components of Euclidian division? Dividend = Quotient (Dividend // Divisor) * Divisor + Remainder => Remainder = Dividend - Quotient (Dividend // Divisor) * Divisor >>> 10%3 #Answer is 1 Why? This is because Remainder = 10 - 10//3 * 3 = 1 >>> -10%3 #Answer is 2 Why? This is because Remainder = -10 - (-10//3) * 3 = 2 >>> 10%-3 #Answer is -2 Why? This is because Remainder = 10 - (10//-3) * 3 = -2 >>> -10%-3 #Answer is -1 Why? This is because Remainder = -10 - (-10//-3) * 3 = -1