Lab guidePython

Python_Sunday_17092023

Last updated 29 November 2023

Python Sunday 17092023

Scratchpad #2 and #3

# # name = 'john'

# # # name = ['j', 'o', 'h', 'n']
# # # name = {0: 'j', 1: 'o', 2: 'h', 3: 'n'}
# # #

# name = "John Doe"

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

# print("Enter your amount in INR")
# amount_in_inr = int(input())

# amount_in_inr = int(amount_in_inr)
# print(type(amount_in_inr))

# print("Enter your amount in USD")
# amount_in_usd = float(input("Enter your amount in USD: "))

# amount_in_inr = amount_in_usd * 82
# print(f"{amount_in_usd} USD is {amount_in_inr} INR")

# age = 15

# if age > 18:  # code block
#     print("Welcome")
#     print("Welcome")
#     print("Welcome")

# print("This is not inside the block")

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

# if city == "Mumbai":
#     print("Hello")
#     print("Hello")
#     print("Hello")
#     print("Hello")
#     print("Hello")
# elif city == "Pune":
#     print("Hello again")
# elif city == "Delhi":
#     print("Goodbye")
# elif city == "Palghar":
#     print("Hello again")
# else:
#     print("Invalid city")

# 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 = "john"

# # if logged_in_user == None:
# #     print("Sorry, you have to log in to view this content")
# # else:
# #     print("Here is the content")

# if logged_in_user:  # bool(logged_in_user)
#     print("Here is the content")
# else:
#     print("Sorry, you have to log in to view this content")

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("Welcome")
#     else:
#         print("You are not welcome")
# else:
#     print("Please enter your age!")

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

# # if player1 == 'rock':
# #     if player2 == 'scissor':
# #         print('Player 1 wins')
# #     elif

# 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")

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

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

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

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

# for num in range(0, 100, 5):
#     print(num)

# for num in range(10, 0, -2):
#     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("Please enter your password: ")

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

# BACKEND => SERVER (WEB APP)
# FRONTEND => CLIENT (BROWSER)

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

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

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

# while password != 'helloworld':
#     if password == 'quit':
#         break
#     print("Incorrect password! Please try again!")
#     password = input("Please enter your 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 == '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")

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

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

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

Scratchpad #4 and #5

# tasks = "my first task||my second task||"

# tasks = ['My first task', 'This is something else', 'hello', 'World']
# print(tasks[5])

# print("Hello World")

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

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

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

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

doubles = [n * 2 for n in nums]  # [2, 4]

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

print(doubles)

names = ["John", "Jane", "Jack", "Jill"]

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)


product = [1, 'Pixel 8 Pro', 'Google', 'Some desc...', 500, 100000, True]

# product[1], product[2]

product = {
    "index": 1,
    "price": 100000,
    "name": "Pixel 8 Pro",
    "brand": "Google",
    "in_stock": 500,
    "description": "Some desc....",
    "discounted": True,
}

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

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

Scratchpad #6

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

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

# from random import random

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

# for _ in range(3):
#     flip_coin()

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

# result = greet()
# print(result)

# def greet(name: str, greeting: str) -> str:
#     return f"{greeting} {name}, how are you?"

# greet()

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

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

# print(add(10, 4))

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

# print(add([1, 2, 3, 2.3]))

# def sum_odd_nums(numbers):
#     total = 0
#     for num in numbers:
#         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 == 1:
#         return True
#     return False

# print(is_odd_num(5))

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

# print(exponent())

# def greet(name, greeting="Hi"):
#     return f"{greeting} {name}, how are you?"

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

# num = 1

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

# hello = add

# print(hello(10, 2))

# print(add(10, 2))

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

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

# math = [add, sub]

# print(math[1](10, 2))

# 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, 5))

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

# print(greet(message="Hello", name="Jane"))

# name = "John Doe"

# def greet():
#     name = "Jane Smith"
#     print(name)

# greet()
# # print(name)

# total = 0

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

# dummy()
# print(total)

# PI = 3.14

# def outer():
#     total = 0

#     def inner():
#         nonlocal total
#         total += 5
#         print(total)

#     inner()

# outer()


def greet(name, message):
    """Function that greets a user
    @param name {str}
    @message message {str}
    @returns {str}
    """
    return f"{message}, {name}"


print(help(greet))

# print(greet("John", "Hello"))
# print(greet.__doc__)
# print(print.__doc__, end="\n")

# print("Hello World", end="")
# print("Goodbye World")

Scratchpad 4 - 8

# tasks = "my first task||my second task||"

