Learn Python 3: Python basics in 7 coding challenges
Tags: python, beginners, tutorial, codenewbie
Published: 2021-07-06 20:08:37

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:**
 
* [Why challenge-based learning?](#why)
* [1. Hello World](#hello-world)
* [2. String concatenation](#string-concatenation)
* [3. List](#list)
* [4. Slicing](#slicing)
* [5. Branching](#branching)
* [6. For loop](#for-loop)
* [7. Functions](#functions)
* [What to learn next](#next)


<br>

<h4><b> Learn Python 3 in half the time with hands-on practice</b></h4>
 
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. 
 
<b>[An Intro to Python 3](https://www.educative.io/courses/intro-python-3)</b>

<br>
 
<a name="why"></a>

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


<br>
 
<a name="hello-world"></a>

## 1. Hello World
Let’s start with a basic puzzle that uses the `print()` function.

```py
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 single quotes to define our string.

<br>

**Challenge 1: Hello World**

What is the output of the above code?

A) `hello world`
B) `'hello world'`
C) `Hello World`

**Solution**

The correct answer is `hello world` because the quotes are used to denote the string but are not parts of the string.

<br>
 
<a name="variables"></a>

## 2. Variables
Now we'll introduce the concepts of variables and float division.

```py
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.

<br>

**Challenge 2: Variables**

What is the output of the above code?

A) `5`
B) `05`
C) `5.0`

**Solution**

The solution is `5.0`. 

Division always returns a floating-point number, meaning it always includes a decimal point value. Here, the decimal point value was zero but must still be included to be a floating point number.


<br>
 
<a name="list"></a>

## 3. List

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

```py
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.

```py
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.

<br>

**Challenge 3: Lists**

What is the output of the above code?

A) `1`
B) `4`
C) `9`
D) `16`
E) `25`

**Solution**

The correct answer is `1`.

 The index passed to a list indicates the position of the desired element. Indices are numbered starting with 0. Therefore, calling the `0`th element of the list prints the first number, `1`.

<br>

> #### 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.
>
><b>[An Intro to Python 3](https://www.educative.io/courses/intro-python-3)</b>

</div>

<br>
 
<a name="slicing"></a>

## 4. Slicing

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

**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.

<br>

**Challenge 4: Slicing**

What is the output of the above code?

A) `galaxy`
B) `alaxy`
C) `5`
D) `6`

**Solution**

The code outputs the number `5` because `len()` checks the length of `galaxy` starting after the first element. The selected portion, `alaxy`, has 5 letters. Therefore, the program prints `5`.

<br>
 
<a name="branching"></a>

## 5. Branching
Now we're moving into some harder challenges. In this challenge, we'll introduce branching and conditional statements.

```py
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`.

<br>

**Challenge 5: Branching**

What is the output of the above code?

`A`
`B`
`C`
`D`
`E`
`F`

**Solution**

The key is to notice the indentation. The first `if` statement asks if `x` is greater than `y`. This is false for our entered input of `(3,7)` so we do not enter that `if` block. Instead, we enter the corresponding `else` statement on line 15. Both of the `if` statements are not true and so we return `F` at the bottom of the `else` block.


<br>
 
<a name="for-loop"></a>

## 6. For loop
Now that we've seen a `while` loop, we'll learn about `for` loops.

```py
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.

<br>

**Challenge 6: For Loops**

What is the output of the above code?

A) `cat mouse`
B) `3 5`
C) `cat`
D) `3`

**Solution**
The answer is `3 5`. 

The `for` loop repeats the code body for every `word` in the `words` list. The code body prints the length of the current selected word. The length of the first `word` is `3` and the length of the second word is `5`. 

<br>
 
<a name="functions"></a>

## 7. Functions
For our final challenge, we'll take a look at a fundamental programming concept: functions.

```py
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.

<br>

**Challenge 7: Functions**

What is the output of the above code?

A) `6`
B) `3`
C) `3+3`

**Solution**

The solution is `6`. 

We first set up the function `func` to return `x+1`. We then add `f` as another valid name for the function. This allows us to call either `func` or `f` and execute the same code block. As a result, the final function all translates to `(2+1) + (2+1)`.

<br>
 
<a name="next"></a>

## 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:
- [Object Oriented Programming (OOP)](https://www.educative.io/blog/how-to-use-oop-in-python) with Python class inheritance
- Python Standard Library
- Implementation with popular outside technologies like [Django](https://www.educative.io/blog/what-is-django-python) or [Pandas](https://www.educative.io/blog/python-pandas-tutorial)
- Advanced Python 3 syntax like [Lambda](https://www.educative.io/blog/python-lambda-functions-tutorial) and Continue statements

To help you get to that point, Educative has launched our new Python course [**An Intro to Python 3**](https://www.educative.io/courses/intro-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!*

<br>

### Continue reading about Python Projects

- [A Complete Guide to Web Development in Python](https://www.educative.io/blog/web-development-in-python)
- [10 Best Python IDEs and Code Editors to use in 2021](https://www.educative.io/blog/best-python-ides-ce-2021)
- [10 Python quirks you should know about in your code](https://www.educative.io/blog/python-quirks-tricks)