Menu

Python Daily Evening October 2023

Python Daily Evening October 2023

Scratchpad #1 – #4

# PRIMITIVE DATA TYPE - ATOMS

# STR, INT, FLOAT, NONE, BOOL

# NAME: STR, ARTIST: STR, ALBUM: STR, TRACK_LENGTH: FLOAT,

# EXPRESSION / STATEMENT

# score = 10
# score = score + 2
# print(score)

# player_one_high_score = 10  # snake casing
# playerOneHighScore = 10  # camel casing
# PlayerOneHighScore = 10  # pascal casing
# player-one-high-score = 10 # kebab casing

# GST_RATE = 18
# __score__ = 10


# first_name = "john"
# first_name = ['j', 'o', 'h', 'n']

# name = "John Doe"
# # name.lower().find("doe")

# name.find("Doe").upper()

# print("Enter amount in USD")
# usd = float(input("Enter amount in USD: "))
# inr = usd * 82.12

# print(f"USD {usd} is INR {inr}")

# age = int(input("Please enter your 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("You aren't allowed")

# logged_in_user = None

# if logged_in_user:
#     print("Welcome to the app")
# else:
#     print("Please login to continue")

# age = int(input("Please enter your 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("You aren't allowed")

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

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("You aren't allowed")
else:
    print("Please enter a valid value")


# for num in range(10):
#     print(f"{num} - Hello World")

# full_name = "John"

# for char in full_name:
#     print(char)

# print("OUTSIDE THE LOOP")

# for num in range(-1, -10, -1):
#     print(num)

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

# password = input("Enter your password: ")

# while password != "hello":
#     print("Incorrect password!")
#     password = input("Enter your password again: ")

# print("Welcome")

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

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

# from random import random

# while True:
#     print(random())

# password = input("Enter your password: ")

# while password != "hello":
#     if password == 'quit':
#         break
#     print("Incorrect password!")
#     password = input("Enter your password again: ")

# password = input("Enter your password: ")

# while True:
#     if password == 'hello':
#         break
#     print("Incorrect password!")
#     password = input("Enter your password again: ")

# for num in range(10):
#     if num == 5:
#         break
#     print(num)

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

    if (player1 == 'rock' and player2 == 'scissor') or (
            player1 == 'paper'
            and player2 == 'rock') or (player1 == 'scissor'
                                       and player2 == 'paper'):
        print("Player 1 wins!")
    elif (player2 == 'rock'
          and player1 == 'scissor') or (player2 == 'paper' and player1
                                        == 'rock') or (player2 == 'scissor'
                                                       and player1 == 'paper'):
        print("Player 2 wins!")
    elif player1 == player2:
        print("DRAW")
    else:
        print("Something went wrong")

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

Scratchpad 5-10

langs = ['Python', 'JavaScript', 'Rust', 'Elm', 'WASM', 'Odin']

# for lang in langs:
#     print(lang)

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


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

# # # doubles = [n // 2 for n in nums]  # [2,4,6,8,10]
# # # evens = [num for num in nums if num % 2 == 0]

# # result = [num * 2 if num % 2 == 0 else num / 2 for num in nums]

# # # doubles = []

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

# # print(result)

# # message = "Hello Python!"

# # print("".join(char for char in message if char not in "aeiou"))

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

# # print(nums[20])

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

# for num in nums: # [1,2,3] - 3
#     for n in num:
#         print(n)

# product = [1, 'iPhone 15', 'Apple', 'Some description...', 500, 200000, True]

# product = {
#     0: 1,
#     1: 'iPhone 15',
#     2: 'Apple',
#     3: 'Some description...',
#     4: 500,
#     5: 200000,
#     6: True
# }

# print(product[0])

# product = [{
#     'sr_no': 1,
#     'name': 'iPhone 15',
#     'price': 200000,
#     'description': 'Some description...',
#     'in_stock': 500,
#     'discounted': True,
#     1: 10000
# }, {
#     'sr_no': 1,
#     'name': 'iPhone 15',
#     'price': 200000,
#     'description': 'Some description...',
#     'in_stock': 500,
#     'discounted': True,
#     1: 10000
# }, {
#     'sr_no': 1,
#     'name': 'iPhone 15',
#     'price': 200000,
#     'description': 'Some description...',
#     'in_stock': 500,
#     'discounted': True,
#     1: 10000
# }]

# print(product['price'])

product = {
    'sr_no': 1,
    'name': 'iPhone 15',
    'price': 200000,
    'description': 'Some description...',
    'in_stock': 500,
    'discounted': True,
}

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

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

# for key in product.keys():
#     print(key, product[key])

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

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

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

for k, v in product.items():
    print(k, v)


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

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

# from random import random

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


# result = flip_coin()
# print(result)


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


# print(add(10, 20))


from random import random

def flip_coin():
    num = random()
    if num > 0.5:
        print("HEADS")
    else:
        print("TAILS")


# def flip_several_times(times):
#     for _ in range(times):
#         flip_coin()


# flip_several_times(3)



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

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

# def is_odd_number(num):
#     if num % 2 == 1:
#         return True
#     return False

# print(is_odd_number(9))


# def multiply(a=1, b=1):
#     return a * b

# print(multiply(10, 3))

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

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

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

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