# tasks = ['My first task', 'This is something else', 'hello', 'World']
# print(tasks[5])

# print("Hello World")

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

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

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

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

doubles = [n * 2 for n in nums]  # [2, 4]

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

print(doubles)

names = ["John", "Jane", "Jack", "Jill"]

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)


product = [1, 'Pixel 8 Pro', 'Google', 'Some desc...', 500, 100000, True]

# product[1], product[2]

product = {
    "index": 1,
    "price": 100000,
    "name": "Pixel 8 Pro",
    "brand": "Google",
    "in_stock": 500,
    "description": "Some desc....",
    "discounted": True,
}

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

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


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

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

# from random import random

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

# for _ in range(3):
#     flip_coin()

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

# result = greet()
# print(result)

# def greet(name: str, greeting: str) -> str:
#     return f"{greeting} {name}, how are you?"

# greet()

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

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

# print(add(10, 4))

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

# print(add([1, 2, 3, 2.3]))

# def sum_odd_nums(numbers):
#     total = 0
#     for num in numbers:
#         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 == 1:
#         return True
#     return False

# print(is_odd_num(5))

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

# print(exponent())

# def greet(name, greeting="Hi"):
#     return f"{greeting} {name}, how are you?"

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

# num = 1

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

# hello = add

# print(hello(10, 2))

# print(add(10, 2))

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

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

# math = [add, sub]

# print(math[1](10, 2))

# 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, 5))

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

# print(greet(message="Hello", name="Jane"))

# name = "John Doe"

# def greet():
#     name = "Jane Smith"
#     print(name)

# greet()
# # print(name)

# total = 0

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

# dummy()
# print(total)

# PI = 3.14

# def outer():
#     total = 0

#     def inner():
#         nonlocal total
#         total += 5
#         print(total)

#     inner()

# outer()


def greet(name, message):
    """Function that greets a user
    @param name {str}
    @message message {str}
    @returns {str}
    """
    return f"{message}, {name}"


print(help(greet))

# print(greet("John", "Hello"))
# print(greet.__doc__)
# print(print.__doc__, end="\n")

# print("Hello World", end="")
# print("Goodbye World")


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

# print(add(10, 5))


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


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

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

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

# def dummy(a, b, c, *nums, role="administrator", **data):
#     print(a, b, c, nums, role, data)


# dummy(10, 20, 30, 40, 50, 60, 70, first_name="Jane", last_name="Doe", role="mod")


# 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}.")


# data = {"first": "Jane", "last": "Smith"}

# say_name(**data)

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

# a = 10
# hello = add

# print(hello(10, 2))


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

# sub = lambda a, b: a - b

# print(sub(10, 5))


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

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

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

# math = [lambda a, b: a + b, lambda a, b: a - b, lambda a, b: a * b]

# print(math[1](10, 4))


# nums = [1,2,3,4,5]
# # doubles = [num * 2 for num in nums]
# doubles = map(lambda num: num * 2, nums)

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

# print(tuple(doubles))

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


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

result = map(lambda name: name.upper(), filter(lambda name: len(name) <= 4, names))

print(list(result))


# import random
# import pprint

# 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:
#     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")


def greet(name, message, color):
    colors = ("red", "yellow", "green", "blue", "purple")

    if type(name) != str:
        raise TypeError("Name has to be a string")
    if type(message) != str:
        raise TypeError("Message has to a string")
    if type(color) != str:
        raise TypeError("Color has to a string")
    if color not in colors:
        raise ValueError("Invalid color")

    return f"{message}, {name} - in color {color}"


# greet("John Doe", "Hello", "maroon")

# try:
#     result = greet("John Doe", 10, "yellow")
#     print(result)
# except:
#     print("Something went wrong")
# except ValueError:
#     print("Something went wrong")
# except (ValueError, TypeError):
#     print("Something went wrong")
# except TypeError as err:
#     print(err)
# except (ValueError, TypeError) as err:
#     print(err)
# except Exception as err:
#     print(err)


# try:
#     result = greet("John Doe", "Hi", "yellow")
# except Exception as err:
#     print(err)
# else:
#     print(result)
# finally:
#     print("This will always run!")

# print("Program completed")


# import getpass


# password = getpass.getpass()
# print(password)

# import random as r
from random import randint, random, shuffle, choice

# from random import *


# def random():
#     print("Something")


random()
print(random())
print(randint(10, 100))
Learn this on the racks

Reading it is one thing. Configuring it is another.

Our batches run labs like this one end to end on real kit, in the Mumbai classroom or live online, taught by practicing engineers.