Python Programming (May 2022)

Python Programming (May 2022)

Scratchpad #3

# # Currency Convert

# # print("Amount of USD you want to convert")
# usd = input("Amount of USD you want to convert: ")

# inr = float(usd) * 75.43
# inr = round(inr, 2)

# print(f"USD {usd} is equal to Rs. {inr}")


# # -----------------

# city = input("Enter your city: ")
# # city = city.lower()

# if city == "bejing":
#     print("You are not welcome")
# elif city == "mumbai":
#     print("You are always welcome")
# elif city == "delhi":
#     print("Nahi aana hai!")
# else:
#     print("You are also welcome")

# ---------------------------------------

# city = "askdmkdsa"

# if city:
#     print(f"{city} is a great place")
# else:
#     print("Please enter something")


# loggedInUser = ""


# if loggedInUser:
#     print("Welcome")
# else:
#     print("Please log in")


# -------------------

# age = int(input("Please enter your age: "))

# if age >= 65:
#     print("Drink are free!")
# elif age >= 21:
#     print("You are allowed to enter and drink")
# elif age >= 18:
#     print("You can enter, but you cannot drink")
# else:
#     print("Entry denied!")

# if age >= 18 and age < 21:
#     print("You can enter, but you cannot drink")
# elif age >= 21 and age < 65:
#     print("You are allowed to enter and drink")
# elif age >= 65:
#     print("Drink are free!")
# else:
#     print("Entry denied!")


isLoggedIn = False
user_role = "moderator"

if isLoggedIn:
    if user_role == "admin":
        print("You have access to everything")
    else:
        print("You can access fewer things")
else:
    print("Please log in first")

Scratchpad #4

# for char in "hello":
#     print(char)


# for num in range(0, 1000):
#     print(num)
#     print(f"{num}: Hello World")


# for num in range(1, 11):
#     print(num)


# print("Goodbye World")


# for char in "Hello World":
#     print(char)


# for num in range(14, 0):
#     print(num)


# for num in range(0, 10, 3):
#     print(num)


# for num in range(11, 0, -2):
#     print(num)

# for num in range(0, 10, 2):
#     print(num)


# for num in range(1, 21):
#     if num == 5 or num == 16:
#         print(f"{num} - FizzBuzz")
#     elif num % 2 == 0:
#         print(f"{num} - Fizz is even")
#     elif num % 2 != 0:
#         print(f"{num} - Fizz is odd")


# password = input("Please enter your password: ")

# while password != "helloworld":
#     print("ACCESS DENIED!")
#     password = input("Please enter your password again: ")

# while password == "helloworld":
#     if password == "helloworld":
#         print("Welcome")
#     elif password != "helloworld":
#         print("Access Denined")

# print("Welcome")


# while password != "helloworld":
#     print("ACCESS DENIED!")
#     password = input("Please enter your password again: ")

# for num in range(0, 10):
#     print(num)


# count = 0
# while count < 11:
#     print(count)
#     count += 1

# count = 3
# password = input("Please enter your password: ")

# while True:
#     if count < 1:
#         print("All your chances are over! Bhag ja!")
#         break

#     if password == "helloworld":
#         break

#     print("ACCESS DENIED")
#     print(f"{count} chances remaining")
#     password = input("Please enter your password again: ")
#     count -= 1

# -----------------------------

player1 = input("Enter player1's choice: ")
player2 = input("Enter player2's choice: ")

if (
    (player1 == "rock" and player2 == "scissors")
    or (player1 == "paper" and player2 == "rock")
    or (player1 == "scissors" and player2 == "paper")
):
    print("Player 1 wins")
elif (
    (player2 == "rock" and player1 == "scissors")
    or (player2 == "paper" and player1 == "rock")
    or (player2 == "scissors" and player1 == "paper")
):
    print("Player 2 wins")
elif player1 == player2:
    print("It's a tie")
else:
    print("Something went wrong")

Scratchpad #5

# todo = []

# while True:
#     task = input("Add task to list. (q to quit) ")

#     if task == "":
#         print("Please enter a valid task")
#     elif task == "q":
#         break
#     else:
#         todo.append(task)

# print(f"You have {len(todo)} tasks in your list.")
# print("Your TODOs are as follows: ")

# for task in todo:
#     print("- " + task)

# # print(todo)


numbers = [1, 2, 3, 4]

count = 0
while count < len(numbers):
    print(numbers[count])
    count += 1


for num in numbers:
    print(num)


# rahul@rstforum.co.in

Scratchpad #6

# numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

# # numbers
# # None
# # print("Hello World")

