# funções
#sintaxe - def+nome que queremos dar à função + (nome do argumento que queremos dar á função separado por ,)+ : Para ela devolver um valor temos de escrever a expressão return, a partir do momento que é cumprida não se executa mais nenhuma linha do código, se não for devolvida executa-se as restantes linhas de código
#Exercise:
def space_concat (str1,str2):
return str1+ " "+str2
print("Código não executado")
full_name = space_concat("Richard","Wagner")
print(full_name)
1. def space_concat (str1,str2)::
- This line defines a function named space_concat.
- It takes two arguments: str1 and str2. These are placeholders for any two strings you'll pass to the function.
2. return str1+ " "+str2:
- Inside the function, this line concatenates (joins) the three parts:
- str1 (the first string passed)
- " " (a space character)
- str2 (the second string passed)
- The return statement sends the resulting combined string back to wherever the function was called.
3. print("Código não executado"):
- This line simply prints the literal string "Código não executado" to the console. It seems to be a placeholder or a remnant from testing, as it doesn't directly relate to the function's logic.
4. full_name = space_concat("Richard","Wagner"):
- This line calls the space_concat function.
- It passes "Richard" as str1 and "Wagner" as str2.
- The value returned by space_concat (which will be "Richard Wagner") is then stored in the variable full_name.
5. print(full_name):
- This line prints the value stored in the full_name variable, which is "Richard Wagner".
In essence, space_concat is a simple function that takes two strings and returns them joined together with a space in between.
#Exercise:
def invert_pair(pair_str):
meio = int(len(pair_str)/2)
str1 = pair_str[:meio]
str2 = pair_str[meio:]
return str2+str1
print(invert_pair("Ousareis passar muito para além da Taprobana"))
1. def invert_pair(pair_str)::
- This line defines a function named invert_pair.
- It takes one argument: pair_str, which is expected to be a single string.
2. meio = int(len(pair_str)/2):
- len(pair_str): Calculates the length of the pair_str (the number of characters).
- /2: Divides the length by 2.
- int(...): Converts the result to an integer. This effectively finds the middle point of the string. If the string has an odd number of characters, int() will truncate the decimal part (e.g., 11 / 2 = 5.5, int(5.5) becomes 5).
3. str1 = pair_str[:meio]:
- This line uses string slicing.
- pair_str[:meio] creates a new string str1 that contains characters from the beginning of pair_str up to (but not including) the index meio. This is the first half of the string.
4. str2 = pair_str[meio:]:
- This line also uses string slicing.
- pair_str[meio:] creates a new string str2 that contains characters from the index meio to the end of pair_str. This is the second half of the string.
5. return str2+str1:
- The function returns the two halves concatenated, but with str2 (the second half) coming before str1 (the first half).
6. print(invert_pair("Ousareis passar muito para além da Taprobana")):
- This line calls the invert_pair function with the Portuguese phrase "Ousareis passar muito para além da Taprobana".
- Let's trace it:
- Length of the string is 44.
- meio will be int(44 / 2), which is 22.
- str1 will be the first 22 characters: "Ousareis passar muito "
- str2 will be the remaining 22 characters: "para além da Taprobana"
- The function returns str2 + str1, which will be: "para além da TaprobanaOusareis passar muito "
#exercício Escreva uma função que, dada uma string que corresponde a uma frase, devolva a última palavra dessa frase, sem espaços, mas com sinais de pontuação. Por exemplo, a seguinte interação deve devolver "esta.":
def last_word(str1):
index = len(str1)-1 # menos um porque é o ponto final
while index>0:
if str1[index]==" ": # para parar quando terminar a última palavra
break
index -= 1
return str1[index+1:] #vai devolver os últimos caracteres e o ponto final que retiramos no iníco
print(last_word("Esta é uma frase que termina em esta."))
1. Function Definition:
This line defines a function named last_word that takes one argument, str1, which is expected to be a string (the phrase or sentence).
2. Initializing the Index:
- len(str1): Calculates the total number of characters in the input string str1.
- -1: Subtracts 1 because string indexing in Python is zero-based. So, len(str1) - 1 gives you the index of the last character in the string.
- The comment # menos um porque é o ponto final (less one because it's the period) suggests the assumption that the string will end with punctuation, and the initial index is set to point to that last character.
3. Iterating Backwards to Find the Start of the Last Word:
This is the core logic for finding the last word:
- while index > 0:: This loop starts from the index (the last character of the string) and continues as long as index is greater than 0. This ensures we don't go out of bounds at the beginning of the string.
- if str1[index] == " ":: Inside the loop, it checks if the character at the current index position is a space.
- If it is a space, it means we've found the space before the last word. The break statement then exits the while loop.
- index -= 1: If the character is not a space, the index is decremented by 1, moving the search one character to the left (backwards) in the string.
What this loop does: It effectively scans the string from right to left until it hits the first space character.
4. Returning the Last Word:
- index+1: After the while loop finishes, index will be pointing to the space before the last word. By adding 1, we get the index of the first character of the last word.
- str1[index+1:]: This is a string slice. It creates a new string that includes all characters from the position index+1 to the end of the original str1.
- The comment #vai devolver os últimos caracteres e o ponto final que retiramos no iníco (it will return the last characters and the period that we removed at the beginning) clarifies that the slice [index+1:] captures the entire last word along with any punctuation that follows it. The "removed at the beginning" part of the comment likely refers to the fact that the initial index was set to the very last character (including punctuation), and the slice ensures that punctuation is included in the output.
5. Calling the Function and Printing the Result:
This line calls the last_word function with the string "Esta é uma frase que termina em esta.".
Let's trace its execution:
- str1 = "Esta é uma frase que termina em esta."
- len(str1) is 38.
- index starts at 38 - 1 = 37 (pointing to the . character).
- The while loop starts from index 37, moving left:
- str1[37] is . (not a space) -> index becomes 36.
- str1[36] is a (not a space) -> index becomes 35.
- ...
- str1[33] is e (not a space) -> index becomes 32.
- str1[32] is (a space) -> The break statement is executed, and the loop stops.
- At this point, index is 32.
- The return statement calculates str1[32 + 1:], which is str1[33:].
- str1[33:] represents the slice from index 33 to the end of the string, which is "esta.".
- The function returns "esta.", and this value is then printed to the console.
#- Escreva uma função que, dado um dicionário, devolve o valor que tem a chave com o maior número de caracteres. Por exemplo, a seguinte interação deve devolver rachmaninoff
def largest_key(dictionary):
largest_k = ""
for key, value in dictionary.items():
if len(key)>len(largest_k):
largest_k=key
return dictionary[largest_k]
conjunto = {"Martim":"dostoievski@fcsh.unl.pt", "Madalena":"kafka@fcsh.unl.pt", "Filipa":"equeiros@fcsh.unl.pt", "Diogo":"ortigao@fcsh.unl.pt"}
print(largest_key(conjunto))
1. Function Definition:
This line defines a function named largest_key. It takes one argument, dictionary, which is expected to be a Python dictionary.
2. Initializing largest_k:
Inside the function, a variable largest_k is initialized as an empty string. This variable will be used to store the key that currently has the greatest length found so far during the iteration. It starts as an empty string because an empty string has a length of 0, ensuring that the first key encountered will always be considered "larger" (longer) initially.
3. Iterating Through the Dictionary:
This loop iterates through each key-value pair in the input dictionary.
- In each iteration, key will hold the current key (e.g., "Martim", "Madalena") and value will hold its corresponding value (e.g., "dostoievski@fcsh.unl.pt").
4. Comparing Key Lengths:
- len(key): This calculates the length (number of characters) of the current key.
- len(largest_k): This calculates the length of the key currently stored in largest_k (the longest key found so far).
- if len(key) > len(largest_k):: This condition checks if the length of the current key is greater than the length of the largest_k.
- largest_k = key: If the current key is indeed longer, then largest_k is updated to store this new, longer key.
5. Returning the Value Associated with the Longest Key:
After the loop has finished iterating through all key-value pairs in the dictionary, largest_k will hold the key that has the maximum string length.
- dictionary[largest_k]: This uses the identified largest_k to access and retrieve its corresponding value from the original dictionary.
- The return statement sends this value back as the result of the function call.
6. Example Usage:
- conjunto = {...}: This line creates a sample dictionary named conjunto.
- print(largest_key(conjunto)): This line calls the largest_key function, passing conjunto as the argument. The function will execute, find the key with the longest length ("Madalena" has 8 chars, "Martim" 6, "Filipa" 6, "Diogo" 5), and return the value associated with that key.
- The result, which is "kafka@fcsh.unl.pt", is then printed to the console.
Exercise:
import requests
def cidades(nomes_cidades):
url = "https://api.geonames.org/searchJSON?q=Amadora&maxRows=1&username=fspring"
url_alterada = url.replace("Amadora",nomes_cidades)
resposta = requests.get(url_alterada)
if resposta.status_code == 200:
print(resposta.json())
else:
print(f"Erro " + str(resposta.status_code))
print(cidades("Setúbal"))
1. Importing the requests Library
This line imports the requests library, which is essential for making HTTP requests (like sending a request to a web API) from your Python script.
2. Defining the cidades Function
This defines a function named cidades (Portuguese for "cities"). It takes one argument: nomes_cidades, which is expected to be a string representing the name of a city you want to search for.
3. Constructing the API URL
- url = "https://api.geonames.org/searchJSON?q=Amadora&maxRows=1&username=fspring": This line initializes a base URL for the Geonames API.
- https://api.geonames.org/searchJSON: This is the endpoint for searching for geographical names and getting results in JSON format.
- q=Amadora: This is the query parameter for the city name, pre-set to "Amadora".
- maxRows=1: This limits the number of results to just one.
- username=fspring: This is a required parameter for the Geonames API, indicating the username for authentication. Note: For real-world applications, you should use your own Geonames username.
- url_alterada = url.replace("Amadora",nomes_cidades): This line dynamically modifies the url. It takes the base url string and replaces the default city "Amadora" with the city name provided to the function via the nomes_cidades argument. This creates the specific API request URL for the desired city.
4. Making the API Request
Here, requests.get() sends an HTTP GET request to the url_alterada. The API's response (which contains the city data or an error) is stored in the resposta variable.
5. Handling the API Response
This block checks the status_code of the API response:
- if resposta.status_code == 200:: A status code of 200 means the request was successful.
- print(resposta.json()): If successful, resposta.json() parses the JSON content of the response into a Python dictionary or list (depending on the JSON structure) and then prints it to the console. This is where you'd see the detailed information about the city.
- else:: If the status_code is anything other than 200 (e.g., 404 for Not Found, 401 for Unauthorized, 500 for Server Error), it indicates an issue.
- print(f"Erro " + str(resposta.status_code)): An error message is printed along with the specific status code to help diagnose the problem.
6. Calling the Function
This line calls the cidades function, passing "Setúbal" as the nomes_cidades argument. The function will then execute, make the API call for Setúbal, print the JSON response (or an error), and then print() will print the return value of the cidades function.
Important Note: The cidades function currently prints the JSON data inside the function but doesn't explicitly return any value. By default, Python functions that don't have a return statement implicitly return None. Therefore, print(cidades("Setúbal")) will first print the API response (from the print(resposta.json()) line) and then print None because the function itself returns None. If you only want the JSON output, you'd typically just call cidades("Setúbal") without wrapping it in another print().
# Faça uma segunda função que, a partir do JSON produzido pela execução da função anterior, escreve para o ecrã a latitude, a longitude e a população da cidade escolhida (toda a informação deverá ser numérica).
def process_json(city_json):
lat = float(city_json['geonames'][0]['lat']) # usamos o float para converter o numero inteiro em um numero com virgulas
lng = float(city_json['geonames'][0]['lng'])
population = city_json['geonames'][0]['population']
info = [lat, lng, population]
print(info)
return info
#Utilizando o que aprendeu nas sessões anteriores e os recursos disponíveis online, faça uma programa em Python que recorra à API da Wikipedia para obter um texto de apresentação (em português) sobre a cidade escolhida. O resultado final do programa deverá ser um texto de apresentação da localidade que inclua, pelo menos, os elementos recolhidos: latitude, longitude, população e texto de apresentação da Wikipedia.
def get_presentation (city):
url = "https://pt.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&titles=" + city + "&formatversion=2&exintro=1&explaintext=1"
response = requests.get(url)
if response.status_code == 200:
return response.json()["query"]["pages"][0]["extract"]
else:
print("Não foi possível completar a operação")
print (get_presentation("Lisboa"))