''' switch_case101.py
a switch/case like statement to replace
multiple if/elif/else statements
'''

# make input() work with Python2 and 3
try:
    input = raw_input
except NameError:
    pass

def switch_case(case):
    return "You entered " + {
    '1': "one",                  # if
    '2': "two",                  # elif
    '3': "three",                # elif
    '4': "four"                  # elif
    }.get(case, "a bad number")  # else

num = input("Input a number between 1 and 4: ")
print(switch_case(num))
# more or less accidentally putting a comma at the end like shown
# turns the integer value into a one element tuple
x = 123,
print(x)  # (123,)

# now this would give a
# TypeError: can only concatenate tuple (not "int") to tuple
print(x + 3)

Shows how to use a class for a record like structure ...

''' class_Persons101.py
create a list of instances of class Persons
from a space separated data file
'''

class Persons:
    # similar to a record
    def __init__(self, ni_number, name, age):
        # prefix dunder __ makes variable private
        self.__ni_number = ni_number
        self.__name = name
        self.__age = age

    def show(self):
        '''for a quick test'''
        # formating string
        sf = " ni_number = {}\n name = {}\n age = {}\n"
        return sf.format(self.__ni_number, self.__name, self.__age)


# format: ni_number firstname lastname age
data_str = '''\
55512 Bart Simpson 45
45622 John Smith 58
45813 Sven Soetebier 41
46231 Alicia Sands 27
'''

fname = "data123.txt"

# write test data file
with open(fname, "w") as fout:
    fout.write(data_str)

# read the data file back in and process
with open(fname, "r") as fin:
    person_list = []
    for line in fin:
        mylist = line.split()
        print(mylist)  # test
        # unpack the list
        ni_number, first, last, age = mylist
        name = first + ' ' + last
        # create a list of instances of class Persons
        person_list.append(Persons(ni_number, name, age))

print('-'*20)
# test one of the instances
inst1 = person_list[0]
print(inst1.show())


''' result ...
['55512', 'Bart', 'Simpson', '45']
['45622', 'John', 'Smith', '58']
['45813', 'Sven', 'Soetebier', '41']
['46231', 'Alicia', 'Sands', '27']
--------------------
 ni_number = 55512
 name = Bart Simpson
 age = 45
'''

Use this function to make sure that an integer value is entered ...

''' get_int23.py
an input function for integer values
'''

try:
    # allows the use of input() for Python2 and Python3
    input = raw_input
except NameError:
    pass


def get_int(prompt="Enter an integer: "):
    """
    this function will loop until a valid integer value is entered
    returns an integer number
    """
    while True:
        try:
            # successful return breaks out of the endless while loop
            return int(input("Enter an integer: "))
        except ValueError:
            print("Try again, value entered was not an integer value.")

# test
n = get_int()
print(n)

Take a look at advanced unpacking made possible in Python3 ...

# advanced unpacking (needs Python3) ...
a, b, *rest = range(10)
print(a)     # 0
print(b)     # 1
print(rest)  # [2, 3, 4, 5, 6, 7, 8, 9]

a, *rest, b = range(10)
print(a)     # 0
print(b)     # 9
print(rest)  # [1, 2, 3, 4, 5, 6, 7, 8]

*rest, b = range(10)
print(b)     # 9
print(rest)  # [0, 1, 2, 3, 4, 5, 6, 7, 8] 

mylist = list(range(10))
size = len(mylist)//3
rest = mylist
newlist = []
for k in range(size):
    a, b, c , *rest = rest
    newlist.append([a, b, c])

print(newlist)  # [[0, 1, 2], [3, 4, 5], [6, 7, 8]]   

Python3 offers function annotations to make code easier to understand ...

# function annotations (needs Python3) ...
# makes code easier to comprehend
# Python doesn't do anything with the annotations other than
# put them in an __annotations__ dictionary

def funk(x: int) -> float:
    return x*x/2

print(funk.__annotations__)

''' result ...
{'x': <class 'int'>, 'return': <class 'float'>}
'''

For the fun of it ...

    ''' RomanNumeral1.py
    a decimal (denary number) to roman numeral function
    '''

    def int2roman(number):
        '''convert denary number to roman numerals'''
        numerals = {
        1: "I", 4: "IV", 5: "V", 9: "IX", 10: "X", 40: "XL", 50: "L",
        90: "XC", 100: "C", 400: "CD", 500: "D", 900: "CM", 1000: "M"
        }
        result=""
        for value, numeral in sorted(numerals.items(), reverse=True):
            while number >= value:
                result += numeral
                number -= value
        return result

    # test ...
    num = 123
    print("%3d --> %s" % (num, int2roman(num)))
    num = 54
    print("%3d --> %s" % (num, int2roman(num)))

    ''' result ...
    123 --> CXXIII
     54 --> LIV
    '''

Want to get some order into your life?

''' priority_queue1.py
uses a priority index for items in the queue

'''

import queue

pq = queue.PriorityQueue()

mypriorities = [
(3, "Take a bath"),
(4, "Feed the dog"),
(5, "Mow the lawn"),
(1, "Jane's birthday"),
(2, "Do tax filings")]

for item in mypriorities:
  pq.put(item)


while not pq.empty():
  print(pq.get_nowait())

''' result ...
(1, "Jane's birthday")
(2, 'Do tax filings')
(3, 'Take a bath')
(4, 'Feed the dog')
(5, 'Mow the lawn')
'''
''' zero_topower_zero.py
by convention 0 to the power of 0 is one
test if Python conforms
'''

print(0**0)  # 1 (is correct by convention)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.