Python Evening 28

Python Evening 28

Ex. 1:
Use a for loop to add up every odd number from 50 to 100 (inclusive) and store the result in the variable `x`.

Ex. 2:
Create a list and add items of your own choice to it. Write code to demonstrate all the
list methods you have learnt so far.

Ex. 3:
sounds = ["numbers", "data", "python", "source", "selenium", "networks", "structures"]

a. Write code that loops over the list and adds all the strings together to form one
large combined string (don't add any spaces between them)
b. The combined string should be in all UPPERCASE as well
c. Save the result in a variable called `result`
# print("Hello World")  # This will print some text
# print(102)
# print(-314.2445)


# PEMDAS / BODMAS
# This a comment for me

price = 0
print(price)

# apple_iphone_price = 1000

price = 200
print(price)

new_price = 200 * (18 / 100)

print(new_price)

copied_price = price

print(copied_price)

# val1 = 100
# val2 = 200
# val3 = 300

val1, val2, val3 = 100, 200, 300

print(val1, val2, val3)
# None
phone_no = None
phone_no = 9873232332


# Strings
first_name = "john"
last_name = "doe"

# String escape sequences
message = 'He \\said, \n\n\\n"\vthat\'s \tcool"!'

# print(first_name)
# print(last_name)
print(message)
# # print("Enter your amount in USD: ")
# user_input = input("Enter your amount in USD: \n")

# inr = int(user_input) * 75

# # print(f"User typed {user_input}")

# print(f"{user_input} USD is {inr} INR.")
# # print(input())


# user_input = input("Please enter your city: ")

# if user_input.lower() == "rio":
#     print("You are welcome here!")
#     print("You are welcome here!")
#     print("You are welcome here!")
#     print("You are welcome here!")
# elif user_input.lower() == "wuhan":
#     print("Get into qurantine")
# else:
#     print("I don't know what city that is")


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

# if (age >= 18 and age < 21) or age == 0:
#     print("You are allowed to enter, but you cannot drink.")
# elif age >= 21 and age < 65:
#     print("You can enter and can consume alcohol.")
# elif age >= 65:
#     print("Drinks are free!")
# else:
#     print("Get lost")


# age = 13
# city = "rio"

# if age > 18 and city == "rio":
#     print("You are welcome")
# elif not (age < 18 or city == "mumbai"):
#     print("Good")
# else:
#     print("ELSE condition")

# num1 = 10
# num2 = 10

# num1 == num2


age = input("Please enter your age: ")  # 19
city = input("Please enter your city: ")

if age:
    age = int(age)
    if age >= 18 and age < 21:
        if city == "mumbai":
            print("You are allowed to enter, but you cannot drink.")
        else:
            print("You can drink. You can do whatever you want")
    elif age >= 21 and age < 65:
        print("You can enter and can consume alcohol.")
    elif age >= 65:
        print("Drinks are free!")
    else:
        print("Get lost")
else:
    print("Please enter a value")


if not age:
    print("Please add a valid value")
elif int(age) >= 18 and int(age) < 21:
    print("You are allowed to enter, but you cannot drink.")
elif int(age) >= 21 and int(age) < 65:
    print("You can enter and can consume alcohol.")
elif int(age) >= 65:
    print("Drinks are free!")
else:
    print("Get lost")
# print("...rock...")
# print("...paper...")
# print("...scissor...")

# player1 = input("Player 1 - Enter your choice: ")
# player2 = input("Player 2 - Enter your choice: ")

# # Conditional Logic

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


# if player1 == player2:
#     print("It's a tie")
# elif player1 == "rock":
#     if player2 == "scissor":
#         print("Player 1 wins")
#     elif player2 == "paper":
#         print("Player 2 wins")
# elif player1 == "paper":
#     if player2 == "rock":
#         print("Player 1 wins")
#     elif player2 == "scissor":
#         print("Player 2 wins")
# elif player1 == "scissor":
#     if player2 == "paper":
#         print("Player 1 wins")
#     elif player2 == "rock":
#         print("Player 2 wins")
# else:
#     print("Something went wrong")
random_numbers = list(range(10, 31))
deleted_numbers = []

deleted_numbers.append(random_numbers.pop(3))
deleted_numbers.append(random_numbers.pop())
deleted_numbers.append(random_numbers.pop(0))
# print(deleted_numbers)

deleted_numbers.clear()
# print(deleted_numbers)

random_numbers.extend(list(range(15, 25)))
# random_numbers.extend([15,16,27,18,19,20,21,22,23,24])
print(random_numbers)

random_numbers.remove(20)
print(random_numbers)


print(random_numbers.index(29))


# my_strs.sort().reverse()
# words = ["hello", "howdy", "namaste", "shalom", "mushi"]

# name = "john doe"

# print()


# print(".".join(words))


# frameworks = ["Django", "Flask"]

# oldValue = frameworks[0]
# frameworks[0] = (frameworks[1],)
# frameworks[1] = oldValue


# for char in [1, 2, 3, 45, 65, 67, 432, 21, 12]:
#     print(char * char)


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

# while password != "balony1":
#     password = input("Please enter your password: ")

# print("Welcome Back")


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

# i = 1
# while i < 11:
#     print(i)
#     i += 1
#     # i = i + 1


# words = ["hello", "howdy", "namaste", "shalom", "mushi"]

# i = 0
# while i < len(words):
#     print(words[i])
#     i += 1


i = 1
password = input("Please enter your password: ")
while password != "balony1":
    print(i)
    if i > 3:
        break
    password = input("Please enter your password: ")
    i += 1
# password = input("Please enter your password: ")

# attempts = 1
# while password != "python3333":
#     print("Incorrect Password!")
#     if attempts > 2:
#         break
#     password = input("Please enter your password: ")
#     attempts += 1

# if password != "python3333":
#     print("You are locked out!")
# else:
#     print("Welcome back!")

# print(f"Total attempts: {attempts * 1000}")


total = 0
odd_nums = []

for number in range(50, 101):
    if number % 2 != 0:
        odd_nums.append(number)
        total += number

print(total)
print(odd_nums)

movies2 = []
for movie in movies:
    movies2.append(movie.upper())
# nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

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


# [print(lst) for lst in nested_list]

# [[print(item) for item in lst] for lst in nested_list]


# nested_list

# # loop 1
# lst -> [1, 2, 3]
#     # inner loop
#     item -> 1 ==== print()
#     item -> 2 ==== print()
#     item -> 3 ==== print()
# lst -> [4,5,6]
#     item -> 4 ==== print()
#     item


# [print("hello world") for x in range(1, 6)]

# none_list = [[print("hello world") for y in range(1, 4)] for x in range(1, 6)]
# print(none_list)

# [[y * x for y in range(3)] for x in range(10)]


# [["X" if num % 2 != 0 else "O" for num in range(1, 4)] for val in range(1, 4)]


# iPhone = ["iPhone", "Apple", 100000, 1000, "SK6283njdas", "This is some description..."]
# mi_phone = ["Redmi", "Xioami", 3000, 20000]

# print(phone[0])
# print(phone[2])


iPhone = {
    "name": "iPhone",
    "name": "Apple",
    "brand": "Apple",
    "price": 100000,
    "stock": 1000,
    42: "cool",
}


# iPhone = dict(name="iPhone", brand="Apple", price=100000)
print(iPhone["stock"])
print(iPhone["name"])
print(iPhone[42])
# 1. Print out: "John Doe is an admin" accessing values using the below dictionary
user = {"first_name": "John", "last_name": "Doe", "role": "admin"}


# 2: Loop over donations, add all the VALUES together and store 
# in a variable called total_donations
donations = {
    "john": 983.23,
    "jane": 2332.12,
    "jack": 23.22,
    "jim": 765.0,
    "jake": 342.34,
    "joe": 18.65,
}


# 3. Create a dictionary named `initial_state` and use all the below list 
# items as key names and make their values to be 0
game_properties = [
    "current_score",
    "high_score",
    "number_of_lives",
    "items_in_inventory",
    "power_ups",
    "ammo",
    "enemy_kills",
    "minutes_played",
]


# 4. Given two lists ["BOM", "DEL", "MAA"] and ["Mumbai", "Delhi", "Chennai"]
# create a dictionary that looks like this {'BOM': 'Mumbai', 'DEL': 'Delhi', 'MAA': 'Chennai'}.
# Save it to a variable called answer.
codes = ["BOM", "DEL", "MAA"]
cities = ["Mumbai", "Delhi", "Chennai"]


# 5. Convert the below multi-dimensional list to a dictionary: End result should look like
# {'name': 'John Doe', 'age': 25, 'job': 'Python Programmer'}
user = [["name", "John Doe"], ["age", 25], ["job", "Python Programmer"]]

Scratchpad #9

# song = {
#     "name": "Sober",
#     "artist": "Tool",
#     "album": "Undertow",
# }

# # print(song["genre"])
# print(song.get("genre"))


# song = {"name": "Vicarious", "album": "10,000 Days"}

# print(song)

# # song.pop()
# song.pop("album")

# print(song)

# song = {"name": "The Pot", "artist": "Tool", "album": "10,000 Days"}


# donations = {
#     "john": 983.23,
#     "jane": 2332.12,
#     "jack": 23.22,
#     "jim": 765.0,
#     "jake": 342.34,
#     "joe": 18.65,
# }

products = [
    {
        "name": "iPhone",
        "brand": "Apple",
        "price": 100000,
        "SKU": "23423nsao3nja",
        "stock": 100,
        "categories": ["mobiles", "electronics", "expensive"],
    },
    {
        "name": "iPhone",
        "brand": "Apple",
        "price": 100000,
        "SKU": "23423nsao3nja",
        "stock": 100,
        "categories": ["mobiles", "electronics", "expensive"],
    },
    {
        "name": "iPhone",
        "brand": "Apple",
        "price": 100000,
        "SKU": "23423nsao3nja",
        "stock": 100,
        "categories": ["mobiles", "electronics", "expensive"],
    },
]

print(products[1]["categories"][-1])
# user_input = input("Please enter a string: ")
# words = user_input.split()

# fixed_words = tuple(words)

# print(fixed_words)


# DRY
# WET


# # Function definition/declaration
# def greet():
#     print("Hello World!")


# greet()


# result = int("10")


def greet():
    print("Line start")
    print("Line end")
    return "Hello World!"


# message = greet()

print(greet())
import random


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


# print(flip())


# param
# def say_hello(person, message):
#     print(f"{message}, {person.upper()}")
#     print("Hello World")
#     print("Hello World")
#     print("Hello World")


# user_name = input("Please enter a name: ")
# user_message = input("Please enter the message: ")

# say_hello("john", "Namaste")
# say_hello(user_name, user_message)  # arg


# def odd_even(num):
#     if num % 2 == 0:
#         return f"{num} - Even"
#     else:
#         return f"{num} - Odd"


# random_num = random.randint(0, 10)

# print(odd_even(random_num))


# def raise_to(num, pow=1):
#     return num ** pow


# print(raise_to(10, 3))


# # Accepts a list
# def sum_odd_nums(numbers):
#     total = 0
#     for num in numbers:
#         if num % 2 == 1:
#             total += num
#     return total


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


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


# def sub(num1, num2):
#     return num1 - num2


# def div(num1, num2):
#     return num1 / num2


# # MAIN FUNCTION
# def math(num1, num2, func=add):
#     return func(num1, num2)


# def print_nums(num1, num2):
#     return f"{num1} is cool! {num2} is not!"


# # print(add(10, 20))
# # print(math(10, 20, add))
# # print(math(10, 20, sub))
# # print(math(10, 20, div))

# print(math(100, 55, print_nums))

# print(math(10, 3))


# message = "Hello Universe"


# def full_name(first, last):
#     message = "Hello World"
#     print(message)
#     return "Your name is " + first + " " + last + "."


# print(message)


# # print(full_name("Gagan", "Tesla"))
# # print(full_name("Itachi", "Uchiha"))

# print(full_name(last="Tesla", first="Gagan"))


# total = 1000

# print("Original total", total)


# def static():
#     global total
#     # total = -500
#     total += 1000
#     return total


# print("Returned total", static())

# print("Original Total", total)


# def outer():
#     count = 0
#     while count < 10:
#         print(count)
#         count++
#     return inner()


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


# A simple function that returns the string hello
def say_hello():
    """A simple function that returns the string hello"""
    return "Hello!"


print(say_hello.__doc__)
1. Write a function named get_day. This function should take in one parameter, a number between 1-7 and return the day of the week (1 is Monday,  2 is Sunday and so on). If the number is less than 1 or greater than 7, then it should return None.


2. Write a function named last_item. This function should take in one parameter which should be a list and it should return the last value in the list. It should return None if the list is empty.


3. Write a function called letter_count. This function takes in two parameters. The first parameter should be a word and the second should be a letter. The function returns the number of times that letter appears in the word. The function should be case insensitive (does not matter if the input is lowercase or uppercase). If the letter is not found in the word, the function should return 0.

letter_count("HelLo World", "l") # 3


4. Write a function called multi_letter_count. This function takes in one parameter (a string) and returns a dictionary with the keys being the letters and the values being the count of the letter. Use a diction

multi_letter_count("programmer") # {'p': 1, 'r': 3, 'o': 1, 'g': 1, 'a': 1, 'm': 2, 'e': 1}


5. Write a function called palindrome. A Palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. This function should take in one parameter and returns True or False depending on whether it is a palindrome. (Ignore case sensitivity)
# def last_item(lst):
#     return lst[-1]


# last_item([1, 2, 43, 2323, 32, 32, 23, -3244])

# last_item(["hello", "hi", "howdy"])


# name = "john"

# name.upper().lower()


# def get_day(num):
#     days = [
#         "monday",
#         "tuesday",
#         "wednesday",
#         "thursday",
#         "friday",
#         "saturday",
#         "sunday",
#     ]

#     if num >= 1 and num <= 7:
#         return days[num - 1]
#     else:
#         return None


# print(get_day(6))


# def palindrome(word):
#     # word_lst = list(word)
#     # word_lst.reverse()
#     # word_joined = "".join(word_lst)

#     return word == word[::-1]

#     # if word == word_joined:
#     #     return True
#     # else:
#     #     return False


# print(palindrome("wow"))
# def get_day(num):
#     days = [
#         "monday",
#         "tuesday",
#         "wednesday",
#         "thursday",
#         "friday",
#         "saturday",
#         "sunday",
#     ]
#     if num >= 1 and num <= 7:
#         return days[num - 1]
#     else:
#         return None


# get_day(4)


# def sum_all_nums(*nums):
#     # print(args)
#     total = 0
#     for num in nums:
#         total += num
#     return total


# print(sum_all_nums(10, 5, 100, 6, 67, 43))


# def sum_all_nums(name, age, *nums):
#     # print(name)
#     # print(age)
#     # print(nums)
#     total = 0
#     for num in nums:
#         total += num
#     return f"{name} your age is {age} and you would probably live for {total} years"


# # print(sum_all_nums(10, 5, 100, 6, 67, 43))
# print(sum_all_nums("John", 25, 100, 6, 67, 43))


# def print_name(first, last):
#     print(f"{first} {last}")


# print_name(last="matsumoto", first="yukihiro")


# def user_details(**kwargs):
#     # print(kwargs)
#     for key, value in kwargs.items():
#         print(f"{key} --- {value}")


# user_details(name="Guido", employer="Microsoft", expertise="Python", fav_board="x86")


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


# print(show_info(1, 2, 3, first_name="John", last_name="Doe"))

# prices = [10, 4, 34, 4, 32, 2]


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


# add_all_values(*prices)

# " ".join([name.capitalize() for name in k.split("_")])


# def user_details(**kwargs):
#     for key, value in kwargs.items():
#         print(f"{key} : {value}")


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


# # user1 = {"first_name": "John", "last_name": "Doe", "age": 25}

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


# # user_details(**user1)
# say_name(**user1)

# # say_name(first="John", last="Doe")


# def create_acc(first, last, age, pan_no=None, acc_no=None):
#     print(first, last, age, pan_no, acc_no)


# user_details = [
#     {"first": "John", "last": "Doe", "age": 25, "pan_no": "A2DS2323"},
#     {"first": "Jane", "last": "Doe", "age": 29},
#     {"first": "Peter", "last": "Parker", "age": 30},
# ]

# for data in user_details:
#     create_acc(**data)


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

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

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


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


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


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


# capitalizer = lambda k: " ".join([name.capitalize() for name in k.split("_")])

# print(capitalizer("first_name"))

# print(math(10, 10, lambda x, y: x * y))
# print(math(10, 10, multiply))


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


# nums = [1, 2, 3, 4, 5, 6, 7, 8]
# names = ["john doe", "jane doe", "jack doe", "clark kent"]
# double = map(lambda num: num ** 5, nums)

# names_upper = map(lambda name: name.upper(), names)


# # print([num for num in nums if num > 3])

# # print(list(double))

# # print(tuple(names_upper))


# # print("".join(list(map(lambda word: word * 3, "HELLO"))))


# names = ["john", "jack", "brad", "leo", "kamal", "mukesh"]

# print(list(filter(lambda name: name.startswith("k"), names)))
# print(list(filter(lambda name: name[0] == "k", names)))


names = ["John", "Jack", "James", "Desmond", "Charlie", "Jacob"]
# mapobject = ("john", "jack")

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

print(list(result))
# remove_negatives(lst) # [1,3,-2,-6,-4,2] -> [1,3,2]
# negate(lst) # [1,2,3] -> [0,1,2]

# import random


# def remove_negatives(lst):
#     return list(filter(lambda num: num > 0, lst))


# # print(random.randint(0, 100))


# print(remove_negatives([1, -2, 3, -6]))
# print(remove_negatives([-1, 3, -6]))

# {"i": 1, "want": 1}


# line = "I want to be a pirate king. Hello world, hello universe, hello galaxy."


# def count_words(sentence):
#     sentence_list = sentence.split(" ")
#     sentence_list = [
#         word.lower().replace(",", "").replace(".", "") for word in sentence_list
#     ]
#     return {word: sentence_list.count(word) for word in sentence_list}


# print(count_words(line))


# users = [{"name": "john"}, {"name": "jack"}, {}, {"name": "jane"}]

# if all(users):
#     print("DO SOME USER LOGIC")
# else:
#     print("SOMETHING WENT WRONG")


# >>> [num for num in [2,34,5,6,2] if num % 2 == 0]
# [2, 34, 6, 2]
# >>>
# >>> all([num for num in [2,34,5,6,2] if num % 2 == 0])
# True
# >>>
# >>> all([num*0 for num in [2,34,5,6,2] if num % 2 == 0])
# False
# >>> [num*0 for num in [2,34,5,6,2] if num % 2 == 0]
# [0, 0, 0, 0]
# >>>
# >>>
# >>>
# >>> any([0,0,0,1])
# True
# >>> any([0,0,0,""])
# False
# >>>
# >>> any([0,0,-2,""])
# True
# >>>
# >>> any([0,0,[],""])
# False
# >>> any([0,0,[]," "])
# True
# >>>
# >>> any([0,0,[]," "])
# True
# >>>
# >>>
# >>>
# >>> [val for val in [1,2,3] if val > 5]
# []
# >>>
# >>>


# print(sorted([12, 3, 7, 3, 9]))
# print(sorted((12, 3, 7, 3, 9)))

# strings = ["hello", "Hello", "world", "a", "A", "Universe", "python"]
# lower_strings = [word.lower() for word in strings]

# print(sorted(lower_strings))


# my_list = [12, 3, 7, 3, 9]

# for num in reversed(my_list):
#     print(num)


# my_dict = {"a": 1, "b": 2, "c": 3}

# for item in my_dict:
#     print(item)


# students = ["jack", "jane", "john", "jill", "jack", "josh", "jason"]
# marks = [45, 50, 10, 12, -2, 32, 28, 34, 23, 45, 3, 34, 21]
# grades = ["A", "A+", "F", "F", "F-", "B+", "B"]

# # report = zip(students, marks)
# report = zip(students, marks, grades)

# print(list(report))


vm_ips = [81, 82, 83, 84, 85, 86]
server_ids = [228, 229, 230]

print(list(zip(vm_ips, server_ids)))


mapped_list = [(81, 228), (82, 229), (83, 229)]

for item in mapped_list:
    item[0]


# name = "John Doe"
# name.upper() # 'JOHN DOE'
# name.lower() # 'john doe'
# name.capitalize() # 'John doe'
# name.swapcase() # 'jOHN dOE'

# name = "    john doe         "
# name.strip() # 'john doe'
# name.rstrip()
# name.lstrip()

# name.split() # LATER


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

# name.replace('John', 'Jack')
# # 'Jack Doe'

# name.startswith('j') # False
# name.endswith('e') # True
# name.count('e') # 1

# "".join() # LATER