Python Yes/No User Input

18,805

Solution 1

Use raw_input instead:

Join = raw_input('Would you like to write to text file?\n')

raw_input gets what the input was as a string, while input gets the exact user input and evaluates it as Python. The reason you're having to put "Yes" rather than Yes is because you need to make the input evalute as a string. raw_input means that you don't need to do that.

Note for Python 3.x

raw_input was changed to input in Python 3.x. If you need the old functionality of input, use eval(input()) instead.

Solution 2

Don't use input in Python 2.x; use raw_input. input is equivalent to eval(raw_input(...)), which means you have to type a string which forms a valid Python expression.

In Python 3, raw_input was renamed input, and the former input was removed from the language. (You rarely want to evaluate the input as an expression; when you do, you can just call eval(input(...)) yourself.)

Solution 3

You can change your if statement to use lower() or upper() to compare with the string and not have to use the single quotes around the 'yes' or 'y' as indicated below

if Join.lower() == 'yes' or Join.lower() == 'y':

If using Python3, try this:

Join = input('Would you like to write to text file?\n')
if Join.lower() == 'yes' or Join.lower() == 'y':
    for key, value in ip_attacks.iteritems(): #for key(the IPAddress) and value(the occurrence of each IPAddress) in ip_attacks
        if value > 30: #if the value (number of occurrences) is over 30
            myTxtFile.write('\n{}\n'.format(key)) #then we want to write the key(the IPAdress) which has been attack more than 30 times to the text file
else:
    print ("No Answer Given")

Otherwise if using Python2, as others have stated you would want to use raw_input() instead of just input()

Share:
18,805
Daniel
Author by

Daniel

Updated on June 18, 2022

Comments

  • Daniel
    Daniel almost 2 years

    I am trying to create a user input for writing to a file the current code works but i have to write my answer with ' ' around them is there anyway i can just write yes or Y without having to include ' '

    Join = input('Would you like to write to text file?\n')
    if Join in ['yes', 'Yes']:
        for key, value in ip_attacks.iteritems(): #for key(the IPAddress) and value(the occurrence of each IPAddress) in ip_attacks 
            if value > 30: #if the value (number of occurrences) is over 30  
                myTxtFile.write('\n{}\n'.format(key)) #then we want to write the key(the IPAdress) which has been attack more than 30 times to the text file
    else:
        print ("No Answer Given")