PYTHON 3
BASIC SYNTAX
Python is an interpreted
language
• You can write programs interactively
using the interpreter
• You can also write scripts
– File extention will be .py [eg.
demo.py]
– In console the script can be run by
python command
Python Basic Concepts
• Identifier
• Reserved
Words
• 33 keywords
Lines and Indentation
• No semicolon needed at the end of
lines
• Python does not use braces({}) to
indicate blocks of code
• Blocks of code are denoted by line
indentation
• The number of spaces in the
indentation is variable, but all
statements within the block must be
indented the same amount.
• A single code block is also called
suites
in Python
Indentation
Quotation in Python
• Python accepts single ('), double
(") and triple (''' or """) quotes
to denote string literals
– the same type of quote must start and
end the string.
– The triple quotes are used to span the
string across multiple lines.
Comments
• Single line comment:
#comment
• Triple quotes can be
utilized for multiple-line
commenting.
User Input
• input()
– takes the next line from console
• input("\n\nPress the enter key to
exit.")
• By default, input is a string.
• n = int(input()) # casts to int
Multiple Statements on a
Single Line
• The semicolon ( ; ) allows
multiple statements on a
single line
Print
• print(“String”, end = ‘’)#doesnt print \
n after string
Multiple Assignment
• Python allows you to assign a single
value to several variables
simultaneously
• a=b=c=1
• a, b, c = 1, 2, "john"
VARIABLE TYPES
Standard Data Types
• Python has five standard data
types-
– Numbers
– String
– List
– Tuple
– Dictionary
• No data type for characters
– A character is just a string of length 1
• To find out the type of a object:
type(var)
Numerical Types
• Python supports three different
numerical types −
• int (signed integers)
– You can store arbitrary large values
• float (floating point real values)
• complex (complex numbers)
– A complex number consists of an
ordered pair x + yj, where x and y
are real numbers and j is the
imaginary unit.
Strings
• A contiguous set of characters
represented in the quotation marks.
• Python allows either pair of single or
double quotes.
• It also has a multiline triple quote
“““ STRING ”””
• Strings are immutable in Python.
Lists
• Most versatile among the
compound data types
• A list contains items separated by
commas and enclosed within
square brackets ([1,2, “String”, ‘a’ ])
• Mostly like C arrays, however can
contain items of different types
Python Tuples
• A tuple consists of a number of
values separated by commas and
enclosed within parenthesis.
• Unlike List Tuples can not be
updated.
– They are read only
Common Operations/Functions
on List, String, and Tuple
• Slicing: To get substrings, subLists ,or
a single element the slice operator ([ ]
and [:] ) is used
– indexes starts at 0 in the beginning
– [inclusive:exclusive]
• The plus (+) sign is the
concatenation operator
• The asterisk (*) is the repetition
operator
• len() function returns the length
Example
Example
Output
Example
Output
Python Dictionary
• Dictionaries can hold key-value pairs.
– Similar to Map
– A dictionary key can be almost any
Python type, but are usually numbers
or strings.
– Values, on the other hand, can be any
arbitrary Python object
– Have no notion of order in data
• Dictionaries are enclosed by curly
braces ({ })
• Values can be assigned and
accessed using square braces ([])
Example
Output
Data Type Conversion
• To convert between the built-in types,
simply use the type-name as a
function.
• int(x [,base])
– Converts x to an integer. The
base (optional) specifies the base if x
is a string.
• float(x), complex(real [,imag]), str(),
chr()
• tuple(), list(), dict(), set()
BASIC OPERATORS
Operator Types
• Arithmetic Operators
• Comparison (Relational)
Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
• Most are similar to C/Java
– except Logical Operators
Arithmetic Operators
• +-*/%
• ** : power/ exponent
– 3**2 == 9
• // : integer/floor division
– 9//2 = 4, 9.0//2.0 = 4.0
• no x++ or x--
Comparison Operators
•
==
• !
=
• >
• <
• >
=
• <
=
Assignment Operators
• =
•
+=
• -=
• *=
• /=
• %
=
• **
=
• //=
Bitwise Operators
• &
• |
• ^
• ~
• <
<
• >
>
Bitwise Operators
• bin()
– used to obtain binary representation
of an integer number.
Logical Operators
• an
d
• or
• no
t
• These operators are UNLIKE C, C++
or Java
Python Membership Operators
• Python’s membership operators test
for membership in a sequence, such
as strings, lists, or tuples.
• in
• not in
Python Identity Operators
• Identity operators compare the
memory locations of two objects
• is
• not is
CONDITIONAL
STATEMENTS
If - Else
Nested If
:
Single Line If-Else
LOOP
S
Loops
• whil
e
Range
• The built-in function range() is used to iterate
over a sequence of numbers.
• range() generates an iterator to progress
integers starting with 0 upto n-1
– memory efficient
• To obtain a list object of the
sequence, it is typecasted to list()
Range
Range
Loop Control Statements
• break
• continue
• pass
– The pass statement is a null operation;
nothing happens when it executes.
– The pass statement is also useful in
places where your code will
eventually go, but has not been
written yet i.e. in stubs)
FUNCTION
S
Structure
• parameters can also be defined
inside the parentheses
• The first statement of a function can be
an optional statement - the
documentation string of the function or
docstring.
• A return statement with no arguments
is the same as return None
• Can also be eliminated
Required Arguments
• Required arguments are the
arguments passed to a function in
correct positional order.
– typical parameters like C
• The number of arguments and their
order in the function call should
match exactly with the function
definition.
Keyword Arguments
• Used to pass arguments by the
parameter name.
• This allows to skip arguments or
place them out of order
Default Arguments
Variable-length Arguments
• variable-length arguments and are
not named in the function
definition, unlike required and
default arguments.
Example
Example
Scope of Variables
• There are two basic scopes of
variables in Python-
– global variables
– local variables
• Variables that are defined inside a
function body have a local scope,
and those defined outside have a
global scope.
Returning Multiple Values
• Can be done using class, tuples,
list, or dictionary
• Most convenient by tuples
Modules
import <module_name>
import <module_name> as <name>
from <module_name> import <func>
Examples
import math as mt
a= 10
print(mt.sqrt(10))
from math import sqrt
a= 10
print(sqrt(10))