Programação Básica
Programação Básica
#include <stdio.h>
void greet() {
printf("Hello, World!");
}
int main() {
greet(); // This is a procedure call
return 0;
}
loves(romeo, juliet).
Each paradigm has its strengths and weaknesses, and the choice of
paradigm can be influenced by other factors such as the specific problem
the program is trying to solve and the programming language in use.
Procedural programming can be useful for simple, straightforward tasks,
while object-oriented programming is widely used in large software
systems. Functional programming is becoming increasingly popular for
tasks that require concurrency or for programs with no side effects.
Logic programming is useful for tasks that involve complex rule systems
or inferences.
1. Start
2. Read the first number (num1)
3. Read the second number (num2)
4. Add num1 and num2 and store the result in sum
5. Display sum
6. Stop
START -> Input num1 -> Input num2 -> Add num1 and num2 -> Store the result in
sum -> Display sum -> END
Variables and constants have a name and a data type associated with
them. The name allows us to refer to the variable, while the data type
defines the kind of data that the variable can hold.
Sometimes, you may need to convert a value from one data type to
another. This is known as type conversion or casting. The two main
types of casting are implicit casting (also known as coercion) and
explicit casting.
int num1 = 5;
float num2 = (float) num1; // Explicitly cast num1 to a float
if condition:
# Code to be executed if condition is true
if condition:
# Code to be executed if condition is true
else:
# Code to be executed if condition is false
if condition1:
# Code to be executed if condition1 is true
if condition2:
# Code to be executed if both condition1 and condition2 are true
else:
# Code to be executed if condition1 is true and condition2 is false
else:
# Code to be executed if condition1 is false
do:
# Code to be executed
while condition
Control flow statements allow you to control the flow of your program.
They include:
Functions are blocks of reusable code that perform specific tasks. They
allow you to break down your program into smaller, more manageable
parts, making your code modular and easier to understand. Functions can
take inputs (arguments) and produce outputs (return values).
def function_name(parameters):
# Function code
return value # (optional)
Arrays and lists are data structures that allow you to store multiple
values of the same or different data types. They provide a convenient
way to work with collections of data.
Arrays and lists have a wide range of algorithms and operations that
can be performed on them, such as sorting, searching, and traversing.
Some common algorithms include:
print("Hello, World!")
In addition to console input and output, programs can read from and
write to files. File input and output operations are essential for data
storage and retrieval.
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
The catch block specifies the type of exception to catch. You can have
multiple except blocks to handle different types of exceptions or
provide a generic except block to handle any exception.
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
finally:
# Code to be executed regardless of an exception
Error handling and exception handling are essential for building robust
and resilient programs that can gracefully handle unexpected
situations.
Example (Python):
def sanitize(input):
return ''.join(e for e in input if e.isalnum())
Example (Python):
try:
risky_operation()
except Exception:
log_error("An error occurred.")
show_user_friendly_error_message()
Some of the most widely accepted and effective secure coding practices
include:
class Circle:
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return 3.14 * self.radius * self.radius
class Animal:
def __init__(self, name):
self.name = name
def sound(self):
pass # Placeholder method
class Dog(Animal):
def sound(self):
return "Woof!"
class Cat(Animal):
def sound(self):
return "Meow!"
dog = Dog("Buddy")
cat = Cat("Whiskers")
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Person:
def __init__(self, name):
self.name = name
def __del__(self):
print("Destructor called")
person = Person("John")
del person # Destructor called
import re
import re
Example (Python):
import threading
def print_numbers():
for i in range(10):
print(i)
def print_letters():
for letter in 'abcdefghij':
print(letter)
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
thread1.start()
thread2.start()
In this example, two threads are created: one to print numbers from 0
to 9, and the other to print letters from 'a' to 'j'. The threads are
started with start(), and join() is used to make sure the program waits
for both threads to finish before it terminates.
Example (Python):
import threading
class BankAccount:
def __init__(self):
self.balance = 100 # shared resource
self.lock = threading.Lock()
account = BankAccount()
thread1 = threading.Thread(target=account.update, args=[50])
thread2 = threading.Thread(target=account.update, args=[-75])
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print(account.balance) # prints 75
Deadlocks and race conditions are two of the main issues in concurrent
programming.
● TCP takes care of the data delivery, but it doesn't worry about
the packet structure or the control of the network.
● IP takes care of the routing of packets. It is responsible for
getting each packet of data to the right destination.
This SQL query selects all fields from the "Employees" table where the
"Salary" field is greater than 50000.
NoSQL databases are a type of database that can handle and sort all
kinds of data, everything from unstructured text documents to
structured data. NoSQL databases became popular as web applications
become more complex and required more diverse ways to store and query
data.
1. Singleton Pattern: Ensures that a class only has one instance, and
provide a global point of access to it.
2. Factory Method Pattern: Defines an interface for creating an
object, but lets subclasses decide which class to instantiate.
3. Abstract Factory Pattern: Provides an interface for creating
families of related or dependent objects without specifying their
concrete classes.
HTML stands for Hyper Text Markup Language. It is used to describe the
structure of web pages using markup. HTML elements are the building
blocks of HTML pages and are represented by tags.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
CSS stands for Cascading Style Sheets. It is used to control the style
and layout of multiple web pages all at once.
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
Frontend and backend development are two sides of the same coin. The
frontend of a web application is the part that users interact with.
It's built with languages like HTML, CSS, and JavaScript.
There are many scripting languages, each with its own strengths and
purposes. Here are a few examples:
● Bash: A Unix shell and command language, good for file manipulation
and program execution.
● Python: A high-level, interpreted language, Python is often used
for web and Internet development, scientific applications, data
analysis, and more.
● JavaScript: Primarily used in web development to add interactivity
to web pages.
● Ruby: A dynamic, open-source programming language with a focus on
simplicity and productivity. It has an elegant syntax that is easy
to read and write.
● Perl: A highly capable, feature-rich programming language with
over 30 years of development.
import os
def rename_files():
file_list = os.listdir(r"<path to directory>")
os.chdir(r"<path to directory>")
for file_name in file_list:
os.rename(file_name, file_name.lower())
rename_files()
print(variable_name)
import pdb
pdb.set_trace() # Set a breakpoint
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("Debug message")
logging.error("Error message")
import unittest
class TestAddNumbers(unittest.TestCase):
def test_add_numbers(self):
result = add_numbers(2, 3)
self.assertEqual(result, 5)
if __name__ == '__main__':
unittest.main()
import unittest
class TestMultiply(unittest.TestCase):
def test_multiply(self):
result = multiply(2, 3)
self.assertEqual(result, 6)
if __name__ == '__main__':
unittest.main()
Version Control Systems (VCS) are tools that help manage changes to
source code and facilitate collaboration among developers. VCS allows
you to track modifications, revert to previous versions, and merge
changes made by multiple developers.
Version control systems manage code repositories, which store the code
and its history. Repository management involves tasks such as creating,
cloning, and managing branches.
git merge <branch_name> # Merge changes from branch_name into the current
branch
# Git will mark conflicts in the file. Edit the file to resolve conflicts and
choose the desired changes.
git add <file_name> # Stage the resolved file
git commit -m "Merge conflict resolution" # Commit the merged changes
There are different methodologies that can be followed within the SDLC.
Two popular approaches are Agile and Waterfall:
Project management tools help manage and track the progress of software
development projects. They provide features for task tracking, team
collaboration, and overall project management. Some popular project
management tools include: