Menu

Python Evening 27-06-2022

Python Evening 27-06-2022

Scratchpad #1

score = 10

score + 5

high_score = score * 2

print(high_score)

Scratchpad #3

# print("Amount of US dollars you want to convert?")
# usd = input()

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

# print(input("Hello World "))

# print(int(input("Amount of US dollars you want to convert? ")) * str(10))

# city = input("Which city do you live in? ")

# if city == "delhi":
#     print("You are not allowed anywhere")
# elif city == "mumbai":
#     print("Please come")
# elif city == "pune":
#     print("Good come in")
# else:
#     print("Sure come in")

# username = ""

# if username:
#     print("Here is your content")
# else:
#     print("You have to login")

# age = 3100

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

age = 31

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

Scratchpad #4

# age = 1
# city = "delhi"

# if age > 18:
#     if city == "delhi":
#         print("You aren't allowed")
#     else:
#         print("You can enter")
# else:
#     print("You are not allowed")

# player1 = input("Enter player 1's choice: ")
# player2 = input("Enter player 2'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")

# for something in "rstforum":
#     print(something, "Hello World")

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

# for item in "some text":
#     print(item)
#     print("Hello")

# for number in range(50, 100):
#     print(number)

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

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

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

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

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

while password != "test":
    print("Incorrect password")
    password = input("Please enter your password again: ")

print("Welcome")

Scratchpad #5

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

# while password != "test":
#     print("Incorrect password")
#     password = input("Please enter your password again: ")

# print("Welcome")

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

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

# num = 1
# while num < 10:
#     print(num)
#     # num = num + 1
#     num += 1

# name = "john doe"

# for char in name:
#     print(char)

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

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

# while password != "test":
#     print("Incorrect password")
#     password = input("Please enter your password again: ")
#     if password == 'quit':
#         break

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

# while True:
#     print("Incorrect password")
#     password = input("Please enter your password again: ")
#     if password == 'test':
#         break

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

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

# while True:
#     print("Incorrect password")
#     password = input("Please enter your password again: ")
#     if password == 'test':
#         break

# while True:
#     player1 = input("Enter player 1's choice: ")
#     player2 = input("Enter player 2'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")

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

# tasks = "practice python||pay bills||another task"

# name1 = "john"
# name2 = "jane"

# names = [name1, "jack", name2, 100, "hello world"]

# print(names)

nums = [1, 2, 5, 20, [1, 2, 3]]

# print(nums[4])

print(len(nums))

Scratchpad #6

# nums = list(range(100))

# for n in nums:
#     print(n)

nums = ["jane", "john", "jack", "jill", "jeet"]

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

Scratchpad #7

# names = ['tijlad', 'daljit', 'amit', 'sahil', 'sarvesh', 'abhay']

# upper_names = []

# for name in names:
#     upper_names.append(name.upper())

# print(upper_names)

# upper_names2 = [name.upper() for name in names]

# print(upper_names2)

# >>> [name[1:3] for name in names]
# ['ij', 'al', 'mi', 'ah', 'ar', 'bh']
# >>> names
# ['tijlad', 'daljit', 'amit', 'sahil', 'sarvesh', 'abhay']
# >>>
# >>>
# >>>
# >>> [name for name in names]
# ['tijlad', 'daljit', 'amit', 'sahil', 'sarvesh', 'abhay']
# >>> [name[::-1] for name in names]
# ['daljit', 'tijlad', 'tima', 'lihas', 'hsevras', 'yahba']
# >>>
# >>> "john"[1:3]
# 'oh'
# >>>
# >>>
# >>>
# >>>
# >>> [10 for name in names]
# [10, 10, 10, 10, 10, 10]
# >>> [ for name in names]
# KeyboardInterrupt
# >>>
# >>>
# >>>
# >>> names
# ['tijlad', 'daljit', 'amit', 'sahil', 'sarvesh', 'abhay']
# >>>
# >>> [len(name) for name in names]
# [6, 6, 4, 5, 7, 5]
# >>> [len(name) ** 2 for name in names]
# [36, 36, 16, 25, 49, 25]
# >>>
# >>>
# >>>
# >>>
# >>> name
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# NameError: name 'name' is not defined. Did you mean: 'names'?
# >>>
# >>> names[0]
# 'tijlad'
# >>> names[0][1:]
# 'ijlad'
# >>>
# >>> names[0][1:4]
# 'ijl'
# >>>
# >>> names[0][::]
# 'tijlad'
# >>> names[0][::-1]
# 'daljit'
# >>> names
# ['tijlad', 'daljit', 'amit', 'sahil', 'sarvesh', 'abhay']
# >>>
# >>>
# >>> numbers = [1, 2, 3, 4, 5]
# >>>
# >>> numbers
# [1, 2, 3, 4, 5]
# >>> [num * 2 for num in numbers]
# [2, 4, 6, 8, 10]
# >>>
# >>> [num / 2 for num in numbers]
# [0.5, 1.0, 1.5, 2.0, 2.5]
# >>>

Scratchpad #8

# prod1 = ["iPhone", "Apple", 100000, 500, "Some desc", True]
# prod2 = ["Note 7", "Mi", 50000, 15000, "Some desc", False]

# print(f"Name: {prod1[0]}\nBrand: {prod1[1]}\nPrice: {prod1[2]}")
# print(f"Name: {prod2[0]}\nBrand: {prod2[1]}\nPrice: {prod2[2]}")

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

# print(nums[1][-1])

# [[[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]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]

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

# for num in nums:
#     for n in num:
#         print("inner loop", n)

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

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

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

total = 0

i = 0
while i < len(nums):
    j = 0
    while j < len(nums[i]):
        total = total + nums[i][j]
        j += 1
    i += 1

print(total)

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

nums = [
    [[1, 2, 3, 4], [1, 2, 3], [1, 2, 3]],
    [[1, 2, 3], [1, 2, 3, 73], [1, 32, 3, 45]],
    [[1, 2, 3], [1], [1, 2, 3]],
]

# task 1 = total = ?
# task 2 = total = even numbers

Scratchpad #9

# i = 0

# while i < 10:
#     j = 0
#     print("I am here in i")
#     while j < 10:
#         print("I am here in j")
#         print(j)
#         j += 1
#     print(i)
#     i += 1

# # print("Hello World")

# product1 = [
#     "iPhone", "Apple", 100000, 100, True, "Some description", "Some other text"
# ]

# print(product1[1])

# product1 = {
#     "description": "Some description...",
#     "price": 100000,
#     "in_stock": 100,
#     "name": "iPhone",
#     "discount_available": True,
#     "brand": "Apple",
#     100: "Something"
# }

# print(product1["brand"])
# print(product1[100])

# song = {
#     "name": "saap",
#     "artist": ["john doe", "jane doe"],
#     "album": "pythonic",
#     "track_time": 3.42,
#     "downloadable": True,
#     "metadata": {
#         "youtube_link": "https://....",
#         "spotify_link": "https://....",
#     }
# }
# # print(song["track_time"])
# # print(song["artist"][1])
# print(song)

# # print(song["artist"][0])
# # print(song["metadata"]["spotify_link"])

# my_playlist = [
#     {
#         "name": "saap",
#         "artist": ["john doe", "jane doe"],
#         "album": "pythonic",
#         "track_time": 3.42,
#         "downloadable": True,
#         "metadata": {
#             "youtube_link": "https://....",
#             "spotify_link": "https://....",
#         }
#     },
#     {
#         "name": "naag",
#         "artist": ["john doe", "jane doe"],
#         "album": "pythonic",
#         "track_time": 3.42,
#         "downloadable": True,
#         "metadata": {
#             "youtube_link": "https://....",
#             "spotify_link": "https://....",
#         }
#     },
#     {
#         "name": "naagin",
#         "artist": ["john doe", "jane doe"],
#         "album": "pythonic",
#         "track_time": 3.42,
#         "downloadable": True,
#         "metadata": {
#             "youtube_link": "https://....",
#             "spotify_link": "https://....",
#         }
#     },
# ]

# profile = {"name": "John", "age": 20}
# profile2 = dict(name="John", age=20)

# print(profile)
# print(profile2)

# prod_name = input("Apne product ka naam dal: ")

# product = {"name": prod_name}

# print(product)

# profile = {"name": "John", "age": 20}

# print(profile["namee"])

product1 = {
    "description": "Some description...",
    "price": 100000,
    "in_stock": 100,
    "name": "iPhone",
    "discount_available": True,
}
# print(product1["description"])

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

# for item in product1.values():
#     print(item)

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

# for k, v in product1.items():
#     print(k, v)

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

Scratchpad #10

profile = {"name": "John Doe", "age": 20, "profession": "Programmer"}

print(profile)

Scratchpad #11

# locations = {
#     "name": "john doe",
#     10: "hello",
#     (1.231423, 0.123123): "Mumbai office",
#     (1.221223, 0.131453): "Pune office",
# }

# print(locations["name"])
# print(locations[10])
# print(locations[(1.231423, 0.123123)])

# names = ("Corey", "Maynard", "Morrisey", "Thom")

# # for name in names:
# #     print(name)

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

users1 = {"sahil", "nikhil", "savio", "amit", "onkar", "sherwin", "aayush"}
users2 = {
    "priyanka", "nikhil", "savio", "gokul", "shrushti", "sarthik", "aishwarya",
    "onkar"
}

# nums1 = {12, 324, 4562, 23, 12, 1, 23, 45}
# nums2 = {12, -1, 3, 23, 234, 1, 23, 45.23}
print(users1)
print(users2)

print("\n\n")

print("Union")
print(users1 | users2)  # union operator
# print(nums1 | nums2)

print("intersection operator")
print(users1 & users2)  # intersection operator

print("symmetric difference")
print(users1 ^ users2)  # symmetric difference

Scratchpad #12

# print("Hello World")

# # DRY - Don't repeat yourself
# # WET

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

# greet()
# greet()

from random import random

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


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


# print(flip_coin())

# result = flip_coin()

# print(f"The result is {result}")

# def best_of_3():
#     flip_coin()
#     flip_coin()
#     flip_coin()

# best_of_3()

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

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

# def flip_multiple(times):
#     for num in range(times):
#         print(flip_coin())

# user_input = input("Number of times you flip the coin: ")
# flip_multiple(int(user_input))

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

# result = add(10, 3)

# print(f"The result of your calculation was {result}")

# def sum_odd_nums(nums):
#     total = 0

#     for num in nums:
#         if num % 2 != 0:
#             total += num

#     return total

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

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

# print(is_odd_num(4))


def expo(num=1, power=1):
    return num**power


print(expo())

Scratchpad #13

# user_input = input("Please enter: ")
# print(type(user_input))
# print(user_input)

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

# print(add(10, 4))

# def greet(message="Hi", name="Unknown"):
#     return f"{message}, {name}"

# print(greet(name="John"))

# full_name = "john doe"

# full_name = "jane doe"

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

# print(full_name)

# greet()

# total = 0

# def test():
#     global total
#     total += 10
#     print(total)

# test()

# total = 0

# def test(val):
#     return val + 10

# total = test(total)

# print(total)

# def outer():
#     """
#     This function does something
#     """
#     count = 100

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

#     return inner()

# print(outer.__doc__)
# # print(type.__doc__)

# def test():
#     total = 0
#     for num in range(1, 10):
#         total += num
#     return total

# print(test())

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

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

# def names(**vals):
#     for k, v in vals.items():
#         print(f"{k} - {v}")

# names(name="John", age=20, job="programmer", working=False)


