☰
Python Across Disciplines
with Python + AI Tool   
×
Table of Contents

1.1.   Introduction 1.2.   About the Author & Contact Info 1.3.   Book Conventions 1.4.   What (Who) is a Programmer? 1.5.   Programming Across Disciplines 1.6.   Foundational Computing Concepts 1.7.   About Python 1.8.   First Steps 1.8.1 Computer Setup 1.8.2 Python print() Function 1.8.3 Comments
2.1. About Data 2.2. Data Types 2.3. Variables 2.4. User Input 2.5. Data Structures (DS)         2.5.1. DS Concepts         2.5.2. Lists         2.5.3. Dictionaries         2.5.4. Others 2.6. Files         2.6.1. Files & File Systems         2.6.2. Python File Object         2.6.3. Data Files 2.7. Databases
3.1. About Processing 3.2. Decisions         3.2.1 Decision Concepts         3.2.2 Conditions & Booleans         3.2.3 if Statements         3.2.4 if-else Statements         3.2.5 if-elif-else Statements         3.2.6 In-Line if Statements 3.3. Repetition (a.k.a. Loops)         3.3.1  Repetition Concepts         3.3.2  while Loops         3.3.3  for Loops         3.3.4  Nested Loops         3.3.5  Validating User Input 3.4. Functions         3.4.1  Function Concepts         3.4.2  Built-In Functions         3.4.3  Programmer Defined Functions 3.5. Libraries         3.5.1  Library Concepts         3.5.2  Standard Library         3.5.3  External Libraries 3.6. Processing Case Studies         3.6.1  Case Studies         3.6.2  Parsing Data
4.1. About Output 4.2. Advanced Printing 4.3. Data Visualization   4.4  Sound
  4.5  Graphics
  4.6  Video
  4.7  Web Output
  4.8  PDFs & Documents
  4.9  Dashboards
  4.10  Animation & Games
  4.11  Text to Speech

5.1 About Disciplines 5.2 Accounting 5.3 Architecture 5.4 Art 5.5 Artificial Intelligence (AI) 5.6 Autonomous Vehicles 5.7 Bioinformatics 5.8 Biology 5.9 Bitcoin 5.10 Blockchain 5.11 Business 5.12 Business Analytics 5.13 Chemistry 5.14 Communication 5.15 Computational Photography 5.16 Computer Science 5.17 Creative Writing 5.18 Cryptocurrency 5.19 Cultural Studies 5.20 Data Analytics 5.21 Data Engineering 5.22 Data Science 5.23 Data Visualization 5.24 Drone Piloting 5.25 Economics 5.26 Education 5.27 Engineering 5.28 English 5.29 Entrepreneurship 5.30 Environmental Studies 5.31 Exercise Science 5.32 Film 5.33 Finance 5.34 Gaming 5.35 Gender Studies 5.36 Genetics 5.37 Geography 5.38 Geology 5.39 Geospatial Analysis ☯ 5.40 History 5.41 Humanities 5.42 Information Systems 5.43 Languages 5.44 Law 5.45 Linguistics 5.46 Literature 5.47 Machine Learning 5.48 Management 5.49 Marketing 5.50 Mathematics 5.51 Medicine 5.52 Military 5.53 Model Railroading 5.54 Music 5.55 Natural Language Processing (NLP) 5.56 Network Analysis 5.57 Neural Networks 5.58 Neurology 5.59 Nursing 5.60 Pharmacology 5.61 Philosophy 5.62 Physiology 5.63 Politics 5.64 Psychiatry 5.65 Psychology 5.66 Real Estate 5.67 Recreation 5.68 Remote Control (RC) Vehicles 5.69 Rhetoric 5.70 Science 5.71 Sociology 5.72 Sports 5.73 Stock Trading 5.74 Text Mining 5.75 Weather 5.76 Writing
6.1. Databases         6.1.1 Overview of Databases         6.1.2 SQLite Databases         6.1.3 Querying a SQLite Database         6.1.4 CRUD Operations with SQLite         6.1.5 Connecting to Other Databases
Built-In Functions Conceptss Data Types Date & Time Format Codes Dictionary Methods Escape Sequences File Access Modes File Object Methods Python Keywords List Methods Operators Set Methods String Methods Tuple Methods Glossary Index Appendices   Software Install & Setup
  Coding Tools:
  A.  Python    B.  Google CoLaboratory    C.  Visual Studio Code    D.  PyCharm IDE    E.  Git    F.  GitHub 
  Database Tools:
  G.  SQLite Database    H.  MySQL Database 