# # print(10000)


# numbers[1][1] + 10


# numbers = [1, 2, 3, 4, 5, 6]

# # numbers2 = []

# # for num in numbers:
# #     numbers2.append(num / 2)

# # numbers3 = [num / 3 for num in numbers]

# # print(numbers2)
# # print(numbers3)


# numbers = [1, 2, 3, 4.5, 5.3, 6]

# n2 = [n * 2 for n in numbers]

# print(n2)


nested_list = [
    [[1, 2, 3], [1, 2, 3], [1, 2, 3]],
    [[1, 2, 3], [1, 2, 3], [1, 2, 3]],
    [[1, 2, 3], [1, 2, 3], [1, 2, 3]],
]

# for lst in nested_list:
#     for num in lst:
#         print(num)

Scratchpad #7

product = ["iPhone 13", "Apple", "Some description...", 100000, 500, True]

# products = [
#     ["iPhone 13", "Apple", "Some description...", 100000, 500, True],
#     ["iPhone 13", "Apple", "Some description...", 100000, 500, True],
#     ["iPhone 13", "Apple", "Some description...", 500, 100000, True],
# ]

# product[0]
# product[1]


# product = {
#     2: "Apple",
#     5: 100000,
#     4: 500,
#     1: "Some description...",
#     3: "iPhone 13",
#     0: "Hello",
# }

# product2 = ["Hello", "Some description...", "Apple", "iPhone 13", 500, 100000]

# print(product2[0])
# print(product[0])

# product[3]

# print(product["name"])
# print(product[0])
# print(product2[0])


# profile1 = {
#     "name": "John Doe",
#     "age": 20,
# }

# profile2 = dict(name="John Doe", age=20)

# print(profile1)
# print(profile2)


# book = {
#     "name": "The theory of everything",
#     "author": "Stephen Hawking",
#     "pages": 140,
#     "language": "English",
#     "in_stock": True,
#     73: 1001001,
# }

# print(book["author"])

# print(book["author"])
# print(book["description"])


# for key in book:
#     print(book[key])

# for value in book.values():
#     print(value)


# for item in book.items():
#     print(item[0])
#     print(item[1])


# for key, value in book.items():
#     print(key, value)


song = {
    "name": "Parabola",
    "artist": "Tool",
    "album": "Lateralus",
    "released": 2001,
    "genres": ["Progressive/Art Rock", "Progressive metal"],
}


