Menu

Python daily morning 04-11-2022

Python daily morning 04-11-2022

Scratchpad 1 and scratchpad 2

print("Hello World")

# Snake Case - high_score / player_1_high_score
# Camel Case - highScore / player1HighScore
# Pascal Case - HighScore / Player1HighScore
# Kebab Case - high-score / player-1-high-score


# player_one_score = 10
# player_two_score = 15

# total_scores = player_one_score + player_two_score

# print(total_scores)

score1 = 10
score2 = 20

score3 = score1 / score2  # duck typing

Scratchpad 2

# # print("Amount of US Dollars you want to convert?")
# usd = input("Amount of US Dollars you want to convert? ")
# inr = float(usd) * 82.23
# print(f"${usd} is equal to Rs. {inr}")

# name = "Mark Zuckerberg"

# if name == "Elon Musk":
#     print("Twitter")  # code block
# elif name == "Mark Zuckerberg":
#     print("Meta")
# elif name == "Sundar Pichai":
#     print("Google")
# else:
#     print("Unknown name")

# print("Program completed")


# is_logged_in = True

# if is_logged_in:
#     print("Access granted")
# else:
#     print("Access denied")


# logged_in_user = "alklsmndjkasd"

# if logged_in_user:
#     print("Access granted")
# else:
#     print("Access denied")


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

# if age > 65:
#     print("Drinks are free")
# elif age > 21:
#     print("You can enter and you can drink")
# elif age > 18:
#     print("You can enter but you can't drink")
# else:
#     print("Not allowed")


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

# if age >= 18 and age < 21:
#     print("You can enter but you can't drink")
# elif age >= 21 and age < 65:
#     print("You can enter and you can drink")
# elif age > 65:
#     print("Drinks are free")
# else:
#     print("Not allowed")


# age = input("How old are you? ")

# if age:
#     age = int(age)
#     if age >= 18 and age < 21:
#         print("You can enter but you can't drink")
#     elif age >= 21 and age < 65:
#         print("You can enter and you can drink")
#     elif age > 65:
#         print("Drinks are free")
#     else:
#         print("Not allowed")
# else:
#     print("Please enter your age!")


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

if player1 == player2:
    print("It's a tie")