Python Across Disciplines
by John Gordon © 2023

Table of Contents

Table of Contents  »  Chapter 1 : Preliminaries : Printing

Printing 

Subscribe Contact


Contents

Overview

We will begin our hands-on programming in Python by learning how to display text, numbers, and symbols on the computer screen. In Python programming, we call this printing and use a function called print() to print textual content on the screen. On this page, we will explore the print() function in detail, and, as you will see, we'll use this function extensively throughout this book.

Concept: Printing
Full Concepts List: Alphabetical  or By Chapter 

Printing in Python refers to the action of displaying text or other data on the screen. It's one of the most basic and essential functions in Python programming, especially useful for beginners. When you 'print' something in Python, you are asking the computer to output information to the console or terminal. This is done using the print() function, which takes the data you want to display (like a string of text, a number, or the value of a variable) and writes it to the screen. Printing is a vital tool for debugging, as it allows you to see what your code is doing, track variables' values at different stages, or simply display a message to the user. For instance, the line print("Hello, world!") in Python will display the text "Hello, world!" on your screen. This simplicity makes the print() function a fundamental building block in learning to code with Python.

Common Use & Examples

In Python, we use the print() function and printing to the screen for many different reasons:

Study Tip

Tip: This book contains code examples you can study and copy to try hands-on in your programming environment. When you encounter these throughout the book, I recommend that you close-read each code example, try to understand how it works, be able to explain it verbally, and then copy the code to your code editor, run them and then study the results to confirm your understanding and reinforce concepts and code syntax.

Before we get started coding, it's important to be aware that Python is a case-sensitive programming language, as described here:

Concept: Case-Sensitive

Case sensitivity in Python refers to the way the language distinguishes between uppercase and lowercase letters in identifiers, such as variable names, function names, and class names. In Python, case matters; for example, Variable, VARIABLE, and variable are recognized as three distinct identifiers. This means that Python treats these as completely different entities, and each can be associated with different values or functionalities. The case sensitivity in Python is crucial for maintaining clarity and consistency in code. It enforces good coding practices and helps avoid conflicts or confusions that might arise from inadvertently using the wrong case. For instance, Python's built-in names and keywords are always in lowercase (like int, float, if, else, etc.), and this convention is followed consistently throughout the language's syntax and standard library. Developers often adopt naming conventions, such as using all caps for constants or camelCase/PascalCase for class names, to enhance readability and maintainability of the code.

Printing in Python

Recognized by its name followed by parentheses, the print() function is built into Python, meaning you can use it without any preparations or installations. Inside the parentheses, you place alphanumeric characters (the alphabet, numeric digits, and other symbols) you wish to display (print), known as arguments, enclosed in quotes if the argument is text (e.g., print("Hello, World!")). The print() function is not limited to just printing text data—it is versatile, allowing numbers, variables, and complex expressions as arguments. As you progress, you will find that the print() function is an invaluable tool in Python.

Concept: Strings

