Introduction to Python Programming: Variables, Conditionals, and Functions
2020-07-31 15:04:20 | | Part 2 of 7
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. Variables and functions give us the power to store values and behavior, that we can reference and reuse as needed. And conditionals allow us to program logic and decision trees.
With these tools, we can create programs that make thousands of complex decisions and calculations in an instant. Before we begin, 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.
Python 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. If you'd like, take a moment to get familiar some other data types:
Data Type | Description | Keyword | Example |
---|---|---|---|
String | A sequence of literal characters | str | a = 'Hello' |
Integer | A whole positive or negative number | int | a = 123 |
Boolean | A flag set to either True or False | bool | a = True |
Float | A decimal number with double precision | float | a = 12.03 |
List | An ordered, indexed, mutable(can be modified) collection of values (can be any data type, including strings, integers, floats, booleans, tuples, etc. Lists can even store lists.) | list | numbers = [1, 3, 4, 5] |
Tuple | An ordered, indexed, immutable(cannot by modified) collection of values | tuple | coordinates = (1, 3) |
Dictionary | A structured, key/value pair represenation of an object | dict | person = {'name': 'Jane', 'age': 28} |
Set | An unordered, unindexed collection of values | set | vegetables = {'potato', 'carrot', 'onion', 'garlic'} |
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's 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.
Python 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.
Python Logical Operators
Python 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'))
Python Code Commenting
Comments are phrases and sentences inside that code that does not execute. It is meants to be extra information for us and other developers, to better understand the code. Or code that we want to keep in the program, but don't want to delete. Commenting is also useful for quickly deactivating code, while debugging. Use the # symbol to turn a line of code into a comment.
Try It Yourself
With an inline comment, everything to the left of the # will execute, but anything to the right will not.
Python Programming Exercises
Try to solve the following problems, using everything you've learned up to this point. Feel free to share better solutions in the comments. Optimize each solution, as much as possible.
-
Convert a string to an int using Python
Input: '500'
Expected Output: 500
-
Print the length of a string using Python
Input: 'The quick brown fox jumps over the lazy dog'
Expected Output: 43
-
Print an integer squared using Python
Input: 4
Expected Output: 16
-
Print a variable's type using Python
-
Write a Python function that accepts a single integer, and returns True if it is an odd integer
Input: 3
Expected Output: True
Input: 6
Expected Output: False
Conclusion
That's the end of this tutorial. We hope you found it helpful. Make sure to check out our other tutorials, as well.
Comments
You must log in to comment. Don't have an account? Sign up for free.
Subscribe to comments for this post
Info