Home

 › 

Articles

 › 

Understanding Basic Python Programs, With Examples

Palindrome in Python

Understanding Basic Python Programs, With Examples

Key Points

  • Python is an object-oriented language but doesn’t force the use of objects or classes, making it distinct from languages like Java.
  • Basic Python programs can be created without functions or classes, such as the classic ‘Hello, world!’ program.
  • Python offers a variety of operators for addition, subtraction, multiplication, division, and more.
  • Flow control in Python can be achieved through if/then/else statements, allowing for user experience design.
  • Functions in Python allow for more efficient and organized code, as seen in a basic calculator program example.

If you’re familiar with object-oriented programming languages, understanding basic Python programs might look a bit different at first glance.

Though it is an object-oriented language—like C# and Java—it doesn’t force the use of objects or classes. This fact distinguishes it from languages like Java, where the main code for the program is contained within a class before you even begin coding your app or software program.

If you’d like to get a preview of what some simple programs might look like in Python, you’ve come to the right place. We’ll dive into the basics first, and then get into operators, conditionals, and functions. Let’s go!

Basic Programs without Functions or Classes

Hello, world!

One of the most basic Python programs is a true beginner classic.

When first learning Python, the standard for many years has been to learn how to display “Hello, world!” on the console.

Python is an extremely easy language to learn at the basic level, and we can accomplish that task quite easy with the following code:

# Program prints "Hello, world!" to the console

print("Hello, world!")

In the first line, we commented to explain what the purpose of our program was. This is a best practice to get into because it will help others understand your code better if you’re working on a development team.

Since this is a simple program that only prints one line, we only explained the basic purpose in our comment.

However, if this was a much bigger, more complex program, you’d want to comment regularly to explain what the purpose of each block of code was.

When you’re leaving short, one-liner comments, it’s fine to use the # symbol. However, if you’re doing multiple lines, you can use a series of three quotation marks at the beginning and at the end to indicate where your documentation begins and ends.

The next statement in this program is a print statement, which is pretty intuitive in Python. You can either put the string or numbers right inside the parenthesis, or you can put your content to be printed inside a variable. If we rewrote this program to do it that way, it might look something like this:

textToPrint = “Hello, world!”
print(textToPrint)

Both these versions of the program would print “Hello, world!” to the Python console. Have a look at a quick video tutorial to see it come together:

Using Operators in Basic Python Programs

No matter what kind of program you’re coding, you’ll likely have to work with operations in Python.

Here is a quick guide that will show you what operators are available to use:

OperatorFunction
+addition
subtraction
*multiplication
/division
%modulus
**exponentiation
//floor division
==equals (comparison)
!=not equals
>greater than
<less than
>=greater than or equal to
<=less than or equal to

Note: Python has many more operators, but these are the basic ones you’ll use regularly.

Here is a simple program that uses some of the most common operators:

# Program uses basic Python operators

x = 5;
y = 10;
z = 2;

print (x**z)
print (x+y-z)
print (y/z)
print (x%z)

The first thing we need to do in our program is initialize our variables. Python automatically detects the type of variable you’re initializing, so you don’t need to declare that when you assign the first value to it. 

The first print statement will print the result of xz to the console, and the result of 52 is 25. Then the second print statement adds x and y together, then subtracts z, giving us a result of 13 printed to the console. The third print statement divides y by z, giving us the value of 5. Then the last print statement deals with the modulus operator. We get a result of 1 output to the console.

If you’re not familiar with modulus, it simply outputs the remainder when you divide the two numbers together. This operator is often useful when you’re trying to determine if a number is even or odd.

Using Conditionals in Basic Python Programs

One thing that’s extremely important to learn in software development is flow control. Put simply, flow control allows you to design how your user experiences the software (or website) you’re developing. One of the most widely used ways this is done is through if/then/else statements. Here is a simple example that instructs the computer to print out a certain message based on a number the user has input.

# Program prints out a message based on user's input

# gets user input

userNumber = int(input("Enter a number: "))

# makes a decision based on that input

if(userNumber == 0):
    print("Your number is zero.")
elif(userNumber < 0):
    print("Your number is less than zero.")
else:
    print("Your number is bigger than zero.")

Since you’re seeing some new syntax, let’s break this down piece by piece:

  1. The first non-comment line of code is initializing a variable with what they enter in response to the input prompt. However, one thing you need to remember about getting input from the user in Python is that the default is to store it as a string. For that reason, we had to cast it as an int so we could later perform more logic on it. If we had not done this, our if/elif statements farther down wouldn’t have worked. In that case, the only response a user would get would be what happens when it hits the else statement.
  2. Next, we have an if statement that checks to see if the number is zero. If it is, in fact, zero, then it prints to the screen the following message: Your number is zero. If not, it moves to the next block of code. If it does actually print out this message, then it skips the elif and else statements.
  3. The next snippet of code is an elif statement, which is Python’s syntax for an else-if statement. It only hits this statement if we don’t get a match with the first if statement. So, if the number is not zero but it is less than zero, it prints the following statement to the console: Your number is less than zero. If that doesn’t evaluate as true, we move to the else statement.
  4. This else statement is only executed if neither the if nor the elif statement evaluates as true. We could have used an elif statement here, but it’s just much simpler to do an else statement because the only other option is that the number received is bigger than zero.

Basic Programs with Functions