# >>> song = {
# ...     "name": "Parabola",
# ...     "artist": "Tool",
# ...     "album": "Lateralus",
# ...     "released": 2001,
# ...     "genres": ["Progressive/Art Rock", "Progressive metal"],
# ... }
# >>>
# >>> song
# {'name': 'Parabola', 'artist': 'Tool', 'album': 'Lateralus', 'released': 2001, 'genres': ['Progressive/Art Rock', 'Progressive metal']}
# >>>
# >>>
# >>> "Tool" in song
# False
# >>>
# >>> "Tool" in song.keys()
# False
# >>>
# >>> "Tool" in song.keys()
# False
# >>>
# >>> "Tool" in song.values()
# True
# >>>
# >>> "artist" in song.keys()
# True
# >>>
# >>> "artist" in song
# True
# >>>
# >>> song
# {'name': 'Parabola', 'artist': 'Tool', 'album': 'Lateralus', 'released': 2001, 'genres': ['Progressive/Art Rock', 'Progressive metal']}
# >>>
# >>>
# >>>
# >>> x = {"a": "1", "b": "2", "c": "3"}
# >>>
# >>>
# >>> x
# {'a': '1', 'b': '2', 'c': '3'}
# >>>
# >>>
# >>> x.clear()
# >>>
# >>> x
# {}
# >>>
# >>>
# >>> x = {"a": "1", "b": "2", "c": "3"}
# >>>
# >>>
# >>> y = x
# >>>
# >>> y
# {'a': '1', 'b': '2', 'c': '3'}
# >>> x
# {'a': '1', 'b': '2', 'c': '3'}
# >>> x.clear()
# >>>
# >>> y
# {}
# >>> x = {"a": "1", "b": "2", "c": "3"}
# >>>
# >>>
# >>> y = x.copy()
# >>> y
# {'a': '1', 'b': '2', 'c': '3'}
# >>> x
# {'a': '1', 'b': '2', 'c': '3'}
# >>> x.clear()
# >>> x
# {}
# >>> y
# {'a': '1', 'b': '2', 'c': '3'}
# >>> x
# {}
# >>>
# >>> x = {"a": "1", "b": "2", "c": "3"}
# >>>
# >>>
# >>> x
# {'a': '1', 'b': '2', 'c': '3'}
# >>>
# >>> y = x
# >>>
# >>> y
# {'a': '1', 'b': '2', 'c': '3'}
# >>> x
# {'a': '1', 'b': '2', 'c': '3'}
# >>>
# >>> x is y
# True
# >>> y = x.copy()
# >>>
# >>> y
# {'a': '1', 'b': '2', 'c': '3'}
# >>> x
# {'a': '1', 'b': '2', 'c': '3'}
# >>> y is x
# False
# >>> x is y
# False
# >>> x == y
# True
# >>> y = x
# >>> x == y
# True
# >>> x is y
# True
# >>> x
# {'a': '1', 'b': '2', 'c': '3'}
# >>> y
# {'a': '1', 'b': '2', 'c': '3'}
# >>>
# >>>
# >>>
# >>>
# >>>
# >>>
# >>> {}.fromkeys("hello", True)
# {'h': True, 'e': True, 'l': True, 'o': True}
# >>>
# >>>
# >>> {}.fromkeys(["name", "age", "address", "phone"], None)
# {'name': None, 'age': None, 'address': None, 'phone': None}
# >>>
# >>>
# >>> {}.fromkeys(True, None)
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: 'bool' object is not iterable
# >>>
# >>>
# >>> {}.fromkeys(["name", "age"], None)
# {'name': None, 'age': None}
# >>>
# >>> {}.fromkeys("abcd", None)
# {'a': None, 'b': None, 'c': None, 'd': None}
# >>>
# >>> {}.fromkeys(100, None)
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: 'int' object is not iterable
# >>>
# >>>
# >>>
# >>>
# >>>
# >>> {}
# {}
# >>>
# >>> type({})
# <class 'dict'>
# >>>
# >>> {"name": "John Doe"}
# {'name': 'John Doe'}
# >>>
# >>>
# >>> song = {
# ...   "name": "Sober",
# ...   "artist": "Tool",
# ...   "album": "Undertow",
# ... }
# >>>
# >>>
# >>>
# >>> song
# {'name': 'Sober', 'artist': 'Tool', 'album': 'Undertow'}
# >>>
# >>>
# >>> song["name"]
# 'Sober'
# >>>
# >>> song["artist"]
# 'Tool'
# >>>
# >>> song["length"]
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# KeyError: 'length'
# >>>
# >>>
# >>> song
# {'name': 'Sober', 'artist': 'Tool', 'album': 'Undertow'}
# >>>
# >>> song.get("name")
# 'Sober'
# >>> song.get("artist")
# 'Tool'
# >>> song.get("length")
# >>>
# >>> result = song.get("length")
# >>>
# >>> result
# >>> print(result)
# None
# >>>
# >>> song
# {'name': 'Sober', 'artist': 'Tool', 'album': 'Undertow'}
# >>>
# >>> song["name"]
# 'Sober'
# >>>
# >>> song.get("name")
# 'Sober'
# >>> song["hello"]
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# KeyError: 'hello'
# >>> song.get("hello")
# >>>
# >>>
# >>> song = {
# ...   "name": "Vicarious",
# ...   "album": "10,000 Days"
# ... }
# >>>
# >>>
# >>> song.pop()
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: pop expected at least 1 argument, got 0
# >>>
# >>> song.pop("name")
# 'Vicarious'
# >>>
# >>> song
# {'album': '10,000 Days'}
# >>>
# >>>
# >>> song = {
# ...   "name": "Vicarious",
# ...   "album": "10,000 Days"
# ... }
# >>>
# >>> song
# {'name': 'Vicarious', 'album': '10,000 Days'}
# >>>
# >>>
# >>> song.pop("hello")
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# KeyError: 'hello'
# >>>
# >>> song.pop("name")
# 'Vicarious'
# >>> song
# {'album': '10,000 Days'}
# >>>
# >>>
# >>> song = {
# ...   "name": "The Pot",
# ...   "artist": "Tool",
# ...   "album": "10,000 Days"
# ... }
# >>>
# >>> song
# {'name': 'The Pot', 'artist': 'Tool', 'album': '10,000 Days'}
# >>>
# >>> song.popItem()
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# AttributeError: 'dict' object has no attribute 'popItem'. Did you mean: 'popitem'?
# >>> song.popItem()
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# AttributeError: 'dict' object has no attribute 'popItem'. Did you mean: 'popitem'?
# >>>
# >>>
# >>> song.popitem()
# ('album', '10,000 Days')
# >>>
# >>>
# >>>
# >>>
# >>>
# >>> song.popitem("artist")
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: dict.popitem() takes no arguments (1 given)
# >>>
# >>> song = {'name': 'The Pot', 'artist': 'Tool', 'album': '10,000 Days'}
# >>>
# >>>
# >>>
# >>> song
# {'name': 'The Pot', 'artist': 'Tool', 'album': '10,000 Days'}
# >>>
# >>>
# >>>
# >>> song2 = {}
# >>>
# >>> song
# {'name': 'The Pot', 'artist': 'Tool', 'album': '10,000 Days'}
# >>> song2
# {}
# >>> song2.update(song)
# >>>
# >>> song2
# {'name': 'The Pot', 'artist': 'Tool', 'album': '10,000 Days'}
# >>>
# >>> song2["name"]
# 'The Pot'
# >>>
# >>> song2["name"] = "Sober"
# >>>
# >>> song2
# {'name': 'Sober', 'artist': 'Tool', 'album': '10,000 Days'}
# >>>
# >>>
# >>>
# >>> song2.update({"length": 2.45})
# >>>
# >>> song2
# {'name': 'Sober', 'artist': 'Tool', 'album': '10,000 Days', 'length': 2.45}
# >>>
# >>> song2["name"] = "Hello"
# >>>
# >>> song2
# {'name': 'Hello', 'artist': 'Tool', 'album': '10,000 Days', 'length': 2.45}
# >>>
# >>> song2.update({"name": "World"})
# >>> song2
# {'name': 'World', 'artist': 'Tool', 'album': '10,000 Days', 'length': 2.45}
# >>>
# >>>
# >>> song2.update({"name": "Sober", "album": "Something"})
# >>>
# >>> song2
# {'name': 'Sober', 'artist': 'Tool', 'album': 'Something', 'length': 2.45}
# >>>
# >>>
# >>>
# >>> song
# {'name': 'The Pot', 'artist': 'Tool', 'album': '10,000 Days'}
# >>>
# >>>
# >>> {key for key in song}
# {'album', 'artist', 'name'}
# >>>
# >>>
# >>> {key:True for key in song}
# {'name': True, 'artist': True, 'album': True}
# >>>
# >>>
# >>>
# >>> {key:value for key,value in song.items()}
# {'name': 'The Pot', 'artist': 'Tool', 'album': '10,000 Days'}
# >>>
# >>>
# >>> song
# {'name': 'The Pot', 'artist': 'Tool', 'album': '10,000 Days'}
# >>>
# >>> {key:value.upper() for key,value in song.items()}
# {'name': 'THE POT', 'artist': 'TOOL', 'album': '10,000 DAYS'}
# >>> {key.upper():value.upper() for key,value in song.items()}
# {'NAME': 'THE POT', 'ARTIST': 'TOOL', 'ALBUM': '10,000 DAYS'}
# >>>
# >>>
# >>>
# >>> {num:True for num in range(10)}
# {0: True, 1: True, 2: True, 3: True, 4: True, 5: True, 6: True, 7: True, 8: True, 9: True}
# >>>
# >>> {num:num for num in range(10)}
# {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
# >>>
# >>> {num:num*2 for num in range(10)}
# {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
# >>> {num:num**2 for num in range(10)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
# >>>

