Introduction to Python Programming: Variables, Conditionals, and Functions

2020-07-31 15:04:20 | #programming #python

Tested On

  • Linux Ubuntu 20.04
  • Windows 10
  • macOS Catalina

Now that we have a basic understanding of Python, we can begin to learn about its more dynamic capabilities. With variables and functions, we are able to store elements so that we can reuse them again and again. And using conditionals, we have the ability to program logic and decision trees.

With these tools, we can create programs that make thousands of complex decisions and calculations in an instant. Please complete the prerequisites above, which will ensure you have Python 3 installed and are familiar with VirtualEnv.

How to Set Up a Project Skeleton

How to Create Python Project Files with Windows 10 PowerShell 2.0+

cd ~
New-Item -ItemType "directory" -Path ".\python-fundamentals"
cd python-fundamentals
New-Item -ItemType "file" -Path . -Name "main.py"
virtualenv venv
.\venv\Scripts\activate

To verify that the virtual environment is active, make sure (venv) is in the PowerShell command prompt. For example, (venv) PS C:\Users\username\python-fundamentals>

How to Create Python Project Files with Linux Ubuntu 14.04+ or macOS

cd ~
mkdir python-fundamentals
cd python-fundamentals
virtualenv -p python3 venv
source venv/bin/activate
touch main.py

To verify that the virtual environment is active, make sure (venv) is in the terminal command prompt.

This will create the following files and folders, and activate the virtual environment.

▾ python-fundamentals/
  ▸ venv/
  main.py

Fundamental Python Programming Concepts

Please follow the PEP8 style guide when writing your Python code, as it makes your code more readable to the Python community. Some major highlights:

PEP8: Indentation Should Use 4 Spaces Per Indentation level

Correct:

def add(a, b):
        return a + b

Wrong:

def add(a, b):
      return a + b

PEP8: Functions and Classes Should Be Surrounded By 2 Blank Lines

Correct:

def add(a, b):
        return a + b
      

    def subtract(a, b):
        return a - b
      
      
    if __name__ == '__main__':
        print(add(2, 2))
        print(subtract(2, 2))
        print(subtract(2, 1))

Wrong:

def add(a, b):
        return a + b
    def subtract(a, b):
        return a - b

    def multiply(a, b):
        return a * b
      
    if __name__ == '__main__':
        print(add(2, 2))
        print(subtract(2, 2))
        print(multiply(2, 2))

PEP8: Imports Should Be On Separate Lines Unless You Are Importing from the Same Module

Correct:

import sys
import os
from datetime import timezone, timedelta

Wrong:

import sys, os, datetime
      

Please review PEP8 for more examples.

Variables

Variables allow you to store values and reuse them as much as needed. The following example declares some numbers we can experiment with.

Try It Yourself


 
  

As you can see in the above example, by storing 10 into x and 25 into y, we can reuse the variables multiple times. We can print them individually, add them together, and perform a variety of other operations. Try assigning a number to z adding it to x. Play around with some other combinations.

The next example demonstrates how to declare strings. A string is just a set of literal characters. You can declare them with quotes.

Try It Yourself


 
  

Notice how strings are different from integers (numbers). Strings are declared with quotes and integers are declared without quotes. And they behave differently when you add them together. Strings will literally be combined, whereas integers will actually be added and return a sum.

Try It Yourself


 
  

Did you notice that you can add two integers together, and you can add two strings together, but if you add a integer and a string together, it will result in the error: TypeError: unsupported operand type(s) for Add: 'int' and 'str' on line 8.

One way to prevent this error, is to convert the string to an integer, first, and then add the two integers together. For example: print(a + int(d)). Try it yourself by updating the example above, and clicking the Run button.

You're now familiar with int and str. There are plenty of other data types to learn about (float, list, tuple, range, dict, set, bool), but you don't need to be concerned about them right now. We will cover those in a future tutorial.

Python Conditionals

Python conditional statements allow you to provide logic to your operations, in the form of "if ... then... else". Let's try an example where we create logic for the following sentence: "if x is greater than 50, then print 'True' to the screen, else print 'False' to the screen." Here an example using code:

Try It Yourself


 
  

Try changing the value of x above to less than 50 and see what happens. To make more complex conditionals, you can add more conditions with elif which is short for "else if", like in the following example:

Try It Yourself


 
  

Add as many elif conditions as you need.

Comparison Operators

By now, you should have noticed some new syntax, mainly == and > and <. These are called comparison operators. They allow us to compare if a value is equal to ==, greater than >, or less than < another. Here are a few more operators:

Operator Description Example
== Equal to a == b
> Greater than a > b
< Less than a < b
>= Greater than or equal to a >= b
< Less than or equal to a <= b
!= Not equal to a != b

Try using these new operators in the example above to create more conditionals.

Logical Operators

Logical operators allow you to produce more complex logic and decision trees. and checks if all conditions are true, or checks if at least one condition is true, and not lets you reverse the result of a conditional (returns False if the result True and vice versa).

Try It Yourself


 
  

Python Functions

Similarly to variables, functions/methods are reusable. But instead of storing a value, you can store code blocks into a function. Let's put our examples above into functions to make it easier to reuse them. In the following example, we move our even number checker into a function that we can invoke directly. All of the code that's indented inside the function is a part of that function. Everything else is outside.

Try It Yourself


 
  

Now, everytime we want to check if a number is even, we can just pass that number into the is_even_number function. Experiment by making your own functions.

Feel free to add any of the above examples to your main.py file and run it with python main.py and put the execution code inside the if __name__ == '__main__': block.

Filename: main.py

def is_even_number(x):
    print(isinstance(x, int))
    if isinstance(x, int) and x % 2 == 0:
        return True
    else:
        return False

        
if __name__ == '__main__':
    print(is_even_number(2))
    print(is_even_number(5))
    print(is_even_number('Hello'))

Comments

You must log in to comment. Don't have an account? Sign up for free.

Subscribe to Our Newsletter

Would you like to receive free whitepapers and other IT news? Just leave your email address below. You may opt out at any time.



Tell Us About Your Project









Contact Us

Do you have a specific IT problem that needs solving or just have a general IT question? Use the contact form to get in touch with us and an IT professional will be with you, momentarily.

Hire Us

We offer web development, enterprise software development, QA &amp; testing, google analytics, domains and hosting, databases, security, IT consulting, and other IT-related services.

Free IT Tutorials

Head over to our tutorials section to learn all about working with various IT solutions.

Contact