So far, we’ve only tackled extremely easy code that executes our programs line by line. However, in a professional environment, Python programmers rarely write syntax this easily.

One of the tools they use regularly is a function. The function allows you to write repetitive code only once. Then you can use it over and over throughout the rest of your program.

One of the great things about this is that if your code needs to change, you only have to change it in one spot for that specific logic.

Calculator Program Example

One of the most basic Python programs you can make using functions is a calculator.

# Program uses multiple functions to calculate based on user entry

# displays menu for user's choice

def GetTask():
    taskBoolean = True
    while(taskBoolean):
        print("Welcome to My Calculator App!")
        print("Here's the menu:")
        print("1: Addition")
        print("2: Subtraction")
        print("3: Multiplication")
        taskChoice = int(input("Enter a number 1 - 3: "))
        if(taskChoice==1):
            Addition()
        elif(taskChoice==2):
            Subtraction()
        elif(taskChoice==3):
            Multiplication()
        else:
            continue
        moreInput = input("What you like to do another calculation? (Y/N)")
        if(moreInput == "y" or moreInput == "Y"):
            taskBoolean = True
        else:
            taskBoolean = False

# handles addition

def Addition():
    numOne = int(input("Enter the first number: "))
    numTwo = int(input("Enter the second number: "))
    numResult = numOne + numTwo
    print(f"{numOne} + {numTwo} = {numResult}")

# handles subtraction

def Subtraction():
    numOne = int(input("Enter the first number: "))
    numTwo = int(input("Enter the second number: "))
    numResult = numOne - numTwo
    print(f"{numOne} - {numTwo} = {numResult}")

# handles multiplication

def Multiplication():
    numOne = int(input("Enter the first number: "))
    numTwo = int(input("Enter the second number: "))
    numResult = numOne * numTwo
    print(f"{numOne} * {numTwo} = {numResult}")

# main program only has one line of code

GetTask()

Since this code is quite a bit longer than our other examples, we’ll unpack it all to explain what’s happening in this code. But, for now, we’re going to skip all the way down to the bottom before we dive into the function.

Look at that last line of code. We could have had a lot more code in the main program, but we chose to only do one thing—run the function that displays the calculator menu. That’s really the workhorse of this entire program because it’s communicating with the user and controlling what code gets executed next.

So, this is what’s happening in that first function:

  1. We declare the function with its name and any parameters needed to make the function do its job the way we intended. We could have set it up where we pass in numbers through the parenthesis. If so, we would have a variable in that parenthesis as a parameter. However, we thought it best to show how easy it would be to adjust one block of code as the program changed over time rather than simply manually coding it into the main program.
  2. Next, we declare a boolean variable that will control whether the while loop runs or not.
  3. The while loop is performing the bulk of the work in this program. First, it needs to evaluate the condition inside the parenthesis. We only need to give it the variable name because it’s a boolean that will evaluate to either true or false. Since we set it to true before we entered the loop, we ensured that it would run at least one time. However, you have to be careful with while loops. If you forget to change it to false at some point, it’s just going to run infinitely.
  4. Next, we printed the menu to show the user the options they could choose from. So, whatever one they pick, this while loop is going to send the user to another function.
  5. Each of the calculator functions are nearly identical, so we won’t break down each of those. But let’s say the user chooses “1” for addition. The loop then sends control over to the Addition() function.
  6. In the Addition() function, the user is prompted for their two numbers to add together. They receive output to the console that shows the operation done and what the result is. The “f” in front of the string to print tells Python that we’re going to parse some variables into the string. You’ll see those variables surrounded by {} symbols. This just makes it extremely easy to format our output.
  7. The Addition() function is done now, so we get sent back into the while loop in the GetTask() function—where we left off. When we return to it, it asks us if we want to perform another calculation. If the answer is “yes,” then we set the boolean variable to true, otherwise it gets set to false. This is an important element of our while loop because it allows us to exit it.
  8. Now, if the user says “yes,” then the while loop executes again. If not, the program stops.

To a beginner, this program might look complicated, but it’s really quite simple when you break it down into smaller parts. That’s another added benefit of using functions—it allows you to code one part of your program at a time, essentially allowing you to start with a minimum viable product, then build on its functionality from there​​.

Wrapping Up

We just looked at a few basic Python programs here. If you want to dive a little deeper, you’ll need to roll up your sleeves and start coding. Fortunately, building something tangible with a little bit of Python knowledge is easy.

Check out a beginner tutorial on Python to get a handle on the basics, then move on to more advanced topics. Programming With Mosh is one of my favorite tech teacher YouTubers, and his crash course series on Python is superb:

Frequently Asked Questions

Is Python a good language for beginners?

Absolutely! Python is one of the best languages for beginners because of its simplicity. It’s easy to read and write, plus there’s a huge community ready to help if you get stuck.

What can I build with Python?

So many things! From simple scripts to automate tasks, web applications, data analysis projects, or even complex systems like machine learning models, Python has got you covered.

How do I run my Python code?

Just save your code in a file ending with “.py” and run it in your terminal using the command “python filename.py”. Make sure Python is installed on your machine first!

How long does it take to learn Python?

This depends on how much time you dedicate daily and what your goals, motivations, and learning habits are. If you don’t know anything about programming, it might take several months to years of regular study before you feel comfortable enough to call yourself “good” or even get a job as a Python developer. But if you are already a developer, then grasping the nuances of Python will come much quicker to you.

To top