Scratchpad #8

# def hello():
#     print("Hello World")
#     print("Hello World")

# hello()

# def greet():
#     print("TEST")
#     return "Hello John"

# message = greet()
# print(greet())
# print(greet())

# print(message)

import random

# def flip_coin():
#     if random.random() > 0.5:
#         return "HEADS"
#     else:
#         return "TAILS"

# print(flip_coin())
# print(flip_coin())
# print(flip_coin())

# def greet(person):  # parameter
#     return f"Hello, {person}"

# print(greet("James"))  # argument
# print(greet("John"))

# def greet(person, message):  # parameter
#     return f"{message}, {person}"

# print(greet("James", "Hello"))

# def add(a, b):
#     return a + b

# print(add(10, 5.4))

# def sum_odd_nums(nums):
#     total = 0
#     for num in nums:
#         if num % 2 == 1:
#             total += num
#     return total

# print(sum_odd_nums([1, 2, 3, 4, 5]))

# def is_odd_num(num):
#     if num % 2 == 0:
#         return False
#     return True

# print(is_odd_num(2))

# def greet(message, name="John"):
#     return f"{message.upper()}, {name}"

# print(greet("John Doe", "hi"))
# print(greet("James"))

# def add(a, b):
#     return a + b

# def sub(a, b):
#     return a - b

# def math(a, b, fn=add):
#     return fn(a, b)

