Home/Blog/Learn to Code/Learn Python 3: Python basics in 7 coding challenges
Home/Blog/Learn to Code/Learn Python 3: Python basics in 7 coding challenges

Learn Python 3: Python basics in 7 coding challenges

Ryan Thelin
Jun 30, 2021
9 min read

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Python 3 is the latest version of Python, a popular programming language used mainly for web development, data science, and machine learning. Python has quickly become one of the most popular programming languages for new developers because of the wide range of uses in software development and some of the great improvements added since Python 2.

Today, we’ll walk you through a hands-on, challenge-based tutorial to get you started with Python quickly!

Here’s what we’ll cover today:


Learn Python 3 in half the time with hands-on practice

Our new 50 challenge Python course lets you skip the book work and get right to hands-on learning, with challenges ranging from beginner to expert difficulties.

An Intro to Python 3


Why challenge-based learning?#

Not everyone learns new programming languages the same way. For many aspiring Python programmers, book learning is inefficient and doesn’t lead to lasting learning. The main flaws of book learning are that it doesn’t invite the reader to directly engage and it encourages memorization instead of the natural exploration of programming concepts.

To avoid the downsides of book learning, many would rather learn to code by exploring Python code through hands-on, challenge-based crash courses. This method is great for hands-on learners because it allows absolute beginners to learn both the theory and pragmatic use case for every basic concept or algorithm.

The challenges encourage you to explore the problems naturally and learn to use Python syntax through investigation rather than lecturing.


1. Hello World#

Let’s start with a basic puzzle that uses the print() function.

print('hello world')

The print() function allows you to connect your program to the outside world. This function, as the name indicates, prints a value to the standard output.

You can think of the standard output as the environment in which your Python program lives. Your standard output is the air around you. Let’s say you shout “Ouch!” Every person in your environment can read from your standard output that you just experienced pain. The data that is printed to the standard output is of the string data type.

A string is a sequence of characters.

You can define a string in Python in any of the following ways:

  • Single quotes ('hello world')
  • Double quotes ("hello world")
  • Triple quote ('''hello world''' and """hello world""")

In the puzzle, we use the single quote to define our string.

Challenge 1: Hello World

Q

What is the output of the above code?

A)

hello world

B)

'hello world'

C)

Hello World


2. Variables#

Now we’ll introduce the concepts of variables and float division.

x = 55 / 11
print(x)

The puzzle has two goals. First, it introduces the concept of variables. Python evaluates the result of the expression on the right side of the equation and stores it in the variable x. After defining the variable, you can access it at any point in the program code.

Second, it forces you to read code carefully due to a twist: Division operations always return a floating-point number. Thus, variable x stores the float value 5.0. The print function outputs the result as a float and not as an integer value 5.

This is the source of most errors in the code. People focus too much on what they mean (semantics) and too little on how they say it (syntax).

Tip: Programs always execute instructions according to syntax, which may be different from what you intended. The key is to get used to thinking like a computer.

Challenge 2: Variables

Q

What is the output of the above code?

A)

5

B)

05

C)

5.0


3. List#

This puzzle introduces lists, our first data structure in Python.

squares = [1, 4, 9, 16, 25]
print(squares[0])

The data type is “abstract” because you can use lists independently of the list elements’ concrete data types. Most complex algorithms that you’ll learn later will use lists as a building block. Many famous algorithms such as quicksort are based only on a single list as their core data structure.

The pythonic way of handling lists and list access is simple and clean. You can create a list by writing comma-separated values between the opening and closing square brackets.

lst = [1, 4, 9, 16, 25] 

You access the i-th element in a list lst with the intuitive bracket notation lst[i]. This notation is consistent for all compound data types, such as strings and arrays.

Challenge 3: Lists

Q

What is the output of the above code?

A)

1

B)

4

C)

9

D)

16

E)

25


Keep building your Python programming experience.#

Learn Python concepts from data structures to decorators, all with step-by-step challenges. Educative’s hands-on courses let you learn the languages and tools you need quickly, with real-world examples and in-browser code environments.

An Intro to Python 3


4. Slicing#

Now, we’ll explore how to use slicing and some more advanced variable manipulation.

word = "galaxy"
print(len(word[1:]))

Slicing

Slicing is a Python-specific concept for accessing a range of values in sequence types, such as lists or strings. It is one of the most popular Python features. Understanding slicing is one of the key requirements for understanding most existing Python codebases.

The idea behind slicing is simple. Use the bracket notation to access a sequence of elements instead of only a single element. You do this via the colon notation of [start: end]. This notation defines the start index (included) and the end index (excluded).