def full_name(first_name, last_name, age):
    print(f"Hello my name is {first_name} {last_name} and I am {age} years old.")


full_name(age=20, last_name="Doe", first_name="John")


# full_name = "Jane Doe" # Global Scope

# def greet():
#     # Local Scope
#     # full_name = "Jack Smith"
#     print(full_name)

# greet()

# print(full_name)


# total = 0

# def dummy():
#     global total
#     total += 1
#     print(total)

# dummy()

# print(total)


# GLOBAL SCOPE

# def outer():
#     # NON-LOCAL SCOPE
#     total = 0

#     def inner():
#         # LOCAL SCOPE
#         nonlocal total
#         total += 1
#         print(total)

#     inner()


# outer()


# def greet_user(first_name, last_name, message):
#     """
#     Function that accepts a person's name and a message.
#     @params first_name {str}
#     @params last_name {str}
#     @params message {str}
#     @returns str
#     """
#     return f"{message}, {first_name} {last_name}."


# # print(greet_user("John", "Doe", "Hello"))
# # print(greet_user.__doc__)
# print("".upper.__doc__)


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


# # print(add(10, 5))
# print(add(10, 20, 30, 40, 50))


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

# profile(first_name="John", last_name="Doe", age=20, hello="World")


# def dummy(a, b, *args, moderator="admin", **kwargs):
#     print(a, b, args, moderator, kwargs)


# dummy(10, 20, 30, 40, 50, 60, 70, moderator="jane", hello="World", test=200)



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

# data = [10, 20, 30]

# print(add(*data))



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


# name = {"first": "Robert", "last": "Moore"}

# say_name(**name)
# # say_name(first="Robert", last="Moore")

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

# hello = add

# print(hello(10, 5))

# square = lambda num: num ** 2
# add = lambda a, b: a + b

# print(square(2))
# print(add(2, 10))


# def math(a, b, fn):
#     return fn(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 capitalize_str(input_str):
    words = input_str.split(" ")
    cap_words = [word[0].upper() + word[1:] for word in words]
    result = " ".join(cap_words)
    return result


print(capitalize_str("hello this is something"))


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


# double = lambda num: num * 2

# print(double(10))


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

filtered_names = filter(lambda name: len(name) > 4, names)
upper_names = list(map(lambda name: name.upper(), filtered_names))
print(upper_names)

result = [name.upper() for name in names if len(name) > 4]
print(result)

# upper_names = list(map(lambda name: name.upper(), filter(lambda name: len(name) > 4, names)))
# print(upper_names)


# contacts = []

# def add_contact():
#     name = input("Enter the name of the contact: ")
#     phone = input("Enter the phone number of the contact: ")
#     email = input("Enter the email address of the contact: ")
#     contact = {
#         'name': name,
#         'phone': phone,
#         'email': email
#     }
#     contacts.append(contact)
#     print("Contact added successfully.")


# def view_contacts():
#     if not contacts:
#         print('No contacts found')
#     else:
#         print('Contacts')
#         for contact in contacts:
#             print(f"Name: {contact['name']}")
#             print(f"Phone: {contact['phone']}")
#             print(f"Email: {contact['email']}")
#             print('--------------------------')


# def search_contacts():
#     name = input('Enter the name of the contact to search: ')
#     found_contacts = []
#     for contact in contacts:
#         if contact['name'].lower() == name.lower():
#             found_contacts.append(contact)

#     if not found_contacts:
#         print('No matching contacts found.')
#     else:
#         print('Matching contacts:')
#         for contact in found_contacts:
#             print(f"Name: {contact['name']}")
#             print(f"Phone: {contact['phone']}")
#             print(f"Email: {contact['email']}")
#             print('--------------------------')


# def update_contact():
#     name = input('Enter the name of the contact to update: ')
#     for contact in contacts:
#         if contact['name'].lower() == name.lower():
#             phone = input("Enter the updated phone number: ")
#             email = input("Enter the updated email address: ")
#             contact['phone'] = phone
#             contact['email'] = email
#             print("Contact updated successfully")
#             return

#     print('Contact not found')


# def delete_contact():
#     name = input('Enter the name of the contact to delete: ')
#     for contact in contacts:
#         if contact['name'].lower() == name.lower():
#             contacts.remove(contact)
#             print("Contact deleted successfully")
#             return

#     print('Contact not found')


# while True:
#     print('Contact Management System')
#     print('1. Add contact')
#     print('2. View contacts')
#     print('3. Search contacts')
#     print('4. Update contact')
#     print('5. Delete contact')
#     print('6. Exit')

#     choice = input('Enter your choice: ')

#     if choice == '1':
#         add_contact()
#     elif choice == '2':
#         view_contacts()
#     elif choice == '3':
#         search_contacts()
#     elif choice == '4':
#         update_contact()
#     elif choice == '5':
#         delete_contact()
#     elif choice == '6':
#         print('Thank you for using the contact management system.')
#         break
#     else:
#         print("Invalid choice. Please try again.")


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 add 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:
    print()
    game_deck_list = shuffle(starting_deck_list)

    current_card_dict = get_card(game_deck_list)

    current_card_rank = current_card_dict['rank']
    current_card_suit = current_card_dict['suit']
    current_card_value = current_card_dict['value']

    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.lower()

        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_suit = next_card_suit
        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!')