Hello, Python: A Beginner‘s Guide to Understanding Core Programming Concepts

I often hear from budding developers that they want to learn coding, but don‘t know where to start. With so many languages and frameworks out there, it can definitely feel overwhelming!

That‘s why I recommend Python as a first language – it provides the perfect stepping stone into programming.

(Note: This article focuses on Python 3 specifically, the most current version used today.)

My goal in this guide is to help you, my reader, grasp all the basic concepts needed to start writing Python scripts. I won‘t go too deep into any one topic, but instead want to equip you with an overall mental model for how Python works.

We‘ll move through key features like:

  • Printing – Displaying output
  • Variables – Named values that store data
  • Operators – Symbols that perform actions like math
  • Conditionals – Making decisions by checking conditions
  • Loops – Repeating actions
  • Functions – Reusable blocks of code

Along the way, I‘ll share plenty of annotated code snippets to illustrate each idea.

Let‘s start at the beginning!

Why Learn Python First?

There are a few key advantages that make Python so beginner-friendly:

Simplicity

Python reads much more like English than other languages full of curly braces. The enforced indentation makes the overall flow very easy to follow visually.

Compare a basic "Hello World" program in Java vs Python:

// Java
public class HelloWorld {

  public static void main(String[] args) {

    System.out.println("Hello World!"); 

  }

}
# Python
print("Hello World!") 

Java has a lot more syntactic elements just to print a simple message.

This simplicity allows new programmers to grasp concepts faster in Python without getting mired in complex syntax rules.

Interpreted vs Compiled

Python is an interpreted programming language whereas Java and C# are compiled languages.

This means that unlike compiled code which must first transform source code into machine-readable executables before testing, Python is run line-by-line by an interpreter program.

So if you make a tweak to your Python script, you can immediately test that change and see the output, enabling faster development.

Dynamic Typing

Python utilizes dynamic typing based on value rather than requiring explicit type declarations of variables like many compiled languages.

So where Java requires:

// Declare variable type
String name = "John";
int age = 30;

Python infers types automatically:

# No type declarations needed
name = "John" 
age = 30 

This frees you up as a beginner from needing to know data types right away.

Huge Community

Lastly, Python enjoys substantial community support. Because it‘s open-source and beginner-friendly, there is no shortage of libraries, documentation, and enthusiasts ready to aid programming learners.

This support ecosystem makes development in Python much easier and enjoyable.

Okay, with the basics covered of why Python stands above other first language options, let‘s start coding!

Printing to Screen

The most basic Python program prints a message:

print("Hello World")

Breaking this down:

  • print() is a built-in Python function that outputs text.
  • The message to print goes inside the parentheses.
  • Text must be wrapped in quotes – single or double work. This designates a string value.
  • Execution automatically moves line by line. No need to call print explicitly.

Let‘s tweak this example:

message = "Hello World" # Assign our string to a variable 
print(message) # Reference variable instead  

Now we see variables in action:

  • message is declared by assigning it a string value
  • No data types needed – Python recognizes it as a string
  • We can print variables directly without retyping strings

Being able to store labeled, reusable values in variables helps us start to simplify and better organize code.

Python Data Types

In programming, a data type represents a kind of value. So far we‘ve seen strings, but Python comes with a few built-in types:

Data TypeDescriptionExample
StringText data"Hello"
IntegerWhole numbers25
FloatDecimal numbers5.99
BooleanTrue/False valueTrue
ListOrdered collection[1, 2, 3]
TupleOrdered + immutable collection(1, 2, 3)
SetUnordered unique collection{1, 2}
DictionaryKey-value pairs{"name": "John"}

The major types like strings, integers, and Booleans represent pure values. Structured types like lists and dictionaries allow grouping multiple values together.

Let‘s showcase some types:

# Numbers 
grade = 100 # Integer 
price = 9.99 # Float

# Booleans  
passed = True 

# Strings
name = "Maria"

# Lists - ordered + changeable
lottery_numbers = [17, 58, 32]

# Tuples - ordered + unchangeable 
rgb_values = (255, 192, 203) 

# Sets - unordered + unique items
vowels = {"a", "e", "i", "o", "u"}  

# Dictionaries - key-value pairs
user = {"name": "Sam", "id": 87342}  

Note how we didn‘t have to declare types explicitly. Python identifies the type automatically based on the value structure and properties.

We‘ll use these rich data type options as we advance to more complex programs later.

Operators

Operators are symbols that perform an action between two values. Let‘s explore them through examples.

Math Operators

Just like in math class, common operators like +, -, *, / handle numeric calculations in Python:

# Addition
sum = 30 + 12 # 42

# Subtraction  
difference = 50 - 24 # 26

# Multiplication
product = 20 * 5 # 100

# Division  
quotient = 100 / 20 # 5.0  

We can use operators between hard-coded values, variables, or a mix:

apple_count = 5
orange_count = 3

# Combine variables  
total_fruits = apple_count + orange_count 

# Increment variable
apple_count = apple_count + 1  

There is also % (modulo) for remainder after division, and ** for exponents.

Comparison Operators

To compare two values you can use operators like == (equal), != (not equal), > (greater than) etc.:

age = 25
target_age = 30

is_over_age = age >= target_age # False 

if age != target_age:
   print("Age does not match target")

This allows evaluating logic depending on value relationships.

There are also comparison operators for membership:

techs = ["AI", "Robotics", "VR"]

"AI" in techs # True
"Networks" not in techs # True

Very useful for lists!

Logical Operators

When comparing Booleans, logical operators like and, or, not prove helpful:

is_admin = True
is_editor = False