In Python, we call text strings. Strings are characters, words, or phrases and contain from one to any number of valid alphanumeric symbols surrounded by quotes (" "). Alphanumeric symbols include the letters of the alphabet, numeric digits (when included in a string, numbers are not numeric but characters of the string), all of the other symbols on the keyboard (~!@#$%^&*()_+=-`{}|[]\:";'<>?,./'`), and extended characters from non-English languages, etc.


Printing Text (Strings)

Try the following examples of printing strings in your editor:

Python Code:

print("Hello, World!")
print("Hello,", "World!")
print("Hello" + "," + " " + "World" + "!")
print("Hello", "World", sep=", ", end="!")
If you wrote these examples the same in your environment and ran them, the output should look like this:

Output:

Hello, World!
Hello, World!
Hello, World!
Hello, World!
Code & Output Details:
  • First, note that all four variations of the print() statement in this example print the same output.
  • Code Lines 1 thru 4: Study the difference in syntax between these four lines.
  • Code Line 1: This is a single string Hello, World! inside the quotes (" ") so the print() function prints the contents of the quotes directly.
  • Code Line 2: This line demonstrates two separate strings, Hello, and World! each inside their own set of quotes (" "). The print() function concatenates the two strings together to print them as one line of output. Pay close attention to the fact that there is no space after the comma in the first string and no space preceding the W in the second string. How does the space get in the output, then? By default, in Python, if you place separate strings in a print() function and separate them with a comma, the print() function will add one blank space between those two strings. Sometimes, this is exactly what you need (like in this example), but sometimes, you need more control over the precise output. In those cases, you might use the techniques shown in Code Lines 3 or 4.
  • Code Line 3: This line demonstrates another, more precise approach to concatenation. In this case, rather than rely on the print() function to place an automatic blank space between individual strings (each enclosed in quoted (" ")), we can use the plus (+) operator to indicate how we want the strings concatenated. In this example, each piece of our overall string is separated into parts and concatenated using the plus operator.
  • Code Line 4: This line demonstrates yet another approach using the print() function's sep and end arguments (see the General Form section below) to specify how to separate the two strings in the concatenated, and what symbol we want at the end of the connected output.
Study Tip

Using the examples above, practice by changing the string and string segments in various ways until you are comfortable with the forms of concatenation using the automatic comma spacing, the plus (+) sign, and the sep/end arguments.

Concatenation

String concatenation is a valuable technique that combines or joins multiple strings. This operation is beneficial when creating longer or more complex strings. Python offers different ways to perform string concatenation. One of the simplest methods is using a comma (,) between strings. For example, if you have two strings, "Hello" and "world", you can concatenate them in a print statement like this:

Python Code:

print("Hello", "world")

Output

Hello world

Concept: Concatenation

Concatenation refers to the act of combining or linking things together in a sequence or series. In programming or computer science, concatenation often refers explicitly to joining strings together to create a single, long string. This is accomplished by placing one string after another, effectively merging their characters or contents. String concatenation is commonly used when working with text or manipulating data in programming languages.

Another method of concatenation is using the plus (+) operator. For example, if you have those same two strings, "Hello" and "world", you can concatenate them using the expression "Hello" + "world", like this:

Python Code:

print("Hello" + "world")

Output

Helloworld
Notice the problem we have, though; using the + operator our two strings have no space between them, because the + operator does exactly what we tell it to do. In this case, we said put these two strings (words) together. Without any other instructions, we get exactly what we asked for.

What if what we wanted was this:

Python Code:

Hello, world!
A comma and a space follow the word world followed by an exclamantion point? We have several options to do this. Here is the code for several approaches and then an explanation of each:
print("Hello" + ", world!")
print("Hello" + ", " + "world" + "!")
print("Hello", end=", ")
print("world!")
print("Hello", end=", ")
print("world", end="!")
print("Hello", "world", sep=", ", end="!")

Output

Hello, world!
Hello, world!
Hello, world!
Hello, world!
Hello, world!

Code & Output Details


Printing Numbers


Next, try the following examples of printing numbers in your editor:

Python Code:

print(10)
print(10, 20, 30)
print(10 + 20 + 30)
If you wrote these examples the same in your environment and ran them, the output should look like this:

Output:

10
10, 20, 30
60

Code & Output Details:


Printing Strings & Numbers Together


We can also combine printing strings and numbers in a single print() function statement. The following examples demonstrate how we might combine strings and numbers in print() function statements.
Concept: Casting

In programming, we often need to convert data from one type to another type. For example, in Code Lines 2 & 3 of this Python code ...

print("Age: " + str(21))
print("Sum: " + str(10 + 20 + 30))


... requires us to cast (convert) the numeric values to strings to concatenate those values with our string labels Age and Sum. In this case, we do this using the str() function, which casts numeric values to string values. The process of converting (casting) data from one type to another is called casting.

Python Code:

print("Age:", 21)
print("Age: " + str(21))
print("Sum: " + str(10 + 20 + 30))
If you wrote these examples the same in your environment and ran them, the output should look like this:

Output:

Age: 21
Age: 21
Sum: 60

Code & Output Details:


Print Function General Form

Every function has a general form. It is important to learn how to interpret general forms. The general form shows all of the options available for any given unit of syntax in a programming language. For example, here is the general form of the print() function:

print(object(s), sep=separator, end=end, file=file, flush=flush)

Concept: Object
Full Concepts List: Alphabetical  or By Chapter 

Objects are an important concept in Python programming, but can be difficult to understand. Let's use the concept of a noun in human language. A noun is a person, place or thing. We often refer to things as objects. Further, we often describe objects by their attributes (color, shape, size, etc.) and by their behaviors, or actions (fly, roll, spin, etc.). For example, the word bicycle is a noun that represents a thing (an object) that we are familiar with. We could say "that bike is red (attribute) and it has two wheels that roll (behavior)."

In many programming languages, like Python, we have a similar conceptual approach and terminology. There are many things (objects) in Python, such as date objects, video, audio, data, people, bicycles, etc. You may be wondering how that's possible, a bicycle in Python? As we proceed, I'll point out objects that already exist in Python, their attributes and behaviors. Also, we'll learn to create our own objects as well. We will also see tools in Python, such as functions, that help us work with objects. The first of these functions that we'll learn is the print function.

print() is the function name, and everything inside the parenthesis ( ) is the function's arguments. The following table describes each argument in the general form of the print() function:

Concept: Arguments

In programming, we often pass data and objects between different segments of our programs. For example, when you call a function, like print(), you can often pass values to that function for it to perform its tasks. These values that we pass are called arguments.

Argument Description
object(s) Any objects in Python and any number of objects. Objects that are not a string of alphanumeric characters are converted to alphanumeric equivalents for printing. Here is an example of a print function call with two objects as arguments. For example:
print("Hi", "Bob")
The output of this print function call would be Hi Bob. Notice the space between "Hi" and "Bob". The reason for this is explained in the sep=separator argument described below.
sep=separator Optional argument. When you specify more than one object to print in one argument list, you can also specify how those objects are separated when printed. The default is a blank space " ". You could change this to any other one or more characters by indicating it here in the second argument of the function call. For example:
print("Hey", "What's up?", sep=", ")
This print function statement has two object arguments: "Hey" and "What's Up?", and the sep=", " indicates that when this statement runs, it should print Hey, What's up? Notice that the sep=", " includes a comma and a space after it so that when the two objects print, they will be formatted properly with a space between the comma and the next word.
end=end Optional argument. You can use this argument to append (add) one or more characters to the end of the output. For example:
print("Hi", "Bob", end="!")
This print function statement has two object arguments, "Hi" and "Bob", and it includes end="!" which results in the output: Hi Bob!. This time, we did not have the sep argument, so we got the single default space " " as the separator between the two objects.
file=file Optional argument. This argument is used with objects that are a bit more complex than simple alphanumeric strings of characters. We will revisit this argument later in the book.
flush=flush Optional argument. This argument is used to manipulate how data is handled internally, which is a bit more complex of a concept for now. We will revisit this argument later in the book.


Escape Sequences (a.k.a. Escaping)

In Python programming, escape sequences are used within strings to represent characters that are not easily typed directly into the code. They are particularly useful in the print() function for formatting the output. An escape sequence starts with a backslash (\) followed by the character that specifies the action to be taken. Common escape sequences include \n for a new line (Enter key), \t for a tab (Tab key), \\ for a literal backslash, and \" or \' for including a literal double or single quote in a string, respectively.

Example:

print("Hello\nWorld")

Output:

Hello
World

Code Details:

Using escape sequences allows for greater control and flexibility in how text is displayed in the output, making it easier to format complex strings. Escape sequences are a fundamental aspect of string manipulation in Python, helping to handle special characters and format text efficiently.

Concept: Escape Sequence
Full Concepts List: Alphabetical  or By Chapter 

In Python programming, escape sequences are special characters used within strings to represent characters that can't be easily typed or have special meaning in Python. Prefaced by a backslash (\), these sequences are interpreted by Python to perform specific functions or represent specific characters. Common escape sequences include \n for a newline, \t for a tab, \\ for a literal backslash, \' for a single quote, and \" for a double quote. These sequences are essential for including characters in a string that would otherwise be interpreted differently by Python. For instance, the newline escape sequence (\n) is widely used to break text into multiple lines. Escape sequences enable more precise control over the formatting and representation of strings in Python code, allowing developers to include a range of characters that are not easily typable or would disrupt the string's syntax if used directly.

See the Reference Materials: Escape Sequences  page for a full list of the sequences available in Python.


Practice Problems

Read the following programming prompts and write a program that solves the problem in your programming environment. Do not read the Solution until you try to solve it yourself first. Once you have completed writing your code, run your program, click the Solution button and compare your work.

Note: There is often more than one way to write solutions in programming. Your solution may not match the solution provided below exactly, which is generally fine if you're getting the required results. Use the provided solution as an example of an approach to learn from while not interpreting it as the only "right" solution.

Problem 1

Write a Python program using the print() function to output the following contact information. Your output should match the format and lines shown here:

Bob Smith
1234 Nowhere Street
Someplace, UT 84999
(801)555-8888
bob@smithco.com



Problem 2

Write a Python program using the print() function with two object arguments and also use the sep and end arguments to print the following output:


Wow, that's great news!




Problem 3

Write a Python program using the print() function with three object arguments to construct a (fictitious) social security number. The three object arguments should be the three sets of numbers that make up an SSN, like 123-45-6789. Also, use the sep argument to separate the three sets of numbers with a dash symbol. Here is an example of the output:



111-22-3333








© 2023 John Gordon
Cascade Street Publishing, LLC