I am a python newbie.I am getting familiar with loops and tried this example from a book
while True:
s = input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
However the output is as follows
Enter something : ljsdf
Traceback (most recent call last):
File "trial_2.py", line 2, in <module>
s = input('Enter something : ')
File "<string>", line 1, in <module>
NameError: name 'ljsdf' is not defined
This function was known by the name of raw_input earlier in Python 2. It was later changed to a much simpler name 'input' in Python 3. The raw_input function is obsolete in Python 3 which means, if you are using the latest version of Python then you will not be able to use it.
With int(input()) you're casting the return value of the input() function call to an integer. With input(int()) you're using int() as a prompt for the user input. Since you don't pass int() an argument, it returns zero.
To ask for user input in Python, use the built-in input() function. In addition to asking for simple string input like this, you also want to learn how to: Ask for multiple inputs in one go. Ask for input again until valid input is given.
Use range() to print a string multiple times Use range(stop) to create a range of 0 to stop where stop is the number of lines desired. Use a for-loop to iterate through this range. In each iteration, concatenate the string to itself by the number of times desired and print the result.
You have to use raw_input()
instead (Python 2.x), because input()
is equivalent to eval(raw_input())
, so it parses and evaluates your input as a valid Python expression.
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
Note:
input()
doesn't catch user errors (e.g. if user inputs some invalid Python expression). raw_input()
can do this, because it converts the input to a string
. For futher information, read Python docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With