def show_info(a, b, *args, role="moderator", **kwargs):
    print(a, b, args, role, kwargs)


show_info(10, 20, 30, 40, 50, role="programmer", hello="world", name="john")

Scratchpad #14

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

# my_values = [10, 4, 5, 2, 1, 23]

# print(add(*my_values))

# def greet(first_name, last_name):
#     print(f"Hello my name is {first_name} {last_name}")

# # info = ["john", "doe"]
# # greet(*info)

# info = {"first_name": "John", "last_name": "Doe"}

# greet(**info)

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

# add = lambda a, b: a + b

# print(add(10, 5))

# def math(a, b, fn1, fn2):
#     return [fn1(a, b), fn2(a, b)]
# print(math(10, 5, sub, add))

# def math(a, b, fn1, fn2):
#     return fn1(a, b)

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

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

# print(math(10, 4.5, lambda a, b: a + b, lambda a, b: a - b))
# print(math(10, 4, lambda a, b: a - b))
# print(math(10, 4, lambda a, b: a * b))

add = lambda a, b: print(a + b)

print(add(10, 5))

Scratchpad #15

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

# add = lambda a, b: a + b

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

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

# def num_double(num):
#     return num * 2

# doubles = map(lambda num: num * 2, nums)
# # doubles = map(num_double, nums)

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

# for num in doubles:
#     print(num)

# names = ["john", "john", "jill gupta", "jack gupta", "sarvesh smith"]

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

# print(list(uppercased_names))

# for name in uppercased_names:
#     print(name)

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

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

# print(list(odds))

# names = ["ohjn", "john", "jill gupta", "jack gupta", "sarvesh smith"]

# result = filter(lambda name: name[0] != 'j', names)

# print(list(result))

# products = [
#     {
#         "name": "iPhone",
#         "brand": "Apple",
#         "price": 1200
#     },
#     {
#         "name": "Nord",
#         "brand": "One Plus",
#         "price": 800
#     },
#     {
#         "name": "Galaxy S22",
#         "brand": "Samsung",
#         "price": 1400
#     },
# ]

# products = list(filter(lambda product: product["price"] < 1000, products))
# print(products)

# # print(products[2]["price"])

# # products = list(
# #     map(
# #         lambda product: {
# #             "name": product["name"],
# #             "brand": product["brand"],
# #             "price": product["price"] * 82
# #         }, products))

# # print(products)

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

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

# print(list(result))

# names = [None, False, ' ']

# # print(all(names))
# print(any(names))

numbers = {2, 3, 7, 3, 9, 1}

print(sorted(numbers))

Scratchpad #16

# print(max(10, 20, 0, -3, 21, 233, 23))
# print(min(10, 20, 0, -3, 21, 233, 23))

# result = reversed("hello")
# print("".join(result))

# result = reversed([10, 20, 0, -3, 21, 233, 23])
# print(list(result))

# print(abs(-5))
# print(abs(5))

# print(sum(range(10), 10))
# print(sum([1, 2, 3, 4], 5))

# products = [
#     {
#         "name": "iPhone",
#         "brand": "Apple",
#         "price": 1200
#     },
#     {
#         "name": "Nord",
#         "brand": "One Plus",
#         "price": 800
#     },
#     {
#         "name": "Galaxy S22",
#         "brand": "Samsung",
#         "price": 1400
#     },
# ]

# prices = list(map(lambda product: product["price"], products))
# print(sum(prices))

# print(round(10.7898, 2))
# result = zip([1, 2, 3, 4, "hello"], ["john", "jane", 10, 100, "jack", True],
#              [1, 2])

# print(list(result))

# def my_func:
#     print("hello world")

# print(hello)

# def greet(name):
#     if type(name) != str:
#         # raise TypeError("Please enter a string value")
#         raise Exception("Please enter a string value")
#     return f"Hello, {name}"

# print(greet(100))


def contains_john(*names):
    return "john" in names


