
In this blog we will learn python basic topics which is necessary for every beginners:
Comments
Python uses the hash # for comment. There is no block comment in python. For example:
# This is a comment
# using parenthesis for print function is a must in Python 3.x.x
print("Hello realcode4you") # a simple print
Data Types
Data types are the classification or categorization of data items.
It represents the kind of value that tells what operations can be performed on a particular data.
Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.
Following are the standard or built-in data type of Python:
Numeric
Sequence Type
Boolean
Set
Dictionary
Variables
You do not need to declare variables before using them, they are created when you use them.
But you need to be careful with list or array
Variables do not need to be declared with any particular type and can even change type after they have been set.
Every variable in Python is an object.
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
Ex.
# Assigning multiple variables can be done simultaneously
x, y, z = 3, 3.5, "hello"; a = "realcode4you"
print(x)
print(y, z)
print(z + a)
Numbers
Python support integer and floating numbers
# number data type exercise
myInt = 10 # declare an integer var
print(myInt)
myInt = float(10)
print(myInt)
myFloat = 15.7 # declare a float var
print(myFloat)
Arithmetic Operators
Mainly similar with the other programming languages. The only new thing is the floor division operator
Operator Name Example
+ Addition x + y
- Substraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y
Compound operation such as += or //= is available as well
# example of basic operator
x = 5
y = 2
print(x//y)
a = 10
a //=3 # it is equal to a = a // 3
print(a)
# You can concatenate string using +
# we know that z is "hello" and a contains "world"
msg = z + " " + "world"
print(msg)
# You cannot add string and number though (unlike in JavaScript)
print(z+10)
# You can 'multiply' string with number
print(z*6)
Relational and Logical Operator
relational operator such as ==, <, etc are similar to other programming language
logical operator are 'and', 'or' and 'not'
Identity Operator
It is used to compare objects, whether they are actually the same object that occupy the same memory location
Operator Description Example
is Returns true if both variables/objects are the same x is y
is not Returns true if both variables/objects are not the same x is y
Membership Operator
It is used to test if a sequence is present in an object. It is useful in creating loops.
Operator Description Example
in Returns true if a sequence with the specified value
is present in the object x in y
not in Returns true if a sequence with the specified value
is not present in the object x not in y
# exercise of relational, identity and membership
x = 2
print(x==2) # prints out true
print(x==5) # prints out false
print(x<3) # prints out true
print()
x = [1, 2] # x is declared as a list
y = [1, 2]
print(x == y) # prints out true
print(x is y) # Prints out false
print()
name = "Joe"
print(name in ["John", "Joe"]) # prints out true
Type Casting, Input and Output
You can change the data type using float() or int() as needed
You can prompt for user input using inpu()
# print is a function. print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
# statements to ask for inputs from user and cast the value into integer
width = int(input("Enter the width in feet: "))
length = int(input("Enter the length in feet: "))
area = float(width*length/9) # area in m^2
print("\nThe area is ", area, "meter squared")
print("\nFor width %d length %d in feet, the area is %.2f in meter squared" %(width, length, area))
# print with format
x=5; y=10
print('The value of x is {} and y is {}'.format(x,y))
print('I love {0} and {1}'.format('chocolate', 'banana'))
print('I love {1} and {0}'.format('chocolate', 'banana'))
# you can create a multi line statement using backslash
print('Hello {name}, {greeting}'.format(greeting='Good Afternoon!',\
name='Bambang'))
Control Flow
if, elif, and else
An if statement can be optionally followed by one or more elif blocks and a catchall else block if all of the conditions are False:
# example of if, elif and else
x = int(input("Enter a number: "))
if x < 0:
print("It's a negative number")
elif x == 0:
print("It is a ZERO")
elif 0 < x < 20:
print("It is positive less than 20")
else:
print("It is greater than 20")
If any of the conditions is True, no further elif or else blocks will be reached.
With a compound condition using and or or, conditions are evaluated left to right and will short-circuit (i.e. stop further evaluation when a given part of the expression evaluates to true):
# example of short-circuit in condition
a=5;b=7;c=8;d=4
if a<b or c>d:
print("I don't care about the value of c and d!")
In this example, the comparison c > d never gets evaluated because the first comparison was True.
Note: Unlike other popular programming languages you have used before, Python does not have a switch or case statement and also doesn’t have “do…while” loop.
for loops
for loops are for iterating over a collection (like a list or tuple) or an iterator.
The standard syntax for a for loop is:
# example of for loop
seq = [1, 2, 0, 4, 6, 7, 5] # an example of list
total = 0
for value in seq:
total+= value
print(total)
while loops
A while loop specifies a condition and a block of code that is to be executed until the condition evaluates to False or the loop is explicitly ended with break:
# example of while loop
x = 257
total = 0
while total < 500:
total += x
x //= 2
print(total)
The range() Function
Makes it easy to iterate over a sequence of numbers, such as arithmetic progressions.
It takes 1 required argument and 2 optional arguments.
The required argument is a given endpoint (which itself is not part of the sequence)
The optional arguments are the starting point and step/increment (default is 1)
Example:
# example of using range
for x in range(5):
print(x, end=" ") # will print numbers 0, 1, 2, 3, 4
print()
for x in range(3, 6):
print(x, end=", ")
print()
for x in range(3, 8, 2):
print(x, end=" ")
print()
for x in range(9, 2, -1):
print(x, end=" ")
To iterate over the indices of a sequence, you can combine range() and len() as follows:
# an example of using range or len
a = ['Mary', 'has', 'a', 'big', 'lamb']
for i in range(len(a)): # len(a) is the length of sequence a
print(i, a[i])
Break and Continue
The break statement stops loop execution while the continue statement continues with the next iteration of the loop.
In nested loops, the break statement can be used to break out of the innermost for/while loop.
# example of break and continue
for n in range(2,20):
isprime=1
for x in range(2,n):
if n%x == 0:
print(n, 'equals',x,"*",n//x)
isprime=0
break
if isprime>0:
print(n, 'is a prime number')
print('Yay')
Python Data Structure
Tuple
Almost similar to list, however instead of square bracket, it uses parenthesis
Tuple is also immutable, i.e., cannot be changed
# empty tuple
myTup = ()
# a single element tuple needs a comma in its declaration
myTup = (10,) # try to remove the comma if you are brave
print(myTup)
print(myTup[0])
myTup = ('a', 'b', '1', 2, 3)
print(myTup)
print(myTup[-3])
# you can nest a tuple with another tuple
nestedTup = ('a', 'b', 'c'),(1, 2, 3)
print(nestedTup)
# you can create a tuple from a sequence or iterator
myTup = tuple('string123') # from a string
print(myTup)
myTup = tuple([4, 5, 'a']) # from a list
print(myTup)
Tuple Operation
myTup = tuple([True, [1,'a'], 'banana'])
myTup
myTup[0]
# below statement will generate error! you cannot change the tuple
#myTup[0] = False
# unless the tuple itself is mutable, e.g., a list
myTup[1][1] = 2
myTup[1].append('orange')
myTup
a,b,c = (4, 5, 6)
print('The tuple is {2}{1}{0}'.format(a,b,c))
a,*rest = (4, 5, 6, 7)
print('The second variable obtained from the tuple is {}'.format(rest))
myTup = (1,3,2,5,2,7,2,9,0)
myTup.count(2)
2. Lists
Python’s lists are the most flexible data type. It can be created by writing a list of comma separated values between square brackets. The items in the list need not be of the same data type.
It is similar to array in JS. It can hold as many member as you want
# Creating and populating list
myList = [] # create an empty list
myList.append('Fall')
myList.append(2021)
myList.append('CSIS 3290')
print(myList[2])
print(myList[:3])
# create a list from a tuple
myTuple = ('hello', 'csis 3290')
myList = list(myTuple)
print(myList)
myList = list(range(10))
print(myList)
# Be carefult with the index
print(myList[10]) # show the error; IndexError: list index out of range
# example of creating list and combining its values
# putting asterix * in front of your iterable, i.e., list, will decompose the iterable
# allowing us to put a separator
myList = ['CSIS 3290', 'Machine Learning', 'Fall 2021']
print(*myList, sep="--")
Basic List operation
# List operation
a = [1, 2, 3]
b = [4, 5, 6]
print("Concatenation operation: ", a+b)
a.extend(b) # like expand but with a list
print("Extension operation: ", a) # extension is a faster execution than concatenation
a.pop()
print("Extended list after the pop: ",a)
print("Slice of a: ", a[-2:1:-1]) # start with a[-2] --> 4, step with -2, end at index 1
print("Slice of a: ", a[3:1:-1]) # print similar to above
print("Repetition of Hello by 4: ", ['Hello']*4)
# list comprehension. Creating a list with python statement
# create a list using for loop and if statement
num = [1,3,1,5,1,7,8,-1,0,2,4,5]
alist = [i for i in num if i>1]
print(alist)
strings = ['a', 'as', 'bat', 'car', 'dove', 'mobile', 'python']
alist = [x.upper() for x in strings if len(x)>2]
print(alist)
Sort, Zip and enumerate
# sorting
num.sort()
print(num)
num.append(-5)
print(sorted(num))
# zip: pairs up the elements in a number of sequences to create a list of tuple
# it is super useful when we need to pair up different ML algorithms params, or the result of
# our experiments
seq1 = ['Douglas', 'likes', 'banana']
seq2 = [1, 5, 10]
zipped = zip(seq1, seq2)
print(list(zipped))
# enumerate: is like a loop but it will add an additional enumerator value
for i, (a,b) in enumerate(zip(seq1, seq2)):
print('{}: {} {}'.format(i,a,b))
Dictionary
Similar to list/array but instead of index, dictionary has key and value pairs separated by colon
It is defined using curly braces
Keys should be unique and immutable. It can be string, number or event list
Values can be of any data type
# creation
stuID = {}
stuID["Douglas"] = 123
stuID["Bambang"] = 456
stuID["Ivan"] = 789
print(stuID)
print(stuID["Ivan"])
print(stuID.get("Ivan")) # similar to above
# some functions related to dict membership: keys(), values(), items()
for k, v in stuID.items():
print("Student ID of %s is %s" %(k, v))
for i, (k, v) in enumerate(stuID.items()):
print("%d Student ID of %s is %s" %(i, k, v))
# operation
dict1 = {'a': 'some value', 'b':[1,2,3,4]}
dict1[7] = 'an integer'
print(dict1)
# merging two dictionary
dict1.update({'b': 'foo bar', 'c': 12})
print(dict1)
# mapping
dict_map = dict(zip(['one', 'two', 'banana', 'chocolate'], reversed(range(4))))
print(dict_map)
Contact Us:
And get instant help with our expert and professionals with an affordable prices.
Comments