Amorky
Amorky

Reputation: 39

ValueError with input and int

I am in an intro to programming class which is using zyBooks so I'm not sure (due to the way this interpreter works) if my problem is just me doing something stupid or just not working properly with the zyBooks thing.

Its asking me to do a basic user input string. These are the instructions:

Assign user_str with a string from user input, with the prompt: 'Enter a string: '

Hint -- Replace the ? in the following code: user_str = ?('Enter a string: ')

I believe i've followed the instructions its given me but I'm getting this error. Thanks for any help!!!

1
2 '''Your Solution Goes here '''
3 user_str = int(input'Enter a string: '))
4 print()
5 
6 print(user_str)

The error I'm getting:

Exited with return code 1
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    user_str = int(input('Enter a string: '))
ValueError: invalid literal for int() with base 10: 'Hello!'

Upvotes: 0

Views: 1208

Answers (2)

randomrabbit
randomrabbit

Reputation: 322

You cannot turn Hello! into an int. Get rid of the int(...) around input.

Note: You can turn strings into ints if the string is a valid number.

Upvotes: 2

Felipe Urcelay
Felipe Urcelay

Reputation: 11

Im a little confused with your question, so I will answer both interpretations I can make.

If you want the user to enter a string (ex: Hello World), you want to save it as a string in a variable, so omit the int() function that will try (and fail) to convert it to a integer:

user_str = input('Enter a string: ')

If you want an integer instead (ex: 231) the problem is that you are asking the user for a string, so a better solution would be:

user_str = int(input('Enter a number: '))

or:

user_str = int(input('Enter a integer: '))

The correct way for this case would be to try to convert it to a integer, and print a message if it fails (Probably you haven't seen this in your class yet):

correct_inp = False
while not correct_inp:
    inp_str = input('Enter a integer: ')
    try:
        user_str = int(imp_str)
        correct_inp = True
    except:
        print("Ups, this is not an integer, try again")
print(user_str)

Upvotes: 1

Related Questions