Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Yes/No User Input

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")
like image 974
Daniel Avatar asked Mar 13 '23 22:03

Daniel


2 Answers

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.

like image 64
Aaron Christiansen Avatar answered Mar 29 '23 06:03

Aaron Christiansen


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.)

like image 20
chepner Avatar answered Mar 29 '23 04:03

chepner