elif (
    (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")
else:
    print("Something went wrong")

Scratchpad #3

# # print("Amount of US Dollars you want to convert?")
# usd = input("Amount of US Dollars you want to convert? ")
# inr = float(usd) * 82.23
# print(f"${usd} is equal to Rs. {inr}")

# name = "Mark Zuckerberg"

# if name == "Elon Musk":
#     print("Twitter")  # code block
# elif name == "Mark Zuckerberg":
#     print("Meta")
# elif name == "Sundar Pichai":
#     print("Google")
# else:
#     print("Unknown name")

# print("Program completed")


# is_logged_in = True

# if is_logged_in:
#     print("Access granted")
# else:
#     print("Access denied")


# logged_in_user = "alklsmndjkasd"

# if logged_in_user:
#     print("Access granted")
# else:
#     print("Access denied")


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

# if age > 65:
#     print("Drinks are free")
# elif age > 21:
#     print("You can enter and you can drink")
# elif age > 18:
#     print("You can enter but you can't drink")
# else:
#     print("Not allowed")


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

# if age >= 18 and age < 21:
#     print("You can enter but you can't drink")
# elif age >= 21 and age < 65:
#     print("You can enter and you can drink")
# elif age > 65:
#     print("Drinks are free")
# else:
#     print("Not allowed")


# age = input("How old are you? ")

# if age:
#     age = int(age)
#     if age >= 18 and age < 21:
#         print("You can enter but you can't drink")
#     elif age >= 21 and age < 65:
#         print("You can enter and you can drink")
#     elif age > 65:
#         print("Drinks are free")
#     else:
#         print("Not allowed")
# else:
#     print("Please enter your age!")


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

if player1 == player2:
    print("It's a tie")
elif (
    (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")
else:
    print("Something went wrong")

Scratchpad #4

# char = " "

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

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


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

# for num in range(5, 50):
#     print(num)

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

# for num in range(0, -10, -1):
#     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 the secret password: ")

# while password != "testpass123":
#     print("Wrong password")
#     password = input("Please enter the secret password again: ")


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

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


# count = 0
# while count < 10:
#     print(count)
#     if count == 6:
#         break
#     count += 1


# password = input("Please enter the secret password: ")

# while True:
#     if password == "testpass123":
#         break

#     print("Wrong password")
#     password = input("Please enter the secret password again: ")


while True:
    player1 = input("Enter player 1's choice: ")
    player2 = input("Enter player 2's choice: ")

    if player1 == player2:
        print("It's a tie")
    elif (
        (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")
    else:
        print("Something went wrong")

    play_again = input("Do you want to play again? (y/n): ")
    if play_again != "y":
        break

Scratchpad #5

# langs = ["Python", "JavaScript", "Rust", "Elm", "WASM"]

# # for lang in langs:
# #     print(lang)

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


langs = [
    "Haskell",
    "JavaScript",
    "Perl",
    "Python",
    "Python",
    "Python",
    "Ruby",
    "Rust",
    "V",
]

count = 0

while count < len(langs):
    print(langs[count])
    count += 2


# count = len(langs) - 1

# while count >= 0:
#     print(langs[count])
#     count -= 2

Scratchpad #6

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

# doubles = []
# for num in nums:
#     doubles.append(num * 2)

# # print(doubles)

# doubles = [num * 2 for num in nums]
# # print(doubles)


# names = ["john", "jack", "jane", "jill"]
# upper_names = [name.upper() for name in names]
# print(names)
# print(upper_names)


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

# evens = [num for num in numbers if num % 2 == 0]

# print(evens)


# names = ["john", "johnny", "jimmy", "jill"]
# selected = [name for name in names if len(name) < 5]

# selected = []
# for name in names:
#     if len(name) < 5:
#         selected.append(name)

# print(selected)


names = ["john", "johnny", "jimmy", "jill"]

# new_names = [name for name in names if len(name) < 5]
# new_names = [name.upper() if len(name) < 5 else name for name in names]
# print(new_names)

# new_names = []

# for name in names:
#     if len(name) < 5:
#         new_names.append(name.upper())
#     else:
#         new_names.append(name)

# print(new_names)


# message = "Hello Python!"

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


for lst in nl:  # [4, 5, 6]
    for num in lst:  # 3
        print(num)


nl = [
    [[1, 2, 3], [1, 2, 3, 5], [1, 2, 3]],
    [[1, 2, 3], [1, 2, 3, 2, 234, 324], [1, 2, 3]],
    [[1, 2, 3], [1, 2, 3], [1, 2, 3]],
]

Scratchpad #7

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


# products = [
#     [
#         "iPhone 14 Pro Max",
#         "Apple",
#         "Some description...",
#         150000,
#         250,
#         True,
#         "electronics",
#     ],
#     [
#         "iPhone 14 Pro Max",
#         "Apple",
#         "Some description...",
#         150000,
#         250,
#         True,
#         "electronics",
#     ],
#     [
#         "iPhone 14 Pro Max",
#         "Apple",
#         "Some description...",
#         150000,
#         250,
#         True,
#         "electronics",
#     ],
# ]

# product1 = [
#     "iPhone 14 Pro Max",
#     "Apple",
#     "Some description...",
#     250,
#     150000,
#     True,
#     "electronics",
# ]

# print(product1[3])

# product2 = [
#     "One Plus Nord",
#     "One Plus",
#     "Some description...",
#     60000,
#     1000,
#     True,
#     "electronics",
# ]


# product1 = {
#     "name": "iPhone 14 Pro Max",
#     "brand": "Apple",
#     "description": "Some description...",
#     "in_stock": 250,
#     "discounted": True,
#     "category": ["electronics", "consumer", "something else"],
#     "price": 150000,
#     1000: "Hello World",
#     "other": {"hello": "world", "test": "text"},
# }

# product2 = dict(name="Nord", brand="One Plus", price=20000)

# print(product2)


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

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

# for key in book.keys():
#     print(key)

# for item in book.items():
#     print(item)

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


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

Scratchpad #8

# # def greet():
# #     print("Hello World")
# #     print("Hello Again")


# # greet()
# # greet()
# # greet()


# # def square_of_7():
# #     result = 7**2
# #     return result


# # result = square_of_7()
# # print(result)


# # from random import random


# # def coin_flip():
# #     if random() > 0.5:
# #         print("HEADS")
# #     else:
# #         print("TAILS")


# # coin_flip()


# # def add(num1, num2):
# #     return num1 + num2


# # print(add(10, 23))


# # from random import random


# # def coin_flip():
# #     if random() > 0.5:
# #         print("HEADS")
# #     else:
# #         print("TAILS")


# # def flip(times):
# #     for _ in range(times):
# #         coin_flip()


# # flip(10)


# # def sum_odd_numbers(numbers):
# #     total = 0
# #     for num in numbers:
# #         if num % 2 != 0:
# #             total += num
# #     return total


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


# # def is_odd_number(number):
# #     if number % 2 != 0:
# #         return True
# #     return False


# # print(is_odd_number(5))


# # def exponent(num=2, power=1):
# #     return num**power


# # print(exponent(5, 4))


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


# def mul(a, b):
#     return a * b


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


# print(math(10, 20))

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


# def full_name(first="Jane", last="Smith"):
#     return "Your name is " + first + " " + last + "."


# print(full_name(last="Doe", first="John"))
# print(full_name("john"))


# full_name = "John Doe"


# def greet():
#     full_name = "Jane Doe"
#     print(full_name)


# # greet()
# print(full_name)


# total = 0


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


# print(static())


def outer():
    count = 0

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

    return inner()


print(outer())

Scratchpad #9

# # # def greet(message, person):
# # #     """
# # #     This function accepts a message and a name.
# # #     @params
# # #     message: str - Message your want to print
# # #     person: str - Name of the person
# # #     """
# # #     return f"{message}, {person}"


# # # # print(greet("Hello, how are you", "John Doe"))

# # # # print(greet.__doc__)
# # # print(print.__doc__)


# # # total = 10


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


# # # total = change(num=total)
# # # print(total)


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


# # print(
# #     add(
# #         10,
# #         20,
# #         12,
# #         123,
# #     )
# # )


# # def profile(**details):
# #     print(
# #         f"My name is {details['first_name']} {details['last_name']} and I am {details['age']} years old"
# #     )


# # profile(first_name="John", last_name="Doe", age=25)


# # def show_info(num1, num2, *nums, role="admin", **details):
# #     print(num1, num2, nums, role, details)


# # show_info(1, 2, 3, 4, role="moderator", hello="world", fav_num=10)


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


# # data = [10, 23, 45, 6, 32]

# # add_all_values(*data)


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


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

# # say_name(data["first"], data["last"])
# say_name(**data)


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


# hello_world = add

# print(hello_world(10, 20))


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


# def add(a, b):
#     return a + b
# def sub(a, b):
#     return a - b
# print(math(10, 5, sub))

# print(math(10, 5, lambda a, b: a * b))
# print(math(10, 5, lambda a, b: a / b))


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


# add2 = lambda a, b: a + b

# print(add2(10, 34))


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

# doubles = [num * 2 for num in nums]
# print(doubles)

# doubles2 = list(map(lambda num: num * 2, nums))
# print(doubles2)


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

# evens = [num for num in nums if num % 2 == 0]
# odds = list(filter(lambda num: num % 2 == 1, nums))

# print(evens)
# print(odds)


names = ["John", "Jack", "James", "Desmond", "Charlie", "Jacob"]

print(
    list(
        map(
            lambda name: f"The one who wins is {name}",
            filter(lambda name: len(name) < 5, names),
        )
    )
)

Scratchpad 10

# import random

# SUIT_TUPLE = ("Spades", "Hearts", "Clubs", "Diamonds")
# RANK_TUPLE = (
#     "Ace",
#     "2",
#     "3",
#     "4",
#     "5",
#     "6",
#     "7",
#     "8",
#     "9",
#     "10",
#     "Jack",
#     "Queen",
#     "King",
# )

# NCARDS = 8


# def get_card(deck_list_in):
#     this_card = deck_list_in.pop()
#     return this_card


# def shuffle(deck_list_in):
#     deck_list_out = deck_list_in.copy()
#     random.shuffle(deck_list_out)
#     return deck_list_out


# print("Welcome to higher or lower.")
# print(
#     "You have to choose whether the next card to be shown will be higher or lower than the current card."
# )
# print("Getting it right adds 20 points; get it wrong and you will lose 15 points.")
# print("You have 50 points to start.")
# print()

# starting_deck_list = []
# for suit in SUIT_TUPLE:
#     for this_value, rank in enumerate(RANK_TUPLE):
#         card_dict = {"rank": rank, "suit": suit, "value": this_value + 1}
#         starting_deck_list.append(card_dict)

# score = 50

# while True:
#     game_deck_list = shuffle(starting_deck_list)
#     current_card_dict = get_card(game_deck_list)
#     current_card_rank = current_card_dict["rank"]
#     current_card_value = current_card_dict["value"]
#     current_card_suit = current_card_dict["suit"]
#     print(f"Starting card is {current_card_rank} of {current_card_suit}")
#     print()

#     for card_number in range(0, NCARDS):
#         answer = input(
#             f"Will the next card be higher or lower than the {current_card_rank} of {current_card_suit}? (enter h or l): "
#         )
#         answer = answer.casefold()
#         next_card_dict = get_card(game_deck_list)
#         next_card_rank = next_card_dict["rank"]
#         next_card_suit = next_card_dict["suit"]
#         next_card_value = next_card_dict["value"]
#         print(f"Next card is {next_card_rank} of {next_card_suit}")

#         if answer == "h":
#             if next_card_value > current_card_value:
#                 print("You got it right, it was higher")
#                 score += 20
#             else:
#                 print("Sorry, it was not higher")
#                 score -= 15
#         elif answer == "l":
#             if next_card_value < current_card_value:
#                 print("You got it right, it was lower")
#                 score += 20
#             else:
#                 print("Sorry, it was not lower")
#                 score -= 15

#         print(f"Your score is {score}")
#         print()
#         current_card_rank = next_card_rank
#         current_card_value = next_card_value

#     go_again = input("To play again, press ENTER, or 'q' to quit: ")
#     if go_again == "q":
#         break

# print("Thank you for playing")


person = [["name", "john"], ["job", "programmer"], ["city", "mumbai"]]

personDetails = {}

for lst in person:
    personDetails[lst[0]] = lst[1]

print(personDetails)

Scratchpad #11

# def div(a, b):
#     if type(a) != int or type(b) != int:
#         raise TypeError("a and b need to be integers")
#     return a / b


# print(div(10, "hello"))


# print("Hello World!")
# raise Exception("Something went wrong")
# print("Goodbye World")


# def div(a, b):
#     try:
#         return a / b
#     except:
#         return "Something went wrong"


# def div(a, b):
#     try:
#         return a / b
#     except (TypeError, ZeroDivisionError):
#         return "Something went wrong"


# def div(a, b):
#     try:
#         result = a / b
#     except (TypeError, ZeroDivisionError) as err:
#         return f"Something went wrong. {err}"
#     else:
#         # MORE LOGIC
#         return result
#     finally:
#         print("I will always run!")


# print(div(10, 2))


# import random as r


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


# print(r.random())
# print(r.randint(10, 100))


from random import randint as ri, random, shuffle

# from random import *

print(ri(1, 100))
print(random())