Shmuel
Shmuel

Reputation: 55

Having an issue with input

I made a function that gets a list of integers from the user and bubble sort them. This is the error i get:

"input2= input("Please enter some numbers separated by backspace: ") File "", line 1 1 0 3 2 5 4"

def ex2():
    list2= []
    input2= input("Please enter some numbers separated by backspace: ")
    list2_input = input2.split()

    for i in list2_input:
        list2.append(i)

    for i in range(0, len(list2)-1):
        for j in range(0, len(list2)- 1 - i):
            list2[j], list2[j] = list2[j+1], list2[j]
    print list2

Upvotes: -1

Views: 68

Answers (3)

Stefano
Stefano

Reputation: 4031

if you do not want any automatic evaluation on your input use:

raw_input("Please enter some numbers separated by backspace: ")

this is a problem you will only have in Python 2.7 as the 2.7 raw_input has been renamed input in Python 3.

if you call input in Python 2.7 this will call:

eval(raw_input("Please enter some numbers separated by backspace: "))

and as you can see on the following link: https://docs.python.org/2/library/functions.html#eval evals evaluate checks that the expression argument is parsed and evaluated as a Python expression.

Upvotes: 1

Antman
Antman

Reputation: 21

input(...) Equivalent to eval(raw_input(prompt)).

So use raw_input instead or input "1 0 3 2 4 5" include double quotation marks。

Upvotes: 0

Kevin
Kevin

Reputation: 76194

In Python 2.7, input takes the input from the user and runs eval on it. If the text is not a valid Python expression, it will crash.

"1 0 3 2 5 4" is not a valid Python expression, so if the user enters that at an input prompt, it will crash.

To take input from the user without evaling it, use raw_input instead of input.

Upvotes: 4

Related Questions