# print(math(10, 50))

# def full_name(first_name="A", last_name="B"):
#     return f"{first_name} {last_name}"

# print(full_name("john", "doe"))
# print(full_name(last_name="doe", first_name="john"))
# print(full_name())

# name = "James Smith"

# def greet():
#     name = "John Doe"
#     print(name)

# print(name)
# greet()

# total = 50  # global scope

# def math(a, b):
#     total = 10  # local scope
#     print(a + b + total)

# math(10, 20)

# total = 0

# def static():
#     global total
#     total += 1
#     return total

# def increment(num):
#     num += 1
#     return num

# total = increment(total)

# print(static())  # 0

# print(total)

# def outer():
#     count = 0

#     def inner():
#         nonlocal count
#         count += 1
#         return count

#     return inner()


def greet(message, name):
    """
    This function takes a message and a name.
    It concatenates it and upper-cases it and return the value
    
    ## Example
    greet("Hi", "John")

    @params
    message: str
    name: str
    """
    return f"{message}, {name}".upper()


# print(greet("Hi", "John"))

# print(greet.__doc__)

# print(help(greet))

# import random

Scratchpad #9

# def add(*nums):
#     total = 0
#     for num in nums:
#         total += num
#     return total

# print(add(
#     10,
#     5,
#     10,
#     4,
# ))

# def add(special_num, *nums):
#     print(nums, special_num)

# add(20, 1, 12, 12)

# def profile(**kwargs):
#     print(kwargs)

# profile(name="John Doe", age=20, profession="Programmer")

# def show_info(a, b, *args, role="moderator", **kwargs):
#     return [a, b, args, role, kwargs]

# print(
#     show_info(1,
#               2,
#               3,
#               4,
#               True,
#               role="programmer",
#               first_name="John",
#               last_name="Doe"))

# def add_all_values(*args):
#     total = 0
#     for num in args:
#         total += num
#     print(total)

# # Array / List
# nums = [1, 2, 3, 4, 5, 6, 7, 8]

# add_all_values(*nums)

# def say_name(first, last):
#     print(f"My name is {first} {last}.")

# data = {"first": "John", "last": "Doe"}

# say_name(**data)

# def square(num):
#     return num * num

# cube = lambda num: num * num * num
# print(cube(10))
# something = 10
# something = square

# print(something(2))

# def math(a, b, fn):
#     return fn(a, b)

# print(math(10, 2, lambda a, b: a + b))
# print(math(10, 2, lambda a, b: a - b))

# add = lambda a, b, c: a + b + c

# def add(a, b):
#     return a + b

# def sub(a, b):
#     return a - b

# math(10, 2, sub)

# print(math(10, 10, add))

# nums = [1, 2, 3, 4, 5, 6, 7, 8]

# doubles = map(lambda num: num * 2, nums)
# doubles2 = [num * 2 for num in nums]

# # print(list(doubles))
# # print(doubles2)

# for num in doubles:
#     print(num)

# nums = [1, 2, 3, 4, 5, 6, 7, 8]

# evens = filter(lambda num: num % 2 == 0, nums)

# print(list(evens))

# even_doubles = map(lambda num: num * 2, filter(lambda num: num % 2 == 0, nums))

# print(list(even_doubles))

# data = [
#     {
#         "name": "Product #1",
#         "price": 1000
#     },
#     {
#         "name": "Product #2",
#         "price": 2000
#     },
#     {
#         "name": "Product #3",
#         "price": 4000
#     },
#     {
#         "name": "Product #4",
#         "price": 5000
#     },
#     {
#         "name": "Product #5",
#         "price": 10000
#     },
# ]

# filtered_data = filter(lambda product: product["price"] > 4000, data)

# data_in_rupees = map(
#     lambda product: {
#         "name": product["name"],
#         "price": product["price"] * 75
#     }, filtered_data)

# print(list(data_in_rupees))

# print(all([0, 1, 2, 3]))

# nums = [2, 4, 6, 8]

# all_evens = map(lambda num: num % 2 == 0, nums)

# print(all(nums))

# people = ['John', 'Jack', 'James', 'Jason', 'Aane', 'Jacob']

# print(any(map(lambda name: name[0] == 'A', people)))

numbers = [2, 3, 7, 3, 9, 1]
sorted_numbers = sorted(numbers)

print(sorted_numbers)
print(numbers)

Scratchpad #10

# def func:
#     pass

# hello = "world"

# print(hello)

# len(True)

# 10 + "10"

# lst = [1, 2, 3, 4]

# print(lst[20])

# print(int("hell

