Basic Python

In this article, I am going to write some interesting Q&A or examples of basic Python concept.

For Loop and while

  • Returns the sum of all the divisors of a number, without including it. A divisor is a number that divides into another without a remainder.
def sum_divisors(n):
  # Return the sum of all divisors of n, not including n
  s = sum(list(filter(lambda div : n % div == 0 , range(1, n))))
  return s

# 0
print(sum_divisors(3)) # Should sum of 1
# 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
# 55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
# 114
  • make the print_prime_factors function print all the prime factors of a number. A prime factor is a number that is prime and divides another without a remainder.
def print_prime_factors(number):
  # Start with two, which is the first prime
  factor = 2
  # Keep going until the factor is larger than the number
  while factor <= number:
    # Check if factor is a divisor of number
    if number % factor == 0:
      # If it is, print it and divide the original number
      number = number / factor
      # If it's not, increment the factor by one
  return "Done"

# Should print 2,2,5,5
  • This function prints out a multiplication table (where each number is the result of multiplying the first number of its row by the number at the top of its column). make multiplication_table(1, 3) that will print out:

1 2 3

2 4 6

3 6 9

def multiplication_table(start, stop):
	for x in range(start,stop+1):
		for y in range(start,stop+1):
			print(str(x*y), end=" ")

multiplication_table(1, 3)
# Should print the multiplication table shown above
  • The counter function counts down from start to stop when start is bigger than stop, and counts up from start to stop otherwise.
def counter(start, stop):
	x = start
	if start>stop:
		return_string = "Counting down: "
		while x >= stop:
			return_string += str(x)
			if x != stop:
				return_string += ","
		return_string = "Counting up: "
		while x <= stop:
			return_string += str(x)
			if x!=stop:
				return_string += ","
	return return_string