Tip: A very common source of bugs is forgetting that the end index is always excluded in sequence operators.

For the sake of completeness, quickly look into the advanced slicing notation [start:end:step]. The only difference to the previous notation is that it allows you to specify the step size. For example, the command 'python'[:5:2] returns every second character up to the fourth character, i.e., the string pto.

len()

The len() function is a handy tool to get the length of built-in Python data types, such as strings, lists, dictionaries, or tuples.

Challenge 4: Slicing

Q

What is the output of the above code?

A)

galaxy

B)

alaxy

C)

5

D)

6


5. Branching#

Now we’re moving into some harder challenges. In this challenge, we’ll introduce branching and conditional statements.

def if_confusion(
x, y):
if x > y:
if x - 5 > 0:
x=y
return "A" if y == y + y else "B"
elif x + y > 0:
while x > y: x -= 1
while y > x: y -= 1
if x == y:
return "E"
else:
if x - 2 > y - 4:
x_old = x
x=y*y
y = 2 * x_old
if (x - 4) ** 2 > (y - 7) ** 2:
return "C"
return "D"
return "F"
print(if_confusion(3, 7))

Just like any other programming language, Python also has Conditional Statements also known as Branching Statements. To create branches, you can use the keywords if, else, or elif. These statements return Booleans, true if the condition is met and false if it is not.

Tip: The computer does not execute the code strictly from top to bottom, and you shouldn’t either.

Instead, start where the program execution starts, which is at the bottom with the function call if_confusion(3, 7). Now you know that x=3 and y=7. Then, you proceed to do what the interpreter does.

As x>y is false, you can skip the whole upper part of the function. Similarly, you can skip the if branch for x-2>y-4.

Challenge 5: Branching

Q

What is the output of the above code?

A)

A

B)

B

C)

C

D)

D

E)

E

F)

F


6. For loop#

Now that we’ve seen a while loop, we’ll learn about for loops.

words = ['cat', 'mouse']
for word in words:
print(len(word))

Tip: Repeated code is redundant and hard to read, debug, and maintain. As programmers, we should avoid redundant code at all costs.

The Python for loop statement is a way out of redundant code. With a for loop, you write code once and put it into different contexts.

Among the ingredients that make a programming language powerful are control flow statements. The Python for loop is one such control flow statement. It repeats the execution of the code body for all sequence elements, iterating over all elements in the order of the sequence. It’s similar to a forEach loop found in Java or JavaScript.

In the puzzle, the variable word takes first the value cat and second the value mouse. We then print out the length of each word.

Challenge 6: For Loops

Q

What is the output of the above code?

A)

cat mouse

B)

3 5

C)

cat

D)

3


7. Functions#

For our final challenge, we’ll take a look at a fundamental programming concept: functions.

def func(
x):
return x + 1
f = func
print(f(2) + func(2))

A function encapsulates a sequence of program instructions. The ideal function solves a single high-level goal.

For example, you can encapsulate the task of searching the web for specific keywords into a named function. This allows you to call for a search later using just a single statement.

Functions allow you to write code once and reuse it later or in other programs. Reusing code is more efficient than writing the same code each time. Suppose you want to calculate the square root of 145. You could either calculate it for the specific value 145 or define a function that calculates the square root for any value x.

Defining a function

You can define a function with the keyword def, followed by a name and the function’s arguments. The Python interpreter maintains a symbol table that stores all function definitions, i.e., mappings from function names to function objects.

This allows the interpreter to relate each occurrence of the function name to the defined function object. A single function object can have zero, one, or even many names.

In the puzzle, we assign the function object to the name func and then reassign it to the new name f. We can then use both the names to refer to the same code.

Upon the function call, the Python interpreter will find the function in the symbol table and execute it. This can make your code more readable when calling the same function in different contexts.

Challenge 7: Functions

Q

What is the output of the above code?

A)

6

B)

3

C)

3+3


What to learn next#

Now that you’ve completed these 7 challenges, you have programming experience with the major building blocks of most Python 3 programs. Transitioning to a new language can be tough, but know that you’re making a great investment in your education. Python is the best general-purpose language in use today and there has never been a better time to start learning Python!

As you continue your journey to become a python programmer, look for Python projects on concepts like:

To help you get to that point, Educative has launched our new Python course An Intro to Python 3. This course features 50 challenges that provide hands-on experience with all the skills you’ll need to jump into building Python projects. The course’s challenge-based learning approach is perfect for developers looking to transition to Python because it draws on your existing coding intuition to learn in half the time.

Happy learning!


Continue reading about Python Projects#


  

Free Resources