Curso Python #06 - Tipos Primitivos e Saída de Dados
Table of Contents
Introduction
This tutorial covers the basics of primitive data types in Python, specifically focusing on int
, float
, bool
, and str
. Additionally, we will explore how to perform basic operations using the print()
function. Understanding these concepts is essential for anyone starting with Python programming, as they form the foundation for more complex operations.
Step 1: Understanding Primitive Data Types
Primitive data types are the building blocks of data manipulation in Python. Here are the main types you will encounter:
-
Integer (
int
): Represents whole numbers, both positive and negative.- Example:
5
,-3
,0
- Example:
-
Floating Point (
float
): Represents real numbers with decimal points.- Example:
3.14
,-0.001
,2.0
- Example:
-
Boolean (
bool
): Represents truth values, eitherTrue
orFalse
. -
String (
str
): Represents a sequence of characters enclosed in quotes.- Example:
"Hello, World!"
,'Python'
- Example:
Practical Tip
When defining variables, make sure to use the correct data type based on the context of your program.
Step 2: Converting Between Types
You can convert between these primitive types using built-in functions. Here’s how:
-
Convert to Integer: Use
int()
num = int(3.7) # Converts float to int, resulting in 3
-
Convert to Float: Use
float()
num = float(5) # Converts int to float, resulting in 5.0
-
Convert to Boolean: Use
bool()
value = bool(0) # Converts 0 to False
-
Convert to String: Use
str()
text = str(100) # Converts int to str, resulting in '100'
Common Pitfall
Remember that converting non-numeric strings to integers or floats will raise an error. For example, int("abc")
will not work.
Step 3: Using the Print Function
The print()
function in Python is used to output data to the console. Here’s how to use it effectively:
-
Basic usage:
print("Hello, World!")
-
Printing variables:
name = "Alice" age = 30 print(name, "is", age, "years old.")
-
Formatting output: You can format strings using f-strings (Python 3.6+):
print(f"{name} is {age} years old.")
Practical Tip
Use commas to separate multiple items in the print()
function. This automatically adds spaces between them, making your output cleaner.
Conclusion
In this tutorial, we covered the basic primitive data types in Python and how to convert between them. We also explored how to use the print()
function for outputting data. To further enhance your Python skills, practice these concepts by creating small programs that utilize different data types and outputs.