String Error on And command!

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
thangtamfive
Posts: 1
Joined: Mon Jul 03, 2017 4:24 am

String Error on And command!

Post by thangtamfive » Mon Jul 03, 2017 4:36 am

Hello, I am new to MicroPython and therefore this is likely to be a stupid question that anyone should know the answer to, but when I run the following program on my MicroBit it says that there is a syntax error on the line 24-41. If it matters, this is a Rock Paper scissors game, and in lines 24-41 I am trying to makes it say wether you win, lose or tie.
Here is the code:
from microbit import *
import random

rpsbot = ["P2 : Rock", "P2 : Paper", "P2 : Scissors"]
rps = ["Rock", "Paper", "Scissors"]
display.scroll("A=Rock / B=Paper / A+B=Scissors")

while True:
sleep(2000)
if button_a.is_pressed() and button_b.is_pressed():
rps = "P1 : Scissors"
elif button_a.is_pressed():
rps = "P1 : Rock"
elif button_b.is_pressed():
rps = "P1 : Paper"
break


display.scroll(str(rps))
display.scroll(random.choice(rpsbot))

while True:
sleep(500)
if (str(rps)) is "P1 : Paper" and (str(rpsbot)) is "P2 : Paper"():
display.scroll("Tie")
elif (str(rps)) is "P1 : Paper" and (str(rpsbot)) is "P2 : Scissors"():
display.scroll("Lost")
elif (str(rps)) is "P1 : Paper" and (str(rpsbot)) is "P2 : Rock"():
display.scroll("Win")
elif (str(rps)) is "P1 : Rock" and (str(rpsbot)) is "P2 : Paper"():
display.scroll("Lost")
elif (str(rps)) is "P1 : Rock" and (str(rpsbot)) is "P2 : Rock"():
display.scroll("Tie")
elif (str(rps)) is "P1 : Rock" and (str(rpsbot)) is "P2 : Scissors"():
display.scroll ("Win")
elif (str(rps)) is "P1 : Scissors" and (str(rpsbot)) is "P2 : Rock"():
display.scroll("Lost")
elif (str(rps)) is "P1 : Scissors" and (str(rpsbot)) is "P2 : Scissors"():
display.scroll("Tie")
elif (str(rps)) is "P1 : Scissors" and (str(rpsbot)) is "P2 : Paper"():
display.scroll("Win")

Thanks in advance,

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: String Error on And command!

Post by pythoncoder » Mon Jul 03, 2017 6:54 am

You need to save the random choice:

Code: Select all

sel = random.choice(rpsbot)
display.scroll(sel)
Then your comparisons should look like this:

Code: Select all

if sel[5:] == rps[5:]:
The [5:] syntax strips out the "Px : " part of the string to leave just "Rock", "Paper" or "Scissors"
Your line

Code: Select all

rps = ["Rock", "Paper", "Scissors"]
is doing nothing because you redefine rps later.

The correct way to compare strings is with the "==" operator. The "is" operator serves a different purpose and won't work in this context.

There is a lot that could be done to simplify this code but perhaps the first thing for you is to get it to run ;)

Incidentally I don't have a Microbit so my suggestions are untested.
Peter Hinch
Index to my micropython libraries.

Post Reply