# collection = {}

# print(collection["name"])

# def add(a, b):
#     if type(a) != int or type(b) != int:
#         raise TypeError("Please only provide integers")
#     return a + b

# print(add("10", 10))

# def colorize(text, color):
#     colors = ("red", "yellow", "blue", "green")

#     # raise ZeroDivisionError("akjsndkjsa")

#     if type(text) is not str:
#         raise TypeError("text should be a string")
#     if type(color) is not str:
#         raise TypeError("color should be a string")
#     if color not in colors:
#         raise ValueError("invalid color provided")

#     # some logic
#     print(f"Printed {text} in {color}")

# try:
#     colorize("10", "purple")
# except Exception as error:
#     print(error)
# # except (TypeError, ValueError, ZeroDivisionError) as error:
# #     print(error)

# print("AFTER COLORIZE - Hello World")

# def divide(a, b):
#     try:
#         result = a / b
#     except Exception as error:
#         return error
#     else:
#         return result
#     finally:
#         print("I am going to no matter if it succeeds or it fails")

# print(divide(10, "msad"))

# class User:
#     pass

# john = User()  # instance of the class User
# # is a User
# jane = User()

# print(type(john))

# def Person(first_name, last_name, phone):
#     return {"first_name": first_name, "last_name": last_name, "phone": phone}


class User:

    def __init__(self, first_name, last_name, phone, age):
        self.first_name = first_name
        self.last_name = last_name
        self.phone = phone
        self.__age = age  # name mangling

    def greet(self):
        print(self.first_name, self.last_name)

    # def get_age(self):
    #     return self._age


john = User("John", "Doe", "921098321", 25)
jane = User("Jane", "Doe", "324345435", 20)

print(john._User__age)

# john.greet()

# jack = Person("Jack", "Smith", "3243243")

# print(john.first_name, john.last_name)
# print(jane.first_name, jane.last_name)
# # print(jack["first_name"], jack["last_name"])

Scratchpad #11

# # class User:
# #     nationality = "Indian"
# #     total_users = 0
# #     total_active_users = 0

# #     def __init__(self, first_name, last_name, age):
# #         self.first_name = first_name
# #         self.last_name = last_name
# #         self._age = age
# #         self.profession = "programmer"
# #         User.total_users += 1

# #     def __str__(self):
# #         return f"{self.first_name} {self.last_name}\n{self._age}"

# #     def login(self):
# #         print("You have logged in")
# #         User.total_active_users += 1

# #     def logout(self):
# #         print("You have logged out")
# #         User.total_active_users -= 1

# #     def greet(self, message):
# #         print(f"{message} {self.first_name} {self.last_name}")

# #     def get_age(self):
# #         print("Someone is trying to access the age")
# #         return self._age

# #     @classmethod
# #     def get_total_user(cls):
# #         return cls.total_users

# # john = User("john", "doe", 20)
# # jane = User("jane", "smith", 22)

# # print(john)
# # print(jane)

# # # john.login()
# # # john.logout()

# # # print(User.get_total_user())

# # # print(User.total_users)
# # # print(User.total_active_users)

# # # john.nationality = "Nepali"

# # # print(john.nationality)
# # # print(jane.nationality)
# # # print(User.nationality)

# # # john.greet()
# # # print(john.first_name)

# # # print(type(jane))

# # # print(john.get_age())

# # # jane.profession = "developer"

# # # print(jane.profession)
# # # print(john.profession)

# # # jane.greet("hello my name is, ")

# # # class Math:

# # #     @classmethod
# # #     def add(cls, a, b):
# # #         return a + b

# # #     @classmethod
# # #     def sub(cls, a, b):
# # #         return a - b

# # #     @classmethod
# # #     def mul(cls, a, b):
# # #         return a

# # #     @classmethod
# # #     def square(cls, x):
# # #         return x * x

# # # print(Math.square(10))

# # class User:
# #     total_users = 0
# #     total_active_users = 0

# #     def __init__(self, first_name, last_name, age):
# #         self.first_name = first_name
# #         self.last_name = last_name
# #         self._age = age
# #         self.role = "user"
# #         User.total_users += 1

# #     def login(self):
# #         print("You have logged in")
# #         User.total_active_users += 1

# #     def logout(self):
# #         print("You have logged out")
# #         User.total_active_users -= 1

# # class Admin(User):

# #     def login(self):
# #         print("Hello Admin. You have logged in")
# #         User.total_active_users += 1

# #     def create_group(self, name):
# #         print(f"{name} group created")

# # john = User("john", "doe", 20)
# # jane = Admin("jane", "daljit wasan", 20)

