PYTHON
PROGRAMMING
BASICS
Punam_Warke
YTHON BASICS
Comments:: a text on the right of # symbol
Indentation
variables: Reserved memory locations, variable name must be a
character
Syntax: variable = value
e.g. count = 20 # An interger
name = “Anni” # A String
ote : No need to declare variable type.
m_Warke
type
CODE SAMPLE (IN IDLE)
x = 34 - 23 # A comment.
y = “Hello” # Another one.
z = 3.45
if z == 3.45 or y == “Hello”:
x=x+1
y = y + “ World” # String concat.
print x
m_Warke
print y
OUGH TO UNDERSTAND THE CODE
Indentation
Indentation matters to code meaning
Block structure indicated by indentation
First
First assignment to a variable creates it
Variable types don’t need to be declared.
Python figures out the variable types on its own.
Assignment is = and comparison is ==
For numbers + - * / % are as expected
Special use of + for string concatenation and % for string
formatting (as in C’s printf)
printf
m_Warke Logical
Logical operators are words (and,
( or, not) not symbols
The
The basic printing command is print
SIC DATATYPES
• Integers (default for numbers)
z = 5 / 2 # Answer 2, integer division
• Floats
x = 3.456
• Strings
• Can use “” or ‘’ to specify with “abc” == ‘abc’
• Unmatched can occur within the string: “matt’s”
• Use triple double-quotes
quotes for multi-line
multi strings or strings
m_Warke
than contain both ‘ and “ inside of them:
“““a‘b“c”””
MMENTS
• Start comments with #, rest of line is ignored
• Can include a “documentation string” as the first
line of a new function or class you define
• Development environments, debugger, and other
tools use it: it’s good style to include one
def fact(n):
“““fact(n) assumes n is a positive
integer and returns facorial of n.”””
assert(n>0)
m_Warke
return 1 if n==1 else n*fact(n-1)
n*fact(n
MING RULES
Names are case sensitive and cannot start with a number. They
can contain letters, numbers, and underscores.
bob Bob _bob _2_bob_ bob_2 BoB
There are some reserved words:
and, assert, break, class, continue, def, del,
elif,
, else, except, exec, finally, for, from,
global, if, import, in, is, lambda, not, or, pass,
print, raise, return, try, while
m_Warke
SSIGNMENT
• You can assign to multiple names at the same time
>>> x, y = 2, 3
>>> x
2
>>> y
3
This makes it easy to swap values
>>> x, y = y, x
• Assignments can be chained
>>> a = b = x = 2
m_Warke
SEQUENCE TYPES: TUPLE
LISTS, STRINGS AN
DICTIONAR
Punam_Warke
UENCE TYPES 1. Tuple: (‘john’, 32, [CMSC])
A simple immutable ordered sequence of items
No. of values separated by commas
Enclosed within parentheses ()
Items can be of mixed types, including collection
types
Can not be updated or changed (immutable)
ote: 2. Strings: “John Smith”
(*) Repetition Operator • Immutable
(+) concatenation operator • Conceptually very much like a tuple
[], [:] slice operator • Writen in single or double quotes
3. List: [1, 2, ‘john’, (‘up’, ‘down’)]
Mutable ordered sequence of items of mixed types
Compound data type
Values are separated by commas
m_Warke Enclosed within Brackets []
Can be changed (mutable)
Dictionary
A dictionary is a data type similar to arrays
works with keys and values instead of indexes
consists of key value pairs
Each value stored in a dictionary can be accessed using a key
Enclosed within curly brackets {}
values can be assigned or accessed using square braces [].
e.g. tinydict={‘name’:’john’,’code’:6345,’dept’:’sales’}
={‘name’:’john’,’code’:6345,’dept’:’sales’}
m_Warke
A TYPE CONVERSIONS IN PYTHON
Sr.No. Function & Description
1 int(x [,base])
Converts x to an integer. base specifies the base if x is a string.
2 long(x [,base] )
Converts x to a long integer. base specifies the base if x is a string.
3 float(x)
Converts x to a floating-point
point number.
4 complex(real [,imag])
Creates a complex number.
5 str(x)
Converts object x to a string representation.
m_Warke 6 repr(x)
Converts object x to an expression string.
7 eval(str)
Evaluates a string and returns an object.
8 tuple(s)
Converts s to a tuple.
9 list(s)
Converts s to a list.
10 set(s)
Converts s to a set.
11 dict(d)
Creates a dictionary. d must be a sequence of ((key,value) tuples.
12 frozenset(s)
Converts s to a frozen set.
13 chr(x)
m_Warke
Converts an integer to a character.
14 unichr(x)
Converts an integer to a Unicode character.
15 ord(x)
Converts a single character to its integer value.
16 hex(x)
Converts an integer to a hexadecimal string.
17 oct(x)
Converts an integer to an octal string.
m_Warke
ONTROL FLOW IN PYTHON
The control flow of a Python program is regulated by conditional
statements, loops, and function calls.
Python has three types of control structures:
1. Sequential - default mode
2. Selection - used for decisions and branching
3. Repetition - used for looping, i.e., repeating a piece of code
multiple times.
m_Warke
SEQUENTIAL
A set of statements whose execution process happens in a sequence.
The problem with sequential statements is that if the logic has broken in
any one of the lines, then the complete source code execution will break.
e.g.
# This is a Sequential statement
a=20
b=10
c=a-b
m_Warke print("Subtraction is : ",c)
ELECTION/DECISION CONTROL
TATEMENTS
Allows a program to test several conditions and execute instructions based
on which condition is true.
Some Decision Control Statements are:
1. Simple if
2. if-else
3. nested if
4. if-elif-else
m_Warke
imple if:
• if statements are control flow statements that help us to run a particular
code, but only when a certain condition is met or satisfied.
• Syntax:
if expression:
statements(s)
e.g.
n = 10
if n % 2 == 0:
print("n is an even number")
m_Warke
F-ELSE:
The if-else
else statement evaluates the condition and will execute the body of if if the test
condition is True, but if the condition is False, then the body of else is executed.
e.g
n=5
if n % 2 == 0:
print("n is even")
else:
m_Warke print("n is odd")
NESTED IF:
if statements are an if statement
another if statement.
a=5
b = 10
c = 15
if a > b:
if a > c:
print("a value is big")
else:
print("c value is big")
elif b > c:
print("b value is big")
m_Warke
else:
print("c is big")
-ELIF-ELSE:
-elif-else statement is used
nditionally execute a
ment or a block of
ments.
x = 15
y = 12
f x == y:
print("Both are Equal")
elif x > y:
print("x is greater than y")
else:
print("x is smaller than y")
m_Warke
m_Warke
EPETITION
• In Python, we generally have two loops/repetitive
statements:
1. for loop
2. while loop
m_Warke
OR LOOP:
can execute a set of statements
for each item in a list, tuple, or
onary.
e.g.
lst = [1, 2, 3, 4, 5]
for i in range(len(lst)):
print(lst[i], end = " ")
for j in range(0,10):
print(j, end = " ")
m_Warke
WHILE LOOP:
le loops are used to execute a block of
ments repeatedly until a given condition
isfied.
, the expression is checked again and, if
still true, the body is executed again.
continues until the expression becomes
count = 0
while x > 0:
< m: x = x // 2 # truncating division
t(i, end = " ") count += 1
+m_Warke
1 print "The approximate log2 is",
End") count
Example:
# Program to add natural
Python while Loop # numbers up to
# sum = 1+2+3+...+n
# To take input from the user,
# n = int(input("Enter n: "))
n = 10
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
m_Warke
print("The sum is", sum)
HE INFINITE LOOP
A loop becomes infinite loop if a condition never becomes FALSE
E.g.
var = 1
while var == 1 : # This constructs an infinite loop
num = raw_input("Enter
("Enter a number :")
print "You entered: ", num
print "Good bye!"
m_Warke
OR LOOP:
he for loop in Python is used to iterate over a sequence (list,
ple, string)
al”” is the variable that takes the value of the item inside the
quence on each iteration.
ntax:
or val in sequence:
Body of for
op continues until we reach the last item in the
uence
m_Warke
E.g.
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
m_Warke
print("The sum is", sum)
m_Warke
SS
The pass statement is a null statement.
m_Warke
REAK STATEMENT
ython, break and continue statements can alter the
of a normal loop.
he break statement is inside a nested loop (loop
de another loop), the break statement will terminate
innermost loop.
m_Warke
https://www.tutorialspoint.com/execute_python_onlin
se of break statement inside the loop
val in "string":
val == "i": check if the letter is i, upon which we break from the loop.
break we see in our output that all the letters up till i gets printed.
rint(val) After that, the loop terminates.
t("The end")
m_Warke
m_Warke
ONTINUE STATEMENT
The continue statement effectively rejects all the unexecuted statements within the current
teration of the loop and instead pushes that control flow to the loop body beginning.
The continue statement is a loop control statement with a lot of similarities to a break statement
m_Warke
MPARISON
m_Warke