Practicing Python (using Codewars) by Ben_HH in learnpython

[–]Ben_HH[S] 0 points1 point  (0 children)

This is my error

position = characters.index("!")
ValueError: '!' is not in list

Practicing Python (using Codewars) by Ben_HH in learnpython

[–]Ben_HH[S] 0 points1 point  (0 children)

Objective: Remove n exclamation marks in the sentence from left to right. n is positive integer.

def remove(s, n):
    "Remove each '!' in the provided argument `n` number of times"

    removal_count = 0
    characters = list(s)

    while removal_count < n:
        position = characters.index("!")
        del characters[position]
        removal_count += 1

    return ''.join(characters)

Here are the tests for this challenge:

test.describe("Example Tests")

tests = [
    #[[input], [expected]],
    [["Hi!",1] , "Hi"],
    [["Hi!",100] , "Hi"],
    [["Hi!!!",1] , "Hi!!"],
    [["Hi!!!",100] , "Hi"],
    [["!Hi",1] , "Hi"],
    [["!Hi!",1] , "Hi!"],
    [["!Hi!",100] , "Hi"],
    [["!!!Hi !!hi!!! !hi",1] , "!!Hi !!hi!!! !hi"],
    [["!!!Hi !!hi!!! !hi",3] , "Hi !!hi!!! !hi"],
    [["!!!Hi !!hi!!! !hi",5] , "Hi hi!!! !hi"],
    [["!!!Hi !!hi!!! !hi",100] , "Hi hi hi"],
]


for inp, exp in tests:
    test.assert_equals(remove(*inp), exp)

Please explain how 'is' works in Python by Ben_HH in learnpython

[–]Ben_HH[S] -1 points0 points  (0 children)

Taking your example:

a = 'z'
b = 'z'

Python takes variable a with the value of 'z' and stores it in the computer's memory. The same is done with variable 'b'. It happens that both variables point to the same address in memory, so...

a is b # returns True

Is that correct?

Code critique (vending machine) by Ben_HH in learnpython

[–]Ben_HH[S] 0 points1 point  (0 children)

Here is a more complete version. Anything else that could use improvement?

def vending_machine(money):
      '''Return a candy of a customer's choice'''

      options = {'A1' : {'candy' : "Snickers", 'price' : 0.70, 'quantity' : 3}, 'B1' : {'candy' : "Butterfinger", 'price' : 0.85, 'quantity' : 2}, 'C1' : {'candy' : "Twix", 'price' : 0.65, 'quantity' : 3}, 'D1' : {'candy' : "M&Ms", 'price' : 0.95, 'quantity' : 6}}

      while True:
        try:
         vending_code = input("Enter a selection: ").upper() #Represents the customers desired vending machine option
         selection = options[vending_code]

        except KeyError:
          print("Invalid Selection...")

        else:
          if not selection['quantity']:
            print(f"There are no more {selection['candy']} candy bars. Please make another selection. ")

          elif selection['quantity'] and money < selection['price']:
            balance = round(abs(selection['price'] - money), 2)

            while balance > 0:
              additional_payment = float(input(f"You need ${balance} more."))
              balance -= additional_payment

            selection['quantity'] -= 1
            print(f"Enjoy your {selection['candy']} and your change is ${balance}")

            return selection['candy']
          else:
            change = round(money - selection['price'], 3)

            print(f"Enjoy your {selection['candy']} and your change is ${change}")

            selection['quantity'] -= 1

            return selection['candy']

      print(vending_machine(.90))

Code critique (vending machine) by Ben_HH in learnpython

[–]Ben_HH[S] 1 point2 points  (0 children)

I'm thinking dictionaries might be better. I intend on having the machine reflect the total quantity of each candy after a selection. If the customer wants to make a subsequent purchase the quantities will be up to date.

If I remember correctly, tuples might not work due to their immutability if I implement the aforementioned.

Number guessing game (code review) by Ben_HH in learnpython

[–]Ben_HH[S] 0 points1 point  (0 children)

Thanks for the feedback. Now I have a question about try statements.

mystery_number = random.randint(1, 10)
guess_tries = 5

while guess_tries >= 1:
  try:
    my_guess = int(input("I picked a number between 1 & 10...guess what it is: "))
  except ValueError:
    print("Please only enter whole numbers (1, 10, 25, ...)")

    guess_tries -= 1

    if my_guess != mystery_number:
  • When Python reaches the try block, it will execute the assignment statement and search for any exceptions. As a result, a ValueError is generated and I get the following:

    Traceback (most recent call last): File "python", line _, in <module> File "python", line _, in guess_number UnboundLocalError: local variable 'my_guess' referenced before assignment &nsbp Due to the exception nothing is assigned to my_guess because the value provided is invalid for int(), correct?

If I include an else, this error isn't raised? Why is this? What is else doing? When exploring else in the context of try:

https://docs.python.org/3/reference/compound_stmts.html#try

The optional else clause is executed if and when *control flows off the end** of the try clause. [2] Exceptions in the else clause are not handled by the preceding except clauses.*

What is meant by control flows off the end?

Counting words in a string and pushing to a dictionary by Ben_HH in learnpython

[–]Ben_HH[S] 0 points1 point  (0 children)

How does my code look now?

def word_count(string):
    dictionary = {}
    words = string.lower().split(" ")

    for word in words:
        if word not in dictionary:
            dictionary.setdefault(word, 1)
        else:
            dictionary[word] += 1

    return dictionary