# # john.login()
# # jane.login()

# # jane.create_group("python")
# # # john.create_group("python")
# # print(Admin.total_active_users)

# class User:

#     def __init__(self, first_name, last_name, age):
#         self.first_name = first_name
#         self.last_name = last_name
#         self._age = age

#     @property
#     def age(self):
#         return f"{self.first_name} is {self._age} years old"

#     @age.setter
#     def age(self, new_age):
#         self._age = new_age
#         print("The age has been changed")

#     # def get_age(self):
#     #     return self._age

#     # def set_age(self, new_age):
#     #     self._age = new_age
#     #     print("Age has been modified")

# john = User("john", "doe", 20)

# john.age = 25

# print(john.age)

# # print(john.get_age())
# # john.set_age(24)
# # print(john.get_age())

# class User:

#     def __init__(self, first_name, last_name, age):
#         self.first_name = first_name
#         self.last_name = last_name
#         self._age = age

#     @property
#     def age(self):
#         return f"{self.first_name} is {self._age} years old"

#     @age.setter
#     def age(self, new_age):
#         self._age = new_age
#         print("The age has been changed")

# class Admin(User):

#     def __init__(self, first_name, last_name, age, email):
#         super().__init__(first_name, last_name, age)
#         self.email = email

# john = Admin("john", "doe", 20, "john@rstforum.net")

# print(john.email)

# class Human:

#     def __init__(self, name, age):
#         self.name = name
#         self.age = age

#     def speak(self):
#         print(f"Hello, my name is {self.name}")

#     def work(self):
#         print("I am working")

# class Animal:

#     def __init__(self, name, age):
#         self.name = name
#         self.age = age

#     def speak(self):
#         print(f"#### #### ##### ###")

#     def run(self):
#         print("The thing is running")

# class Mutant(Animal, Human):
#     pass

# dj = Mutant("Daljit", 16)

# dj.work()
# dj.run()
# dj.speak()

# class User:

#     def __init__(self, first_name, last_name, age):
#         self.first_name = first_name
#         self.last_name = last_name
#         self._age = age

#     def speak(self):
#         raise NotImplementedError("Subclasses need to implement this method")

#     def __len__(self):
#         return self._age

#     def __add__(self, other):
#         if not isinstance(other, User):
#             raise TypeError("This is sick!")

#         return User("Unnamed", self.last_name, 0)

#     def __repr__(self):
#         return self.first_name

# class Admin(User):

#     def __init__(self, first_name, last_name, age, email):
#         super().__init__(first_name, last_name, age)
#         self.email = email

#     def speak(self):
#         print(
#             f"My name is {self.first_name} {self.last_name} and I am an admin."
#         )

# class Moderator(User):

#     def __init__(self, first_name, last_name, age, email):
#         super().__init__(first_name, last_name, age)
#         self.email = email

#     def speak(self):
#         print(
#             f"My name is {self.first_name} {self.last_name} and I am an moderator."
#         )

# class Animal:
#     pass

# # john = Admin("john", "doe", 20, "john@rstforum.net")
# jane = User("Jane", "Smith", 25)
# john = User("John", "Doe", 25)
# liger = Animal()
# daljit = User("Daljit", "Wasan", 16)

# daljit + liger

# # result = john + jane
# # print(result)

# # print(isinstance(jane, Moderator))

# # jane.speak()
# # john.speak()

# # print(len(jane))

# # a = 10
# # b = 20

# # print(a + b)

# nums = [1, 2, 3, 4, 5]
# name = "john"

# nums_iter = iter(nums)

# print(next(nums_iter))

# for num in nums:
#     print(num)

# for char in name:
#     print(char)


class Counter:

    def __init__(self, start, end, step):
        self.start = start
        self.end = end
        self.step = step

    def __iter__(self):
        return self

    def __next__(self):
        if self.start < self.end:
            num = self.start
            self.start += self.step
            return num
        else:
            raise StopIteration

    def __repr__(self):
        return f"Counter({self.start}, {self.end})"


c = Counter(0, 10, 2)
# print(c)

# for next(num) in iter(c):
#     c = iter(c)
#     print(next(num))

# c_iter = iter(c)

# print(next(c_iter))
# print(next(c_iter))
# print(next(c_iter))

Scratchpad #12

# def my_map(fn, iterable):
#     iterator = iter(iterable)

#     while True:
#         try:
#             fn(next(iterator))
#         except StopIteration:
#             break

# my_map(lambda a: print(a**a), [1, 2, 3, 4, 5, 6, 7])
# print(list(map(lambda a: a**a, [1, 2, 3, 4, 5, 6, 7])))

