Python Exercises For Absolute Beginners

Python programming exercises with solutions for absolute beginners.

1. Create Variable

Create a variable count and assign value 10 to it.

Hint use = operator to assign variable.
Solution
count = 10

2. Check the Variable Type

Create a variable name and assign your name to it. And print the type of the variable

Hint Create variable and use built-in method type to check the variable type.
Solution
name = 'sde.whiletrue.live'
print(type(name))

3. Create Empty Variable

Create a None variable (null value) in other languages and check the variable type.

Hint Like string, int, etc., None is also an object in python.
Solution
empty = None
print(type(empty))

4. Define A Function Which Does Nothing

Define a function which does nothing.

Hint use pass keyword.
Solution
def empty():
  pass
Explanation In python after parenthesis, compiler expected a statement. Use pass if you wish it to do nothing.

5. Condition Checks

Given the code below, what would be the results

def print_true_false(condition):
  if condition:
    print('It is True')
  else:
    print('It is False')

What does the function print_true_false(condition) print if condition is:

  • True
  • False
  • 0
  • 1
  • 0.0
  • []
  • [0]
  • {}
  • set()
  • {1000}
  • dict()
  • ()
  • ''
  • ""
  • 'False'
  • None
Hint Try them yourself in repl
Solution
print_true_false(True) #It is True
print_true_false(False) #It is False
print_true_false(0) #It is False
print_true_false(1) #It is True
print_true_false(0.0) #It is False
print_true_false([]) #It is False
print_true_false([0]) #It is True
print_true_false({}) #It is False
print_true_false(set()) #It is False
print_true_false({1000}) #It is True
print_true_false(dict()) #It is False
print_true_false(()) #It is False
print_true_false('') #It is False
print_true_false("") #It is False
print_true_false('False') #It is True
print_true_false(None) #It is False
Explanation

Python considers empty object as false. Note that, it will not the case for user defined class object.

Example:

class A:
  pass

def print_true_false(condition):
  if condition:
    print('It is True')
  else:
    print('It is False')

a = A()
print_true_false(a) #It is True

6. Initialize Python Data Structures

In repl create empty data structure of type

  • list
  • set
  • dictionary
  • tuple
Hint use builtin methods
Solution
>>> l1 = list() # []
>>> l2 = [] # []
# note you can't create set with `{}`. 
>>> s = set() # set()
>>> d = dict() # {}
>>> d = {} # {}
>>> t = tuple() # ()
>>> t = () # ()
()
Explanation As we have seen in the solution, there are two ways to initialize python data structures except for set().
python programming exercises

Subscribe For More Content