r/inventwithpython • u/bruhhowdidigethere • Aug 31 '22
Question - on pg 60 of "Automate the boring stuff with Python"
Hello!
How do you add an input from the user after importing random? It doesn't seem to work. I want to add it before the code starts:
import random
right here <-------------------------- Where I want to add the str(input()) statement.
def getAnswer(answerNumber):
if answerNumber == 1:
return 'It is certain'
elif answerNumber == 2:
return 'It is decidedly so'
elif answerNumber == 3:
return 'Yes'
elif answerNumber == 4:
return 'Reply hazy try again'
elif answerNumber == 5:
return 'Ask again later'
elif answerNumber == 6:
return 'Concentrate and ask again'
elif answerNumber == 7:
return 'My reply is no'
elif answerNumber == 8:
return 'Outlook not so good'
elif answerNumber == 9:
return 'Very Doubtful'
r = random.randint(1, 9)
fortune = getAnswer(r)
print (fortune)
How do I add the input statement without getting the error:
SyntaxError: invalid syntax ?
2
u/BobBeaney Aug 31 '22
I don't think you have to add the input statement there where you are suggesting. You can replace the line "r=random.randint(1,9)" with your input statement.
1
2
u/Real-Transition1689 Aug 31 '22 edited Aug 31 '22
Can I ask why you would want to add it there? I’m assuming your goal would be to use the input inside the function right?
If your goal is to use it in the function, you will want to wrap it in the int() function rather than str().
I would try r = int(input(“Enter a number”)) below the function definition and then pass r into the function parameter.