Python Programming Basics
Python Programming Basics
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
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
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 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
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
n = 10
while i <= n:
sum = sum + i
i = i+1 # update counter
E.g.
var = 1
while var == 1 : # This constructs an infinite loop
num = raw_input("Enter
("Enter a number :")
print "You entered: ", num
m_Warke
E.g.
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
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