# def count_up_to_gen(max):
#     count = 1
#     while count <= max:
#         yield count
#         count += 1

# def count_up_to_fn(max):
#     result = []
#     count = 1
#     while count <= max:
#         result.append(count)
#         count += 1
#     return result

# # res = count_up_to_fn(10000000000000000000000)
# res = count_up_to_gen(10000000000000000000000)

# for num in res:
#     print(num)

# print(count_up_to_gen(10000000000000000000000))

# res = count_up_to_gen(10)

# for num in res:
#     print(num)

# nums = (num for num in range(100))

# print(nums)

# def fib_list(max):
#     nums = []
#     a, b = 0, 1
#     while len(nums) < max:
#         nums.append(b)
#         a, b = b, a + b
#     return nums

# def fib_gen(max):
#     a, b = 0, 1
#     count = 0
#     while count < max:
#         a, b = b, a + b
#         yield a
#         count += 1

# # res = fib_list(10000)
# res2 = fib_gen(100000)

# for num in res2:
#     print(num)

# Higher order function
# def math(a, b, fn):
#     return fn(a, b)

# def add(a, b):
# #     return a + b

# # print(math(10, 5, add))
# # print(math(10, 5, lambda a, b: a - b))

from random import choice

# def say_something():

#     def words():
#         w = choice(["hello", "hi", "namaste", "satsriakal", "salaam"])
#         return w

#     return words

# # higher order function (function factories)
# def say_something(words_list):

#     def words():
#         w = choice(words_list)
#         return w

#     return words

# a = 10
# b = say_something(["hello", "hi", "namaste", "satsriakal", "salaam"])

# print(b())

# def sum(n, func):
#     total = 0
#     for num in range(1, n + 1):
#         total += func(num)
#     return total

# def square(n):
#     return n * n

# def cube(n):
#     return n * n * n

# print(sum(3, square))
# print(sum(3, cube))

# def greet(person):

#     def get_mood():
#         mood = ["Hey", "What!", "What the heck do you want!", "Get lost!"]
#         msg = choice(mood)
#         return msg

#     result = f"{get_mood()} {person}"
#     return result

# print(greet("John"))

# import random

# def make_greet_func(person):

#     def make_message():
#         msg = random.choice(
#             ["Hello", "What!", "What the heck do you want!", "Get lost!"])
#         return f"{msg} {person}"

#     return make_message

# greet_me = make_greet_func("John")

# print(greet_me())

# def greet(fn):
#     def wrapper():

# # Decorator function
# def stars(fn):

#     def wrapper():
#         print("*" * 10)
#         fn()
#         print("*" * 10)

#     return wrapper

# @stars  # greet = stars(greet)
# def greet():
#     print("Hello, My name is John")

# # greet = stars(greet)

# greet()

from functools import wraps


def make_upper_case(fn):
    """This is the doc for make_upper_case"""

    @wraps(fn)  # wrapper = wraps(wrapper)
    def wrapper(*args, **kwargs):
        """This is the doc for wrapper"""
        return fn(*args, **kwargs).upper()

    return wrapper


# @make_upper_case  # say_hello = make_upper_case(say_hello)
# def say_hello(name):
#     return f"Hello, {name}."

# @make_upper_case # say_message = make_upper_case(say_message)
# def say_message(name, message):
#     """This is the docs for say_message"""
#     return f"{message}, {name}"

# # print(say_hello("James"))
# # print(say_message("James", "Hi"))

# print(say_message.__doc__)

# def ensure_first_arg(val):

#     def inner(fn):

#         def wrapper(*args, **kwargs):
#             if args and args[0] != val:
#                 raise ValueError(f"First argument needs to be {val}")
#             else:
#                 return fn(*args, **kwargs)

#         return wrapper

#     return inner

# @ensure_first_arg("biryani")
# def fav_food(*foods):  # fav_food = inner(fav_food)
#     print(foods)

# fav_food = ensure_first_arg("biryani")(fav_food)

# fav_food("biryani", "butter chicken", "tandori", "panner masala")


def enforce(*types):

    def inner(fn):

        def wrapper(*args, **kwargs):
            new_args = []
            for a, t in zip(args, types):  # [("hello", str), (5, int)]
                try:
                    new_args.append(t(a))  # str(10)
                except (ValueError, TypeError):
                    return "Something went wrong"
            return fn(*new_args)

        return wrapper

    return inner


@enforce(str, int)
def announce(msg, times):
    print((msg + "\n") * times)


announce(int, 5)