Python Encyclopedia for Academics
  • Course Outline
  • Artificial Intelligence
    • Data Science Foundation
      • Python Programming
        • Introduction and Basics
          • Variables
          • Print Function
          • Input From User
          • Data Types
          • Type Conversion
        • Operators
          • Arithmetic Operators
          • Relational Operators
          • Bitwise Operators
          • Logical Operators
          • Assignment Operators
          • Compound Operators
          • Membership Operators
          • Identity Operators
      • Numpy
        • Vectors, Matrix
        • Operations on Matrix
        • Mean, Variance, and Standard Deviation
        • Reshaping Arrays
        • Transpose and Determinant of Matrix
      • Pandas
        • Series and DataFrames
        • Slicing, Rows, and Columns
        • Operations on DataFrames
        • Different wayes to creat DataFrame
        • Read, Write Operations with CSV files
      • Matplotlib
        • Graph Basics
        • Format Strings in Plots
        • Label Parameters, Legend
        • Bar Chart, Pie Chart, Histogram, and Scatter Plot
  • Machine Learning Algorithms
    • Regression Analysis In ML
      • Regression Analysis in Machine Learning
      • Proof of Linear Regression Formulas
      • Simple Linear Regression Implementation
      • Multiple Linear Regression
      • Advertising Dataset Example
      • Bike Sharing Dataset
      • Wine Quality Dataset
      • Auto MPG Dataset
    • Classification Algorithms in ML
      • Proof of Logistic Regression
      • Simplified Mathematical Proof of SVM
      • Iris Dataset
  • Machine Learning Laboratory
    • Lab 1: Titanic Dataset
      • Predicting Survival on the Titanic with Machine Learning
    • Lab 2: Dow Jones Index Dataset
      • Dow Jones Index Predictions Using Machine Learning
    • Lab 3: Diabetes Dataset
      • Numpy
      • Pandas
      • Matplotlib
      • Simple Linear Regression
      • Simple Non-linear Regression
      • Performance Matrix
      • Preprocessing
      • Naive Bayes Classification
      • K-Nearest Neighbors (KNN) Classification
      • Decision Tree & Random Forest
      • SVM Classifier
      • Logistic Regression
      • Artificial Neural Network
      • K means Clustering
    • Lab 4: MAGIC Gamma Telescope Dataset
      • Classification in ML-MAGIC Gamma Telescope Dataset
    • Lab 5: Seoul Bike Sharing Demand Dataset
      • Regression in ML-Seoul Bike Sharing Demand Dataset
    • Lab 6: Medical Cost Personal Datasets
      • Predict Insurance Costs with Linear Regression in Python
    • Lab 6: Predict The S&P 500 Index With Machine Learning And Python
      • Predict The S&P 500 Index With Machine Learning And Python
  • Artificial Neural Networks
    • Biological Inspiration vs. Artificial Neurons
    • Review linear algebra and calculus essentials for ANNs
    • Activation Function
  • Mathematics
    • Pre-Calculus
      • Factorials
      • Roots of Polynomials
      • Complex Numbers
      • Polar Coordinates
      • Graph of a Function
    • Calculus 1
      • Limit of a Function
      • Derivative of Function
      • Critical Points
      • Indefinite Integrals
  • Calculus 2
    • 3D Coordinates and Vectors
    • Vectors and Vector Operations
    • Lines and Planes in Space (3D)
    • Partial Derivatives
    • Optimization Problems (Maxima/Minima) in Multivariable Functions
    • Gradient Vectors
  • Engineering Mathematics
    • Laplace Transform
  • Electrical & electronics Eng
    • Resistor
      • Series Resistors
      • Parallel Resistors
    • Nodal Analysis
      • Example 1
      • Example 2
    • Transient State
      • RC Circuit Equations in the s-Domain
      • RL Circuit Equations in the s-Domain
      • LC Circuit Equations in the s-Domain
      • Series RLC Circuit with DC Source
  • Computer Networking
    • Fundamental
      • IPv4 Addressing
      • Network Diagnostics
  • Cybersecurity
    • Classical Ciphers
      • Caesar Cipher
      • Affine Cipher
      • Atbash Cipher
      • Vigenère Cipher
      • Gronsfeld Cipher
      • Alberti Cipher
      • Hill Cipher
Powered by GitBook
On this page
  • What is print() in Python?
  • Syntax of print()
  • Step-by-Step: Practical Examples
  • Summary
  • Keywords
  1. Artificial Intelligence
  2. Data Science Foundation
  3. Python Programming
  4. Introduction and Basics

Print Function

Nerd Cafe

What is print() in Python?

The print() function in Python is used to display output to the console.

print("Hello, World!")

Output:

Hello, World!

Syntax of print()

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Parameter
Description

*objects

One or more values to print

sep

Separator between values (default is space ' ')

end

What to print at the end (default is newline '\n')

file

Where to send the output (default is screen/console)

flush

Whether to forcibly flush the stream

Step-by-Step: Practical Examples

1. Basic String Output

print("Machine Learning is awesome!")

Output:

Machine Learning is awesome!

2. Printing Variables

model = "RandomForest"
accuracy = 94.5

print("Model:", model)
print("Accuracy:", accuracy)

Output:

Model: RandomForest
Accuracy: 94.5

Practical Tip for ML: Use this to report intermediate results like accuracy, loss, epoch number, etc.

3. Using sep for Formatting

print("Accuracy", 94.5, "percent", sep=" - ")

Output:

Accuracy - 94.5 - percent

Tip: Use sep when printing multiple ML metrics in one line.

4. Using end to Stay on Same Line

for i in range(3):
    print(i, end=", ")

Output:

0, 1, 2, 

Tip: Useful for printing progress, epochs, or loops in ML.

5. Print Multiple Data Types

loss = 0.2456
print("Loss value:", loss, "| Type:", type(loss))

Output:

Loss value: 0.2456 | Type: <class 'float'>

Tip: Always confirm data types when preprocessing data in ML.

6. f-Strings for Clean ML Logging (Python 3.6+)

epoch = 5
acc = 87.23
loss = 0.123

print(f"Epoch: {epoch}, Accuracy: {acc:.2f}%, Loss: {loss:.4f}")

Output:

Epoch: 5, Accuracy: 87.23%, Loss: 0.1230

Tip: f-strings are the most common and readable way to log training progress.

7. Redirecting Output to a File

with open("log.txt", "w") as f:
    print("Training started...", file=f)

Tip: Use this in ML to save logs, especially when training on remote servers.

8. Using flush=True for Real-Time Output

import time

for i in range(3):
    print(f"Training step {i}", end='\r', flush=True)
    time.sleep(1)

Tip: Helpful when printing training progress bars or live metrics in the console.

Summary

Concept
Example

Basic Print

print("Hello")

Variables

print("Accuracy:", acc)

sep

print("a", "b", sep="-")

end

print(i, end=" ")

f-String

print(f"Loss: {loss:.4f}")

To File

print("log", file=f)

Real-time

print(".", end="", flush=True)

Keywords

print function,python print,python output,python basics,print syntax,print examples,sep parameter,end parameter,flush output,print to file,f-strings,ml logging,debugging in ml,python for ml,python variables,real-time printing,training logs,python console output,print multiple values,print formatting, nerd cafe

PreviousVariablesNextInput From User

Last updated 2 months ago