This is a quick introduction to the basics of python programming language. It covers python3.
Variables
See the following program. Save as datatype.py:
a = 100 # integer
b = 1.23 # float
c = "python" # string
# print variables
print(a)
print(b)
print(c)
# convert int to float
print(float(100))
# convert float to int
print(int(3.14))
# convert string to int
d = "12"
e = "12.3"
print(int(d))
# print(int(e)) - this will generate an error
# convert string to float
print(float(d))
print(float(e))
# convert int to string
f = str(12)
print(type(f))
To run
chmod 755 datatype.py
python3 datatype.py
Output
100
1.23
python
100.0
3
12
12.0
12.3
<class 'str'>
Casting between string, int, and float is very simple is python. Simply use int(), float(), or str() functions.
Commandline Input
To take commandline input:
name = input("What is your name: ")
print(name)
output
What is your name: mole
mole
Type casting
type() shows the data type. int() and float() casts to int and float, respectively.
age = input("What is your age")
print(type(age))
a = int(age)
print(type(a))
output
What is your age: 23
<class 'str'>
<class 'int'>
Numeric Operators
See the example:
print(2 + 2 * 2 - 2)
print(5 / 2) # float division
print(5 // 2) # integer division
print(5 % 2) # modulus
print(5 ** 2) # exponent
output
4
2.5
2
1
25
String operations
The following example covers the most common string manipulations.
print("hello")
# string vs character
name = "Justin" # string
achar = 'a' # character
# str() function
address = str() # empty string
address = str("25 Sussex Drive") # create a list
# substrings
print(name[0]) # J
print(name[4:6]) # in
print(name[:4]) # Just
print(name[3:]) # tin
print(name[1:-1]) # usti
# does the substring exist in string
print("tin" in name) # True
print("xin" in name) # False
# comparison
print(name == "Justin") # True
print(name != "Justin") # False
# commonly used functions
print(len(name)) # 6
print(max(name)) # u
print(min(name)) # J
print('--------------------')
# ending strings, default is \n
print("python", end="") # end without \n
print("python", end="|") # end with |
print("\n") # output for 3 lines # pythonpython|
# does the string contain
s1 = "abc123" # True
# true if string contains alphanumeric characters only
print(s1.isalnum()) # True
# digits only
print("123".isdigit()) # True
# lowercase English alphabet only
print("abc".islower()) # True
# uppercase English alphabet only
print("ABC".isupper()) # True
# whitespace characters only (space, \t, \n)
print("\t".isspace()) # True
Output of the code is in comments.
Lists
Lists can hold collection of values. The following example cover the common operations performed on lists.
# creating lists
a = list() # empty list # []
b = [1,2,3] # [1, 2, 3]
c = list(["python","programming"]) # ['python', 'programming']
# without [], each character becomes a separate element in the list
d = list("python") # ['p', 'y', 't', 'h', 'o', 'n']
print(a)
print(b)
print(c)
print(d)
# accessing list elements, indexing begins at 0
print(b[1]) # 2
# concatenating lists
e = [4,5,6]
f = b + e
print(f) # [1, 2, 3, 4, 5, 6]
# replicating a list
g = b * 2
print(g) # [1, 2, 3, 1, 2, 3]
# using a for loop
for i in b:
print(i, end=" ") # 1 2 3
# list functions
print(1 in b) # True
print(4 not in b) # True
print(len(b)) # 3
print(max(b)) # 3
print(min(b)) # 1
print(sum(b)) # 6
# inserting values in list
b.append(4)
print(b) # [1, 2, 3, 4]
b.extend(e)
print(b) # [1, 2, 3, 4, 4, 5, 6]
b.insert(3,22)
print(b) # [1, 2, 3, 22, 4, 4, 5, 6]
# taking values out of list
b.pop()
print(b) # [1, 2, 3, 22, 4, 4, 5]
b.remove(4)
print(b) # [1, 2, 3, 22, 4, 5]
# sort and reverse the list
b.reverse()
print(b) # [5, 4, 22, 3, 2, 1]
b.sort()
print(b) # [1, 2, 3, 4, 5, 22]
Output is in the comments
Tuple
A tuple is an immutable list. Once created, it cannot be modified.
a = ()
b = (1, 2, 3)
c = [4, 5, 6]
d = tuple(c)
e = tuple("python")
print(a) # ()
print(b) # (1, 2, 3)
print(d) # (4, 5, 6)
print(e) # ('p', 'y', 't', 'h', 'o', 'n')
# substrings
print(b[0:2]) # (1, 2)
# does a value exist in the tuple
print(2 in b) # True
print(5 not in b) # True
# basic functions
print(len(b)) # 3
print(sum(b)) # 6
print(min(b)) # 1
print(max(b)) # 3
# looping through tuple
for i in b:
print(i, end=" ") # 1 2 3
print()
Output is in the comments.
Set
A set is an unordered collection on unique elements. Following example shows how to create and manipulate sets:
# create set
a = {'perl', 'php', 'python'}
print(a) # {'python', 'perl', 'php'}
b = lang.copy()
print(b) # {'python', 'perl', 'php'}
# add element to set
a.add('java')
print(a) # {'python', 'perl', 'java', 'php'}
# difference between 2 sets
print(a.difference(b)) # {'java'}
# discard element from set, no error for missing element
# discard element from set, generate error for missing element
b.discard('php')
b.remove('perl')
print(b) # {'python'}
# elements present in both sets
print(a.intersection(b)) # {'python'}
# return true for null intersection, false otherwise
print(a.isdisjoint(b)) # False
# is b a subset of a?
print(b.issubset(a)) # True
print(a.issubset(b)) # False
# is b a superset of a?
print(b.issuperset(a)) # False
print(a.issuperset(b)) # True
# empty set
b.clear()
print(b) # set()
Output is in the comments.
Dictionary
A dictionary is an associated array. See the following code:
# create dictionary
emptydict = {}
print(emptydict) # {}
emergency = {
'Canada' : '911',
'Switzerland' : '112'
}
print(emergency) # {'Canada': '911', 'Switzerland': '112'}
# retrieve and element
print(emergency['Canada']) # 911
# add an element
emergency['Seychelles'] = '999'
print(emergency)
# {'Canada': '911', 'Seychelles': '999', 'Switzerland': '112'}
# delete an element
del emergency['Seychelles']
print(emergency) # {'Canada': '911', 'Switzerland': '112'}
# length of dictionary
print(len(emergency)) # 2
# in and not in operators
print('Canada' in emergency) # True
print('USA' not in emergency) # True
# empty the dictionary
deleteme = {
'useless' : 'information'
}
print(deleteme) # {'useless' : 'information'}
deleteme.clear()
print(deleteme) # {}
# find key
print(emergency.get('Canada','not found')) # 911
print(emergency.get('USA','not found')) # not found
# get all keys or values
print(emergency.keys()) # dict_keys(['Switzerland', 'Canada'])
print(emergency.values()) # dict_values(['112', '911'])
The output is in the comments.
Conditionals
Python supports if-else conditions. See code below
a, b = 100, 200
if a < b:
print('a ({}) < b ({})'.format(a, b))
else:
print('a ({}) >= ({})'.format(a, b))
output
a (100) < b (200)
Loops
Python uses while and for loops. Python for loops are similar to foreach loop in PHP. See code below:
# loop through entire array
color = ['red','green','blue']
for i in color:
print(i)
output
red
green
blue
Loop through part of the array
color = ['red','green','blue']
# skip first element
for i in color[1:]:
print(i)
# only last 2 elements
for i in color[-2:]:
print(i)
output
green
blue
Using while loop
count = 0
while (count < 3):
print(count)
count += 1
output
0
1
2
Functions
Python functions are defined by def. Once again, indentation, not {}, are used to define blocks. See code below:
def xply(m,n):
return m * n
print(xply(32,54)) # output = 1728