print(counter(1, 10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10"
print(counter(2, 1)) # Should be "Counting down: 2,1"
print(counter(5, 5)) # Should be "Counting up: 5"


  • Make the is_power_of function return whether the number is a power of the given base. Note: base is assumed to be a positive number. Tip: for functions that return a boolean value, you can return the result of a comparison.
def is_power_of(number, base):
  # Base case: when number is smaller than base.
  if number < base:
    # If number is equal to 1, it's a power (base**0).
    return number ==1

  # Recursive case: keep dividing number by base.
  return is_power_of(number/base, base)

print(is_power_of(8,2)) # Should be True
print(is_power_of(64,4)) # Should be True
print(is_power_of(70,10)) # Should be False
  • The function sum_positive_numbers should return the sum of all positive numbers between the number n received and 1. For example, when n is 3 it should return 1+2+3=6, and when n is 5 it should return 1+2+3+4+5=15.
def sum_positive_numbers(n):
    # The base case is n being smaller than 1
    if n < 1:
        return 0

    # The recursive case is adding this number to 
    # the sum of the numbers smaller than this one.
    return n + sum_positive_numbers(n-1)

print(sum_positive_numbers(3)) # Should be 6
print(sum_positive_numbers(5)) # Should be 15

I think the recursion concept is a bit hard to understand, so I recommend visualized the code step by step for better understanding.

A recursive function must include a recursive case and base case. The recursive case calls the function again, with a different value. The base case returns a value without calling the same function.

A recursive function will usually have this structure:

def recursive_function(parameters):
    if base_case_condition(parameters):
        return base_case_value

In python, the limit of recursion times is 1000 times.


  • Returns the initials of the words contained in the phrase received, in upper case. For example: “Universal Serial Bus” should return “USB”; “local area network” should return “LAN”.
def initials(phrase):
    words = phrase.split()
    result = ""
    for word in words:
        result += word[0].upper()
    return result

print(initials("Universal Serial Bus")) # Should be: USB
print(initials("local area network")) # Should be: LAN
print(initials("Operating system")) # Should be: OS
  • The is_palindrome function checks if a string is a palindrome. A palindrome is a string that can be equally read from left to right or right to left, omitting blank spaces, and ignoring capitalization. Examples of palindromes are words like kayak and radar, and phrases like “Never Odd or Even”. Make a function to return True if the passed string is a palindrome, False if not.
def is_palindrome(input_string):
	# We'll create two strings, to compare them
	new_string = ""
	reverse_string = ""
	# Traverse through each letter of the input string

		# Add any non-blank letters to the 
		# end of one string, and to the front
		# of the other string. 
	new_string = input_string.lower()
	reverse_string = new_string[::-1]
	if " " in new_string:
		new_string = new_string.replace(" ", "")
		reverse_string = reverse_string.replace(" ", "")
	# Compare the strings
	if new_string==reverse_string:
		return True
	return False

print(is_palindrome("Never Odd or Even")) # Should be True
print(is_palindrome("abc")) # Should be False
print(is_palindrome("kayak")) # Should be True
  • Using the format method, create convert_distance function so that it returns the phrase “X miles equals Y km”, with Y having only 1 decimal place. For example, convert_distance(12) should return “12 miles equals 19.2 km”.
def convert_distance(miles):
	km = miles * 1.6 
	result = "{m} miles equals {k:.1f} km".format(m=miles,k=km)
	return result

print(convert_distance(12)) # Should be: 12 miles equals 19.2 km
print(convert_distance(5.5)) # Should be: 5.5 miles equals 8.8 km
print(convert_distance(11)) # Should be: 11 miles equals 17.6 km

If the placeholders include a colon, what comes after the colon is a formatting expression. See below for the expression reference.

Official documentation for the format string syntax


  • The skip_elements function returns a list containing every other element from an input list, starting with the first element. Complete this function to do that, using the for loop to iterate through the input list.
def skip_elements(elements):
	# Initialize variables
	new_list = []
	i = 0

	# Iterate through the list
	for item in elements: 
		# Does this element belong in the resulting list?
		if i%2 == 0:
			# Add this element to the resulting list
		# Increment i

	return new_list

print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
print(skip_elements([])) # Should be []

  • Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames.
filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.
newfilenames = []
for f in filenames:
    if "hpp" == f.split('.')[1]:
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]
  • The odd_numbers function returns a list of odd numbers between 1 and n, inclusively. Using list comprehension. Hint: remember that list and range counters start at 0 and end at the limit minus 1.
def odd_numbers(n):
	return [x for x in range(n+1) if x%2!=0]

print(odd_numbers(5))  # Should print [1, 3, 5]
print(odd_numbers(10)) # Should print [1, 3, 5, 7, 9]
print(odd_numbers(11)) # Should print [1, 3, 5, 7, 9, 11]
print(odd_numbers(1))  # Should print [1]
print(odd_numbers(-1)) # Should print []
  • The highlight_word function changes the given word in a sentence to its upper-case version. For example, highlight_word(“Have a nice day”, “nice”) returns “Have a NICE day”. Can you write this function in just one line?
def highlight_word(sentence, word):
	i = sentence.index(word)

print(highlight_word("Have a nice day", "nice"))
print(highlight_word("Shhh, don't be so loud!", "loud"))
print(highlight_word("Automating with Python is fun", "fun"))
  • A professor with two assistants, Jamie and Drew, wants an attendance list of the students, in the order that they arrived in the classroom. Drew was the first one to note which students arrived, and then Jamie took over. After the class, they each entered their lists into the computer and emailed them to the professor, who needs to combine them into one, in the order of each student’s arrival. Jamie emailed a follow-up, saying that her list is in reverse order. Complete the steps to combine them into one list as follows: the contents of Drew’s list, followed by Jamie’s list in reverse order, to get an accurate list of the students as they arrived.
def combine_lists(list1, list2):
  # Generate a new list containing the elements of list2
  # Followed by the elements of list1 in reverse order
  return list2
Jamies_list = ["Alice", "Cindy", "Bobby", "Jan", "Peter"]
Drews_list = ["Mike", "Carol", "Greg", "Marcia"]

print(combine_lists(Jamies_list, Drews_list))

#output --> ['Mike', 'Carol', 'Greg', 'Marcia', 'Peter', 'Jan', 'Bobby', 'Cindy', 'Alice']
  • Let’s create a function that turns text into pig Latin: a simple text transformation that modifies each word moving the first character to the end and appending “ay” to the end. For example, python ends up as ythonpay.
def pig_latin(text):

  # Separate the text into words
  words = text.split()
    # Create the pig latin word and add it to the list
    # Turn the list back into a phrase
  return " ".join([x[1:]+x[0]+"ay" for x in words ])
print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay"
print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"
  • The group_list function accepts a group name and a list of members, and returns a string with the format: group_name: member1, member2, … For example, group_list(“g”, [“a”,”b”,”c”]) returns “g: a, b, c”. Make a function to do that.
def group_list(group, users):
  members = ", ".join(users)
  return group+": "+members

print(group_list("Marketing", ["Mike", "Karen", "Jake", "Tasha"])) # Should be "Marketing: Mike, Karen, Jake, Tasha"
print(group_list("Engineering", ["Kim", "Jay", "Tom"])) # Should be "Engineering: Kim, Jay, Tom"
print(group_list("Users", "")) # Should be "Users:"

You can create lists from sequences using a for loop, but there’s a more streamlined way to do this: list comprehension. List comprehensions allow you to create a new list from a sequence or a range in a single line.

For example, [ x*2 for x in range(1,11) ] is a simple list comprehension. This would iterate over the range 1 to 10, and multiply each element in the range by 2. This would result in a list of the multiples of 2, from 2 to 20.

You can also use conditionals with list comprehensions to build even more complex and powerful statements. You can do this by appending an if statement to the end of the comprehension. For example, [ x for x in range(1,101) if x % 10 == 0 ] would generate a list containing all the integers divisible by 10 from 1 to 100. The if statement we added here evaluates each value in the range from 1 to 100 to check if it’s evenly divisible by 10. If it is, it gets added to the list.

  1. [expression for variable in sequence] Creates a new list based on the given sequence. Each element is the result of the given expression.
  2. [expression for variable in sequence if condition] Creates a new list based on the given sequence. Each element is the result of the given expression; elements only get added if the condition is true.


  • Let’s use tuples to store information about a file: its name, its type, and its size in bytes. To return the size in kilobytes (a kilobyte is 1024 bytes) up to 2 decimal places.
def file_size(file_info):
	name, extension, size= file_info
	return("{:.2f}".format(size / 1024))

print(file_size(('Class Assignment', 'docx', 17875))) # Should print 17.46
print(file_size(('Notes', 'txt', 496))) # Should print 0.48
print(file_size(('Program', 'py', 1239))) # Should print 1.21

  • Try out the enumerate function. The skip_elements function returns every other element from the list, using the enumerate function to check if an element is in an even position or an odd position.
def skip_elements(elements):
	# code goes here
	newlst =[]
	for i, e in enumerate(elements):
		if i % 2 != 0:
	return newlst

print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
  • The permissions of a file in a Linux system are split into three sets of three permissions: read, write, and execute for the owner, group, and others. Each of the three values can be expressed as an octal number summing each permission, with 4 correspondings to read, 2 to write, and 1 to execute. Or it can be written with a string using the letters r, w, and x or – when the permission is not granted. For example, 640 is read/write for the owner, read for the group, and no permissions for the others; converted to a string, it would be: “rw-r—–” 755 is read/write/execute for the owner, and read/execute for group and others; converted to a string, it would be: “rwxr-xr-x” Make a function to convert permission in octal format into a string format.
def octal_to_string(octal):
    result = ""
    value_letters = [(4,"r"),(2,"w"),(1,"x")]
    # Iterate over each of the digits in octal
    for i in [int(n) for n in str(octal)]:
        # Check for each of the permissions values
        for value, letter in value_letters:
            if i >= value:
                result += letter
                i -= value
                result += "-"
    return result
print(octal_to_string(755)) # Should be rwxr-xr-x
print(octal_to_string(644)) # Should be rw-r--r--
print(octal_to_string(750)) # Should be rwxr-x---
print(octal_to_string(600)) # Should be rw-------
  • The guest_list function reads in a list of tuples with the name, age, and profession of each party guest, and prints the sentence “Guest is X years old and works as __.” for each one. For example, guest_list((‘Ken’, 30, “Chef”), (“Pat”, 35, ‘Lawyer’), (‘Amanda’, 25, “Engineer”)) should print out: Ken is 30 years old and works as Chef. Pat is 35 years old and works as Lawyer. Amanda is 25 years old and works as Engineer. Make a function to do that.
def guest_list(guests):
	for g in guests:
		n = g[0]
		a = g[1]
		w = g[2]
		print( "{} is {} years old and works as {}" .format(n,a,w))

guest_list([('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")])

#Click Run to submit code
Output should match:
Ken is 30 years old and works as Chef
Pat is 35 years old and works as Lawyer
Amanda is 25 years old and works as Engineer

When we covered for loops, we showed the example of iterating over a list. This lets you iterate over each element in the list, exposing the element to the for loop as a variable. But what if you want to access the elements in a list, along with the index of the element in question? You can do this using the enumerate() function. The enumerate() function takes a list as a parameter and returns a tuple for each element in the list. The first value of the tuple is the index and the second value is the element itself.


  • Iterate through the keys and values of the cool_beasts dictionary. Remember that the items method returns a tuple of key, value for each element in the dictionary.
cool_beasts = {"octopuses":"tentacles", "dolphins":"fins", "rhinos":"horns"}
for k,i in cool_beasts.items():
    print("{} have {}".format(k,i))
  • In Python, a dictionary can only hold a single value for a given key. To work around this, our single value can be a list containing multiple values. Here we have a dictionary called “wardrobe” with items of clothing and their colors. Print a line for each item of clothing with each color, for example: “red shirt”, “blue shirt”, and so on.
wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]}
for i, cs in wardrobe.items():
	for c in cs:
		print("{} {}".format(c,i))
  • The groups_per_user function receives a dictionary, which contains group names with the list of users. Users can belong to multiple groups. Return a dictionary with the users as keys and a list of their groups as values.
def groups_per_user(group_dictionary):
	user_groups = {}
	# Go through group_dictionary
	for g, users in group_dictionary.items():
		# Now go through the users in the group
		for user in users:
			# Now add the group to the the list of
			# groups for this user, creating the entry
			# in the dictionary if necessary
			if user not in user_groups:
				user_groups[user] = []	


print(groups_per_user({"local": ["admin", "userA"],
		"public":  ["admin", "userB"],
		"administrator": ["admin"] }))

You can iterate over dictionaries using a for loop, just like with strings, lists, and tuples. This will iterate over the sequence of keys in the dictionary. If you want to access the corresponding values associated with the keys, you could use the keys as indexes. Or you can use the items method on the dictionary, like dictionary.items(). This method returns a tuple for each element in the dictionary, where the first element in the tuple is the key and the second is the value.

If you only wanted to access the keys in a dictionary, you could use the keys() method on the dictionary: dictionary.keys(). If you only wanted the values, you could use the values() method: dictionary.values().

  1. For key, value in dictionary.items() – Iterates over each key,value pair in the dictionary
  2. del dictionary[key] – Removes the item with key key from the dictionary


Python resource: py4e

There are some useful online python compilers we can use in handy, such as programiz, pythontutor…The pythonturor and even let you visualized your code step by step. For easier understanding, pretty cool tool!

Leave a Comment

Your email address will not be published. Required fields are marked *

Follow by Email