Frage

Alright, so I've tried this for a while now and I can't seem to find a way to close the program once it is running.

What I want it to do is to end the program if the user chooses 'no':

elif y == 'n' or 'no':
    sys.exit(0)

However whatever I choose returns the program to the partOne function. I've tried different things to try and solve this, such as moving

partOne()

from the end of the program to in between the two functions but that does not work because then the PartTwo function has yet to be defined.

Thanks for your response.

import hashlib
import sys

def partOne():
    x = input("\nEnter something to hash: ")
    hash_object = hashlib.sha256(x.encode())
    hex_dig = hash_object.hexdigest()
    print("\nPlain text: ")
    print(x)
    print("\nHashed text: ")
    print(hex_dig)
    print("\nYour password: ")
    print(hex_dig[::9])
    partTwo()

def partTwo():
    y = input("\nDo you want to make another password? (y/n): ")
    if y == 'y' or 'yes':
        partOne()
    elif y == 'n' or 'no':
        sys.exit(0)
    else:
        print("\nYou need to type either 'y' or 'n'.")
        partOne()

partOne()
War es hilfreich?

Lösung

Try y == 'n' or y =='no'

instead of y == 'n' or 'no'

>>> y = 'anything'
>>> 
>>> bool(y == 'n' or 'no')
True

your statement always returns True. Instead of checking y == 'no' it just checks 'no', anything converted to bool in python is True if its not None, False, or 0.

In case of strings and other iterables it returns True if its not empty, e.g. '', [], {}, () will always return False.

Or as Foo Bar User says, if y.lower() in ('n', 'no') will also do. lower() will make sure that the matching is case insensitive.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top