<Python> Data Types & Exceptions

JunePyo Suh·2020년 4월 24일
0

f-Strings & String concatenation

>>> f"{2 * 37}"
'74'

arbitrary expressions are possible in f-Strings.

>>> def to_lowercase(input):
...    return input.lower()

>>> name = "Eric Idle"
>>> f"{to_lowercase(name)} is funny."
'eric idle is funny.'

Functions can also be called in f-Strings.

class Comedian:
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    def __str__(self):
        return f"{self.first_name} {self.last_name} is {self.age}."

Useful in printing classes.

Data Types

List

Various list methods:

list.append()
list.insert(index, element)
del list_name[index]

#list slicing
list_name[start : stop]
list_name[start : stop : step]

Various list manipulations:

Removing elements from list
Using list comprehension, a new list containing only the elements the user does not want to remove can be created:

somelist = [x for x in somelist if not determine(x)]

Or, by assigning to the slice somelist[:], the existing list can be mutated to contain only the items the user wants:

somelist[:] = [x for x in somelist if not determine(x)]

itertools can also be used:

from itertools import filterfalse 
somelist[:] = filterfalse(determine, somelist)

Or, iterate backwards:

def remove_odd_numbers(numbers):
  for i in range(len(numbers)-1, -1, -1):
    if numbers[i] % 2 == 1:
      del numbers[i]
  return numbers

Removing Odd Numnbers from a List

my_list     = [int(s) for s in input().split()]
odd_numbers = [ ]

for element in my_list:
   if (element % 2) == 1:
       odd_numbers.append(element)
 
for odd_number in odd_numbers:
   my_list.remove(odd_number)
 
print(my_list)

Tuple

  • Tuple elements are declared within () instead of [], and it is not mutable.
  • Operations on tuples are the same as the ones on lists.
  • Using tuple may be more efficient in regards to space-time usage. As much as lists are made to be mutated and more versatile, they take up more space and time in memory. (Useful in representing a list of tuple coordinates)

To change a list into a tuple, use:

my_tuple = tuple(my_list):

Set

  • No ordering, no indexing --> For loop retrieves elements in a random sequence
  • No duplicates allowed; if a duplicate, the new one will replace the old one
set1 = {1, 2, 3}
set2 = set([1, 2, 3])

my_set.remove(3)
if 1 in my_set:
    print("1 is in the set")

Intersection & Union

set1 = {1, 2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8, 9}

print(set1 & set2)
> {4, 5, 6}
print(set1.intersection(set2))
> {4, 5, 6}

print(set1 | set2)
> {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(set1.union(set2))
> {1, 2, 3, 4, 5, 6, 7, 8, 9}

Dictionary

dictionary_name[new_key] = new_value
del my_dict["one"]

Looping Dictionary with Values Instead of Keys

my_dict = { "name" : "Andy", "birth year" : 1991, "birth month" : "August" }

for each_value in my_dict.values():
	print(f"{each_value} is Andy's personal information")

Looping Dictionary with Both Keys and Values

for each_key, each value in my_dict.items():
	print(f"{each_key} is {each_value}")

Complex Dictionary
(1) list of dictionaries

for member in my_dict:
	if member["name"] == "JH":
		print(member["birthday"])

(2) Nested Dictionary

print(my_dict["JH"]["birthday"])

Deleting odd numbers from a list:

Exceptions

When exception occurs, following codes won't run, and the program will shut down. Exception handling is required for the program to continue running.

try:
     line1
     line2
     ...
     lineN    
except Exception:
     exception handling
finally:
     this part of code will run regardless of Exception occurrence

Various cases of Exception Handling

except Exception:

Catches all exceptions

except Exception as e:
        print(f"IndexError가 아닌 다른 종류의 Exception이 발생했습니다 ==> {e}")
        elem = -1

Receiving specific information about Exception type by saving its instance.

except Exception as e:
        print(f"IndexError가 아닌 다른 종류의 Exception이 발생했습니다 ==> {e}")
        elem = -1
    else:
        print(f"Exception이 발생하지 않았습니다!") 

Codes in "else" statement are run if no exception occurred.

0개의 댓글