When building functions, debugging scripts, or writing code in general, you'll need to add come commentary to make sure evrything is working as it should. This is where the print() function comes in. This tutorial will cover the following learning objectives:
Different Ways to Use the Print Function
How and Why to Use F-Strings
Different Ways to Use the Print Function
Summary
If you want to pass a basic message to the Terminal (a.k.a Console), use the following syntax: print("[message]")
If you want to pass a message with multiple value, use the following syntax: print([value1], [value2], [value3])
The default ending for a printed message is a new line. If you want to override this, use the end argument with the following syntax: print([value1], end="")
NOTE: If the Terminal in VS Code doesn't open by default, simply press "CTRL + `" (tick mark to the left of the number 1 on your keyboard) to open it. This would be "CMD + `" on Mac.
NOTE:If you want to clear your VS Code Terminal, simply type "clear".
How and Why to Use F-Strings
Summary:
The F-String is used to easily combine raw strings with variables of different data types without needing to change data types. This is used with the following syntax: f'[string] {[variable_name]}'
F-Strings are much easier to use than multi-string concatenation (as shown in the previous tutorial), as it allows you to combine multiple data types without type casting. Example: name = 'Melissa' age = 35 experience = 2.5 f'Hello, my name is {name}! I am {age} years old and have {experience} years of coding experience.'
OUTPUT: "Hello, my name is Melissa! I am 35 years old and have 2.5 years of coding experience."
F-Strings are commonly used in conjunction with the print function to print out dynamic strings. Example: name = 'Ian' print(f'{name} has arrived at the station.')
Exercise
Congratulations! You just completed the Print Function Tutorial! To help test your knowledge, let's
practice outputting some messages to the Terminal.
**It's highly recommended that you
complete the exercise outlined in the previous tutorial before beginning this exercise.**
Instructions:
Open your IDE (e.g., VS Code, PyCharm, Spyder).
Create a New Python File. Name it "print-function.py"
In the Newly Created Python File, complete the following tasks:
Declare a variable named "company" and give it a value of 'XYZ Corporation'.
Declare a variabled named "stock_price" and give it a value of 14.50.
Declare a variable named "stock_exchange" and give it a value of 'NASDAQ'.
Print out the following message: "The Stock Exchange has Opened!"
Print out the following message: "The Buying and Selling Process will Begin NOW!"
Print out the following message: "[company]'s Stock Price is opening at $[stock_price] on the [stock_exchange]."
Exercise Completed! Click here to view the answers.
Have any issues with the above exercise? Post your question on Discord!