Python Forum

Full Version: Problems with coding a script in python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I've learnt the absolute basics of python and I am writing a script for my computing homework. The idea is that it asks you to think of a number between 1 and 10, before asking you to double it, add 10, halve it and take away the number you started with. Because it goes through the sequence n --> 2n --> 2n + 10 --> n + 5 --> 5 the computer can tell you the number you are thinking of, that is 5. Here is what I've tried so far, could anyone find where I went wrong and why it isn't working?
number=(input("Think of a number between 1 and 10. Reply with an Ok when you have it."))
if number==Ok:
          nextstep==(input("Double it, then add 10 "))
          else print("Must try harder ...")
          if nextstep==Ok:
              stepafterthat==(input("Halve it"))
              else print("Must try harder")
              if stepafterthat==Ok:
                  laststep==(input("Take away the number you started with."))
                  else print("Must try harder ...")
                  if laststep==Ok:
                      print("You are thinking of 5!")
                      else print("Must try harder ...")
Please use code tags, otherwise your indentation will be lost
(Nov-09-2016, 09:17 PM)JoeLamond Wrote: [ -> ]I've learnt the absolute basics of python and I am writing a script for my computing homework.
You should look trough the basic stuff one more time.
What you have written now is a mess of very basic errors.

All "else" block has syntax error.
Try run 1 of your line in interactive shell.
>>> nextstep==(input("Double it, then add 10 "))
Traceback (most recent call last):
 File "<string>", line 301, in runcode
 File "<interactive input>", line 1, in <module>
NameError: name 'nextstep' is not defined

>>> # Should be =
>>> nextstep  = input("Double it, then add 10 ")
>>>
You are storing a 'string' value in number. There for the comparison has to be with an equivalent  'string' value in order to be True.
So line 2 for example should be written as

if number == "Ok":    # note the quotes
Also, indentation is very important in Python. In your case, the "else" statements should line up with the associated "if" statement.

YES
if condition:
    do_something
else:
    do_something_else
NO
if condition:
    do_something
    else:
        do_something_else
Thank you very much for the help. As I said before, I only learn the absolute basics of python and was trying to do something a bit more ambitious. Hopefully, I wil be able to write the code correctly next time.