In continuation from
Python Notes-6
Python Notes-5
Python Notes-4
Python Notes-3
Python Notes-2
Python Notes-1
assert
There are three parts to an assert statement: the assert keyword, an expression which, if False, results in crashing the program. The third part (after the comma after the expression) is a string that appears if the program crashes because of the assertion.
assert (BOARDWIDTH * BOARDHEIGHT) % 2 == 0, ‘Board needs to have an even number of boxes for pairs of matches.’
import random
random.randint(1,9);
As python is strongly type there is no concept of function overload
Python is great for interviews see how easy reversing a string is even without using any function
astring = "Hello world!"
print(astring[::-1])
astring = "Hello world!"
print(astring.upper())
print(astring.lower())
astring = "Hello world!"
print(astring.startswith("Hello"))
print(astring.endswith("asdfasdfasdf"))
astring = "Hello world!"
afewwords = astring.split(" ")
x = [1,2,3]
y = [1,2,3]
print(x == y) # Prints out True
print(x is y) # Prints out False
Reference comparison
is is reference compare operator
The ‘is’ operator
Unlike the double equals operator “==”, the “is” operator does not match the values of the variables, but the instances themselves.
Using else in loops
Unlike languages like C,CPP.. we can use else for loops. When the loop condition of “for” or “while” statement fails then code part in “else” is executed. If break statement is executed inside for loop then the “else” part is skipped. Note that “else” part is executed even if there is a continue statement.
Here are a few examples:
# Prints out 0,1,2,3,4 and then it prints "count value reached 5"
count=0
while(count<5):
print(count)
count +=1
else:
print("count value reached %d" %(count))
# Prints out 1,2,3,4
for i in range(1, 10):
if(i%5==0):
break
print(i)
else:
print("this is not printed because for loop is terminated because of break but not due to fail in condition")
list1 = ['physics', 'chemistry', 1997, 2000];
print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 1 2 3 Iteration
max(list)
Returns item from the list with max value.
min(list)
Returns item from the list with min value.
list.append(obj)
Appends object obj to list
list.count(obj)
Returns count of how many times obj occurs in list
list.extend(seq)
Appends the contents of seq to list
list.index(obj)
Returns the lowest index in list that obj appears
list.insert(index, obj)
Inserts object obj into list at offset index
list.pop(obj=list[-1])
Removes and returns last object or obj from list
list.remove(obj)
Removes object obj from list
list.reverse()
Reverses objects of list in place
To be continued …