# AND - True if both true  
can_publish = is_admin and is_editor  

# OR - True if either true
can_draft = is_admin or is_editor

# NOT - Flips 
# not admin so can‘t publish 
can_publish = not is_admin  

We often nest these logical checks for robust conditions.

Operator Precedence

When using multiple operators, some like * and / bind more tightly than others, known formally as operator precedence.

Use parentheses ( ) to dictate explicit order:

x = 5 + 10 * 3 # 35  

# Force addition first
x = (5 + 10) * 3 # 45

Precedence helps understand complex expressions.

We‘ll utilize various operators as we build up sample programs going forward.

Making Decisions with Conditionals

Often programs need to perform different actions based on data values. Here conditionals shine!

Conditionals enable branching code execution based on Boolean tests. Let‘s model an e-commerce scenario:

price = 10
in_stock = True 

# Basic if 
if price < 15: 
   print("Add to cart - good deal!")

if not in_stock:
   print("Unavailable")
else:
   print("In stock!")  

We check two conditions:

  1. Is the price under $15?
  2. Is the item in stock?

This determines the output messages.

We could nest these checks:

# Both tests must pass 
if price < 15 and in_stock:
   print("Add to cart - good deal!") 

To chain multiple decisions, elif (else if) extends an if:

store_has_item = False
local_store = True 

if local_store: 
  print("Checking local store...")

elif store_has_item:
  print("Purchase item!")

else:
  print("Try another store...")  

Here we check local stores first, then all stores before resorting to alternatives.

The indented code blocks representing conditional branches must align properly as Python uses indentation rather than brackets {} to designate branches.

Let‘s up the decision logic with a number guessing game next!

Repeating Code with Loops

Hard-coding repetitive tasks doesn‘t scale as codebases grow. Enter loops!

Loops allow iterative code execution until a condition is met.

Let‘s build an interactive number guessing game with lives using a while loop:

import random 

target = random.randint(1, 10) 
lives = 5

# Repeat game until win or lose
while lives > 0:   

  guess = int(input("Enter guess: "))  

  # Check guess     
  if guess == target:
    print("You guessed correctly!")
    break # Exit loop

  lives -= 1  

  # Provide hint  
  if guess < target:
    print("Too low!")
  if guess > target:
    print("Too high!") 

  print(f"{lives} guesses left!")

if lives == 0: 
  print("You lost... The number was", target)
print("Game over")  

Walking through this:

  • We import Python‘s built-in random library
  • Set a random target number 1-10 and give player 5 lives
  • Start a while loop that continues running until lives reaches 0
  • Get player guess input and check against target
  • Provide high/low hints accordingly
  • Use break to exit loop if guess correct
  • Display remaining lives left
  • After loop, show loss message if lives expired

We repeat similar logic each iteration, showing the usefulness of loops versus manual repetition.

Other loops like for item in list: make iterating lists easier. Loops allow solving more dynamic problems.

Writing Reusable Functions

So far code executes top-to-bottom. We can better organize by grouping code into functions: reusable named blocks that accept inputs.

Consider a function to print sales reports:

# Define function
def print_report(user):

  print(f"Generating report for {user}...")
  # Function body code
  print(f"{user} sales this month:") 
  print("- Products sold: 6")
  print("- Revenue: $12,000")

# Call function  
print_report("Mary") 
print_report("Sam")

Breaking down functions:

  • Define with def name():
  • Enclose parameters in ( ) – names given to inputs
  • Indented blocks represent the function body code
  • return outputs a final value (optional)
  • Call by name print_report("Sam") passing arguments

We can call print_report() repeatedly instead of copying the internals multiple spots.

Let‘s expand with a modular math app:

# Reusable calculator operations 
def add(a, b):
  return a + b

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

def multiply(a, b):
  return a * b  

# Get inputs  
first = float(input("Enter first number: "))  
second = float(input("Enter second number: "))
operation = input("add/subtract/multiply: ")  

# Call matching operation
if operation == "add":   
  print( add(first, second) )

elif operation == "subtract":
  print( subtract(first, second) )  

elif operation == "multiply":
  print( multiply(first, second) ) 

Here we:

  • Define our math operations as functions
  • Get dynamic inputs from user
  • Call the operation function dynamically by matching string
  • This keeps things clean versus putting logic directly in print

Using functions allows encapsulating complexity into single-purpose blocks.

There are also one-liners like lambda for throwaway functions among other advanced options.

Let‘s Review Key Takeaways

Over this guide you‘ve learned fundamental building blocks like:

  • Printing output strings
  • Variables to store labeled data values
  • Data types like strings, numbers to represent values
  • Operators to perform actions between values
  • Conditionals to make decisions on logical tests
  • Loops to repeat tasks iteratively
  • Functions to group reusable logic blocks

These core concepts empower you to start scripting custom Python programs.

With only basic arithmetic you likely couldn‘t tackle calculus right away. Similarly with Python, don‘t jump straight to machine learning before getting comfortable with foundations.

Next steps

I suggest hands-on practice with interactive coding platforms like Replit to apply these basics before moving to advanced topics like:

  • Complex data structures like stacks/queues
  • File reading/writing
  • HTML scraping and data extraction
  • MySQL, MongoDB database access
  • Web development with Django and Flask
  • Game programming with PyGame/Pyxel
  • Data analysis/visualization with NumPy, Pandas, Matplotlib
  • Machine learning/deep learning frameworks like TensorFlow

The world awaits your Python creations! Start coding my friend 🙂

Let me know in the comments if you have any other questions!

Did you like those interesting facts?

Click on smiley face to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

      Interesting Facts
      Logo
      Login/Register access is temporary disabled