print(contains_john("jack", "jill"))

# rahul@rstforum.co.in

Scratchpad #17

# try:
#     num = int(input("Please enter a number: "))
#     print(num)
# except ValueError as err:
#     print(err)

# print("Hello World")

# def divide(a, b):
#     try:
#         result = a / b
#         print(result)
#     except (TypeError, ZeroDivisionError) as err:
#         print(err)

# def divide(a, b):
#     try:
#         result = a / b
#         print(result)
#     except Exception as err:
#         print(err)

# def divide(a, b):
#     try:
#         result = a / b
#     except Exception as err:
#         print(err)
#     else:
#         print(result)
#     finally:
#         print("******")
#         print("I will always run")
#         print("******")

# divide(1, 0)
# divide(1, "hello")
# divide(1, 3)

# print("Hello World")

# import random

# print(random.random())

# import random as r

# random = "Hello World"

# print(random)
# print(r.random())

# # import random
# from random import randint as ri, random as r, choice as ch
# # from random import *

# print(ri(10, 100))
# print(ch())

# import mymod

# print(mymod.add(10, 5))

from mymod import sub

print(sub(10, 5))

Scratchpad #18

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

# def list_manipulation(data, command, location, value=0):
#     # logic

# list_manipulation(nums, "remove", "end")  # 5
# list_manipulation(nums, "remove", "beginning")  # 1
# list_manipulation(nums, "add", "beginning", 100)  # [100, 2, 3, 4]
# list_manipulation(nums, "add", "end", 100)  # [100, 2, 3, 4, 100]

# print(nums)  # [1,2,3,4]
# print(nums)  # [2,3,4]

Scratchpad #19

# from unicodedata import name

# "john".upper()

# class User:
#     # constructor
#     def __init__(self, fn, ln, a):
#         self.first_name = fn
#         self.last_name = ln
#         self.age = a

# user1 = User("john", "doe", 20)
# user2 = User("jane", "smith", 30)

# print(user1.first_name)
# print(user2.first_name)


class Bike:

    def __init__(self, model, make, color, type):
        # attributes
        self.model = model
        self.make = make
        self.color = color
        self.type = type


dhanno = Bike("Standard 500", "Royal Enfield", "black", "cruiser")
sakharam = Bike("RX-100", "Yamaha", "blue", "cafe racer")

print(dhanno.type)
print(sakharam.color)

Scratchpad #20

# class Book:

#     def __init__(self, name, no_of_pages, cover, category, author, price):
#         self.name = name
#         self.no_of_pages = no_of_pages
#         self.cover = cover
#         self.category = category
#         self.author = author
#         self.price = price

# book1 = Book("Rich dad poor dad", 300, "softcover", "self-help",
#              "Robert Kiyosaki", 100)

# print(book1)


class User:
    total_users = 0
    active_users = 0

    def __init__(self, name, age, profession, country):
        self.name = name
        self._age = age  # private attribute
        self.profession = profession
        self.country = country
        self.email = None
        User.total_users += 1

    def greet(self):
        return f"Hello, my name is {self.name} and I am {self._age} years old"

    def set_email(self, new_email):
        self.email = new_email
        print("You email address was updated")

    def login(self):
        User.active_users += 1
        print(f"{self.name} has now logged in")

    def logout(self):
        User.active_users -= 1
        print(f"{self.name} has now logged out")


user1 = User("Jack Smith", 20, "Programmer", "India")
user2 = User("Jane Smith", 22, "Programmer", "UK")

user1.login()
user2.login()
user1.logout()
user2.login()
user2.login()

print(User.active_users)

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

# john = User("John Doe", 20, "Python Developer", "India")
# jane = User("Jane Smith", 26, "Developer", "Bangladesh")

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

# john.set_email("john@yahoo.co.in")
# print(john.email)

# john._age = 129
# print(john._age)

# john.email = "john@gmail.com"
# jane.profession = "System Administrator"

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