eri3l
2/6/2020 - 3:37 AM

code-snippets01

#--- List comprehension

temps = [221, 234,240,-9999,230]
new_temps = [] 
for temp in temps:
   new_temps.append(temp / 10)
   
print(new_temps)

# alternatively
# lists with if 
new_temps2 = [temp/10 for temp in temps]

print(new_temps2)

new_temps3 =  [temp/10 for temp in temps if temp != -9999]
print(new_temps3)

# list comprehension with if-else conditions
# (e.g. if temp is -9999, replace it with 0)
new_temps4 = [temp/10 if temp != -9999 else 0 for temp in temps]

#--- take a par list with nums and strings, return only numbers
# isinstance
# check if number
def foo(lst):
    return [i for i in lst if not isinstance(i, str)]
    
# replace str values with 0
lst = [99, 'no data', 95,94, 'no data']

def bar(lst):
    return[i if not isinstance(i, str) else 0 for i in lst]
    
print(bar(lst))


# TODO Consider all above could be replaced just by: 
# 1. basic list comprehension
[i*2 for i in [1, 5, 10]]
Output: [2, 10, 20]
# 2. List comprehension with if condition:
[i*2 for i in [1, -2, 10] if i>0]
Output: [2, 20]
# 3. List comprehension with an if and else condition:
[i*2 if i>0 else 0 for i in [1, -2, 10]]
Output: [2, 0, 20]
#--- Formatting text. 
# simple take input and format it

def sentence_maker(phrase):
    interogatives = ("how","what","why")
    capitalised = phrase.capitalize()
    
    if phrase.startswith(interogatives):
        return "{}?".format(capitalised)
    else:
        return "{}.".format(capitalised)
        
print(sentence_maker("how are you"))


results = []
while True:
    user_input = input("Say something: ")
    if user_input == "/end":
        break
    else:
        results.append(sentence_maker(user_input))
        
print(" ".join(results))