Learn Python, Microsoft 365 and Google Workspace
Connect with me: Youtube | LinkedIn | WhatsApp Channel | Web | Facebook | Twitter
web development
, data science
, machine learning
, and automation
.PyCharm
, or even a simple text editor like Notepad
.Important: Python source code files always use the
.py
extension.
print
Functionprint
function.print
function features like formatting and special characters.print
The print
function is used to output text or variables to the console. or to a file.
Video: Use of print() function in python
Syntax:
print(value1, value2, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Parameters:
value1, value2, ...
: The values to be printed. Multiple values can be separated by commas.sep
: (Optional) Specifies how to separate multiple values. Default is a space ' '
.end
: (Optional) Specifies what to print at the end. Default is a newline character '\n'
.file
: (Optional) Specifies the file where to print. Default is sys.stdout
(console).flush
: (Optional) Specifies whether to forcibly flush the stream. Default is False
.Instructions:
Examples
# Task 1.1: Print a simple message
print("Hello, world!")
# Task 1.2: Print multiple items
print("Hello", "world", 2024)
Instructions
Examples
# Task 2.1: Print different data types
print(42)
print(3.14159)
print("This is a string")
sep
and end
ParametersInstructions
Examples
# Task 3.1: Change the separator
print("apple", "banana", "cherry", sep=", ")
# Task 3.2: Change the ending character
print("Hello", end=" ")
print("world!")
# Task 3.3: Print with a custom ending character:
print("Hello", "World", end="!")
Instructions
# Task 4.1: print a integer variable
x = 5
print(x)
# Task 4.2: print a string variable
message = 'Python is fun'
# print the string message
print(message)
# Task 4.3: print a string variable
message = "How are you?"
print(message)
Instructions
Examples
# Task 5.1: Use f-strings
name = "Ahmad"
age = 30
print(f"My name is {name} and I am {age} years old.")
Python f-Strings Explained: What Does print(f’{a=}’) Do?
The expression print(f”{a=}”) is part of Python’s f-string formatting introduced in Python 3.8.
When you use a=, Python prints both the name of the variable and its value. Essentially, it shows what the variable is and its corresponding value.
Instructions
Examples
# Task 6.1: Print a newline character
print("Hello\nWorld")
# Task 6.2: Print a tab character
print("Hello\tWorld")
video: Python line break: How to Print Line Break
# Task 6.3: Print a tab character
print("Name\tAge\tCity")
print("Alice\t30\tNew York")
print("Bob\t25\tLos Angeles")
Output:
Name Age City
Alice 30 New York
Bob 25 Los Angeles
In this example, \t
is used to align the columns of text.
In Python, the \t
character is a special escape sequence that represents a horizontal tab. When used in the print
function or any other string operation, it inserts a tab space in the output. This can be particularly useful for formatting text to make it more readable.
\t
can be combined with other string manipulation techniques, such as f-strings
# Task 6.4: Print a tab character with f-strings
name = "Alice"
age = 30
city = "New York"
print(f"{name}\t{age}\t{city}")
Instructions
Examples
# Task 7.1: Print to a file
with open("output.txt", "w") as file:
print("Hello, file!", file=file)
When you use the instruction with open(“output.txt”, “w”) as file in Python, the file is created in the current working directory of your program. On an Android system, this could be different depending on the environment where the code is executed (e.g., a specific app’s data directory, a shared storage location, etc.).
To determine the exact path, you can use the os module to get the current working directory:
import os
print(os.getcwd())
Regarding file closure, when you use the with
statement to open a file, Python automatically takes care of closing the file for you once the block of code under the with
statement is executed. There is no need to explicitly close the file; it is done automatically when the block is exited. This is one of the benefits of using the with statement for file operations. for more details, see Appendix A
Objective: Learn about syntax errors in Python by examining and correcting a sample code snippet.
Instructions:
Code Snippet:
print("Hello World!"
Steps:
print("Hello World!")
Syntax error:
See also:
print()
function to display it.\t
(tab character) to align item names and prices neatly.name
, age
, and hobby
.print()
function to create a sentence incorporating these variables."Hello World\n" * 100
) as a possible solution.related video: 100 times “hello world” without loop
print()
statements.\n
).Related Video: How to print multiple lines
"w"
).write()
method.
There are two main types of comments in Python:
# This is a single-line comment
print("Hello, World!")
"""
This is a multi-line comment.
It can span multiple lines of code.
"""
print("Hello, World!")
See also:
In Python, indentation refers to the use of whitespace (spaces or tabs) to denote block-level structure in the code. Python uses indentation to define the scope of code blocks, such as:
In Python, indentation is mandatory and is used to determine the grouping of statements. The number of spaces used for indentation is not fixed, but it’s standard to use 4 spaces for each level of indentation. Read more: Indentation - PEP 8 – Style Guide for Python Code
Here’s an example:
if True:
print("Hello") # This line is indented with 4 spaces
print("World") # This line is also indented with 4 spaces
In this example, the two print statements are indented with 4 spaces, indicating that they are part of the if block.
Python’s indentation system has several benefits, including:
Another example, consider the following code snippet:
if True:
print("True")
else:
print("False")
Task: 15 Please correct the following Python code:
if True:
print("True")
print("False")
Error message: IndentationError: unexpected indent
”
See also:
Title: “Teach Your Team”
Instructions:
💡 Key Learning Points:
✔ Leadership through teaching.
✔ Confidence in public speaking.
✔ Understanding Python better by explaining it.
Task: Identify and fix the syntax error in the following code snippet.
print("Hello World!"
Error: SyntaxError: The closing parenthesis is missing.
Corrected Code:
print("Hello World!")
Task: Fix the indentation error in the following code snippet.
if True:
print("Hello")
print("World")
Error: IndentationError: unexpected indent
at the second print statement.
Task: Fix the error where the variable name is incorrectly used.
name = "Ahmad"
print(f"My name is {namee} and I am 30 years old.")
Error: NameError: name 'namee' is not defined
because namee
is not the correct variable name.
Task: Correct the following code by adding the necessary module import.
print(os.getcwd())
Error: NameError: name 'os' is not defined
because the os
module was not imported.
Corrected Code:
import os
print(os.getcwd())
Task: Fix the syntax issue in printing to a file.
with open("output.txt", "w") as file:
print("Hello, file!", file=file)
Error: IndentationError: expected an indented block
because the print statement is not indented.
Corrected Code:
with open("output.txt", "w") as file:
print("Hello, file!", file=file)
Answer Key (True/False):
Python
Answer: B) A high-level programming language
Answer: A) Visual Studio Code
Answer: A) pip
Answer: A) Integrated Development Environment
Answer: B) To create isolated environments for different Python projects
Answer: A) Git
Which of the following is the correct extension of the Python file? [Python Quiz #51]
Answer: B) Writing and sharing code, visualizations, and text
Answer: B) Guido van Rossum in 1991
Answer: B) To manage and isolate project-specific dependencies
Answer: C) A repository of software for the Python programming language
pip
in Python?
Answer: B) A package installer
Answer: C) venv
Answer: C) PyCharm
Answer: C) Python supports object-oriented programming
Answer: B) Compiled language
print function
[video:Can You Guess the Output of this Python Code? | print Quiz](https://youtu.be/WD92M8WXRZM?si=1FgSE-5Vr1aFCVR-) |
Code:
print("I", "love", "Python", sep="-")
Options:
Watch the video for the answer: https://youtube.com/shorts/WD92M8WXRZM?si=kJ5jbIAaIlJ_63ia
x = 5
y = 3
print("The value of x is", x, "and the value of y is", y)
Watch the video for the answer: https://youtube.com/shorts/ZE2yfAJsCxk?si=6UvXfKLmR56c-Qu9
print("Hello, world!")
How can you print multiple values on a single line in Python?
Create a list of the values and print the list.
Which of the following statements will print the value of the variable x?
echo x
What is the purpose of the sep argument in the print function?
To specify the format of the output.
What is the purpose of the end argument in the print function?
To specify the format of the output.
How can you print a string without a newline character?
print(string; “”)
name = "Alice"
age = 30
print("My name is", name, "and I am", age, "years old.")
semicolon
at the end of the print statement (this is not valid Python syntax)end
argument within the print function and setting it to an empty string (“”)prin("Hello World!")
Hint NameError: name ‘prin’ is not defined.
print("Hello World!"
Comments:
What is the primary purpose of comments in Python code?
To create errors for debugging
Which of the following is the correct syntax for a single-line comment in Python?
{ This is a comment }
How can you create a multi-line comment in Python?
Using the comment keyword
What happens when you run code that includes comments?
Indentation:
Answer: a) To define code blocks
Answer: b) Using spaces (Python recommends using 4 spaces for indentation)
Answer: b) In Python, improper indentation specifically results in an IndentationError. While a syntax error is a broad category for any error in the syntax, an IndentationError is a specific type of syntax error related to incorrect indentation.
if True:
print("True")
print("False")
Answer: b) Extra indentation (the second print statement has extra indentation)
Answer: b) 4 spaces
a)
```python
if True:
print("True")
print("False")
b)
if True:
print("True")
print("False")
c)
if True:
print("True")
print("False")
d)
if True:
print("True")
print("False")
Answer: b)
if True:
print("True")
print("False")
Hello, World!
Solution:
print("Hello, World!")
name
and age
, and print them using the print
function. Use the variables to print the following:
My name is John and I am 25 years old.
Solution:
name = "John"
age = 25
print("My name is", name, "and I am", age, "years old.")
name
and age
:
My name is John and I am 25 years old.
Solution:
name = "John"
age = 25
print(f"My name is {name} and I am {age} years old.")
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Solution:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Solution:
number = int(input("Enter a number: "))
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
name = "Alice"
age = 30
print(f"{name} is {age} years old.")
Solution:
# Assign the string "Alice" to the variable 'name'
name = "Alice"
# Assign the integer 30 to the variable 'age'
age = 30
# Print the name and age using an f-string
print(f"{name} is {age} years old.")
def add(a, b):
return a + b
result = add(3, 5)
print(result)
Solution:
"""
This program defines a function 'add' that takes two arguments 'a' and 'b'
and returns their sum. It then calls this function with the arguments 3
and 5, stores the result in the variable 'result', and prints the result.
"""
def add(a, b):
return a + b
result = add(3, 5)
print(result)
[1] “Guido van Rossum,” Wikipedia, May 24, 2021. https://en.wikipedia.org/wiki/Guido_van_Rossum
os.getcwd()
is a function in Python that returns the current working directory (CWD) of the script. The “current working directory” is the folder from which your Python script is running. It is useful for figuring out the exact location of the script during execution.
Explanation:
os
: This is the module in Python that provides a way to interact with the operating system.getcwd()
: This function within the os
module returns a string representing the current working directory.Example:
import os
# Get the current working directory
current_directory = os.getcwd()
# Print the current working directory
print("Current Working Directory:", current_directory)
Output: If you run this script, you might get an output like this (depending on where the script is being executed):
Current Working Directory: /Users/yourusername/Documents/my_project
This tells you that the script is being run from the /Users/yourusername/Documents/my_project
directory.
Use Case: Imagine you are writing a script that needs to read or write files. Knowing the current working directory will help ensure you reference the correct paths to those files.
Compile time and run time refer to different phases in the lifecycle of a program:
Compile Time:
Definition: This is the phase when the source code is converted into machine code (or bytecode) by a compiler.
Errors: Errors that occur at compile time are typically related to syntax or static type checks (in statically typed languages). These include things like syntax errors, missing semicolons, or mismatched data types.
Duration: This happens before the program is executed. In languages like C, Java, and C++, the code is compiled before it is run.
Key Point: The program cannot run if there are compile-time errors.
Run Time:
Definition: This refers to the phase when the compiled code is executed by the machine or interpreter.
Errors: Run-time errors occur while the program is being executed. These include logical errors, exceptions, or any unexpected input or environment conditions (like division by zero or file not found errors).
Duration: This happens after the compilation phase (in compiled languages) or during interpretation (in interpreted languages like Python).
Key Point: The program is actively running and performing tasks.
Summary:
Compile time is when the code is translated into machine code before execution.
Run time is when the code is actively being executed on the machine.