top of page

Python Assignment Help | Basic Topics For Practice

In this blog we will learn python basic topics which is necessary for every beginners:


  • 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


  • 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)


# Assigning multiple variables can be done simultaneously
x, y, z = 3, 3.5, "hello"; a = "realcode4you"
print(y, z)
print(z + a)


  • Python support integer and floating numbers

# number data type exercise
myInt = 10 # declare an integer var

myInt = float(10)

myFloat = 15.7 # declare a float var

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

a = 10
a //=3 # it is equal to a = a // 3

# You can concatenate string using +
# we know that z is "hello" and a contains "world"
msg = z + " " + "world"
# You cannot add string and number though (unlike in JavaScript)
# You can 'multiply' string with number

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

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

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!',\

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")
    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
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

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

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
for x in range(3, 6):
    print(x, end=", ")
for x in range(3, 8, 2):
    print(x, end=" ")
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):
    for x in range(2,n):
        if n%x == 0:
            print(n, 'equals',x,"*",n//x)
    if isprime>0:
        print(n, 'is a prime number')

Python Data Structure


  • 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

myTup = ('a', 'b', '1', 2, 3)

# you can nest a tuple with another tuple
nestedTup = ('a', 'b', 'c'),(1, 2, 3)

# you can create a tuple from a sequence or iterator
myTup = tuple('string123') # from a string
myTup = tuple([4, 5, 'a']) # from a list

Tuple Operation

myTup = tuple([True, [1,'a'], 'banana'])

# 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

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)

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('CSIS 3290')

# create a list from a tuple
myTuple = ('hello', 'csis 3290')
myList = list(myTuple)

myList = list(range(10))
# 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
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]

strings = ['a', 'as', 'bat', 'car', 'dove', 'mobile', 'python']
alist = [x.upper() for x in strings if len(x)>2]

Sort, Zip and enumerate

# sorting

# 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)

# 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))


  • 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.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'

# merging two dictionary
dict1.update({'b': 'foo bar', 'c': 12})

# mapping
dict_map = dict(zip(['one', 'two', 'banana', 'chocolate'], reversed(range(4))))

Contact Us:

And get instant help with our expert and professionals with an affordable prices.

325 views0 comments


bottom of page