Syntax error with If statement [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm just learning Python and right now i'm making a very simple rock, paper, scissors game where the user picks one choice and the computer randomly picks another then the program compares the two and says who won.
My code looks like this:
print ('Rock, Paper, Scissors! The game of random guessing!')
print (input('Please hit enter to begin'))
choice = input('Choose Rock, Paper, or Scissors: ')
print('You decided on: ', choice)
import random
'''random gives this program the ability to randomly choose from a list'''
ComputerChoiceOptions = ['Rock', 'Paper', 'Scissors']
ComputerChoice = random.choice(ComputerChoiceOptions)
print('The computer went with:', ComputerChoice)
if choice = ComputerChoice
Winner = 'Tie'
Print(Winner)
My question is specifically with this bit
if choice = ComputerChoice
My debugger gives me a syntax error with this and I'm not sure why.

If statements (and other control blocks) require a colon and indentation. Also, test for equality by using a double '='.
Example:
if choice == ComputerChoice:
assign = 0

Based on the question I'm assuming you are learning programming for the first time, as your problem is one of the first concepts any programmer must learn.
You need to use a == instead of a = when comparing two things in an if statement. When you use a = it assigns the item.
Also, since you are using Python, you will need to indent the body of the if statement.

Related

How can I debug an if statement that isn't working? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I do not know what I did wrong.
def main(): # store anything to then replay code.
import time
math = int(input("Hi there, what is 32 + 16? =")) # asking what 32+16 is.
if math == "48":
print("Correct!") #this is the if statement that isn't working, suppose to say correct if the input is 48.
else:
print("Not quite..") # this would come up instead of 'correct' if I would put 48.
time.sleep(2) # a delay
restart=input('Do you wish to start again? ').lower()
if restart == 'yes': # if the player wants to play the game again.
main() # to replay code.
else:
exit() # this wouldn't start the game again.
main() # this just starts main.
Change this
if math == "48":
to this:
if math == 48:
You convert the input to int already.
Wouldn't this be better served in a while loop as opposed to being enumerated at runtime?
To answer your question, you've already declared an integer, the quotes make python interpret it as a string.
You were super close but there are a few things that needed tweaking to get it working.
First, you will need to make sure that your main is defined correctly and remove the "**" from your code before the comments.
Second, the reason your code always fails the if statement check for if they got the correct answer is that you are casting the answer to an integer when you get the input, but then comparing it to a string version of 48, deleting the quotations around that should fix the issue as well.
I have implemented these and had the code working in python3 on my system.
Hope this helps (modified code below)
import time
def main():
math = int(input("Hi there, what is 32 + 16? =")) #
if math == 48:
print("Correct!") #This is where I made the change, removing the
quotes that surrounded the 48.
else:
print("Not quite..")#this would come up instead of 'correct' if I
would put 48.**
time.sleep(2)#a delay**
restart=input('Do you wish to start again? ').lower()
if restart == 'yes':#if the player wants to play the game again.**
main()#to replay code.**
else:
exit()#this wouldn't start the game again.**
main()#this just starts main.**

Test case for the magic-8-ball game [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm mew to python and to TDD in general, I have developed a magic-8-ball game and I would like to learn how I can write the Test case for this program. The test should ensure the following:
Allow the user to input their question
Show an in progress message
Create 10/20 responses and show a random response
Allow the user to ask another question/advice or quit the game.
Below is my code. I know I should write Tests first but like I said, this a new territory for me.
RESPONSES = ("It is certain", "It is decidedly so", "Without a doubt", "Yes-definitely",
"You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Yes",
"Signs point to yes", "Reply is hazy", "Ask again later", "Better not tell you now",
"Cannot predict now", "Concentrate and ask again", "Don't count on it",
" My reply is no", "My sources say no", "Outlook not so good", "Very doubtful")
from time import sleep
from random import choice
class MagicBall:
def input_question(self):
play_again = 'yes'
while play_again == 'yes':
str(input('Enter your question: '))
for i in range(3):
print("Loading {}".format(".."*i))
sleep(1)
print(choice(RESPONSES))
play_again = str(input("Would you like to ask another question? yes/no ")).lower()
if play_again == 'no':
print("Goodbye! Thanks for playing!")
SystemExit()
magic = MagicBall()
magic.input_question()
Unit tests are written to confirm that the expected output is obtained from a range of inputs for any function or method that carries out some computations and returns a value.
If you had a function to calculate the sum of two number:
def calc(first,second):
return first + second
To confirm that the correct result is obtained you would do the following:
self.assertEqual(calc(5,5), 10)
You expect 10 to be the result from 5 and 5 so if it is something else it will produce an error.
I have also noticed this is a question from the Andela Interview questions scheduled for next week. Please review the documentation you were given for more clarity on how to write tests for different cases.

Python is stopping before running a loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm having trouble with this code. It will run normally until it gets to the loop (def Game) and just stops there. I did have it as an if statement but that still didn't work. Please note that this may be a bit messy.
import random
import time
GameInProgress = ("Yes")
TutorialDone = ("No")
ReplayGame = ("Yes")
#Test purposes
PlayerName = ("Lewis")
print ("Welcome to 'Guess The Word!")
def Game():
GameInProgress = ("Yes")
TutorialDone = ("No")
ReplayGame = ("Yes")
#Test purposes
PlayerName = ("Lewis")
print ("Welcome to 'Guess The Word!")
WordSelected=("No")
LettersGuessed=0
print (TutorialDone)
EnterName = input("Would you like to enter your name?").title()
def Game(): is not a loop, it is a function it does not execute until you call it.
you can call a python function in this way
Game()
if you want to call the same function again and again simply you can call the function inside a for or while loop:
while(condition):
Game()
if your are very beginner follow some tutorials
https://www.tutorialspoint.com/python/python_functions.htm

Python - How do I get this to read the code? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Here is my code
import time
print("------------------------------------------")
print(" Welcome to Senpai Quest")
print('------------------------------------------')
time.sleep(3)
print("")
print('You have English next, there is a test. If you hit yes .you go to
class and you get +1 charisma and Knowledge.')
print("")
print('If you hit no, you will skip class and get +1 Courage and +1 risk.')
ans1=str(input('Do you Take the english test? [Y/N]'))
if ans1== ['y']:
print("It works")
else:
print("Woo Hoo!")
When it asks the question and for the 'y' it just goes straight through to "woo hoo!". What i would like it to do is to print "It works" but if you type n it just goes to woo hoo. Please help
This should work:
ans1 = input('Do you Take the english test? [Y/N]').strip()
if ans1.lower() == 'y':
print("It works")
else:
print("Woo Hoo!")
I suggest using the distutil's strtobool in order to cover all cases
from distutils.util import strtobool
ans1=input('Do you Take the english test? [Y/N] ').strip()
if strtobool(ans1):
print("It works")
else:
print("Woo Hoo!")

unexpected Indent and break out of loop in game code [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
i am new to python as you may be able to tell with this question. I am currently building a Rock, Paper, Scissors game to later include into a bigger program i am working on in python 3.4. the problem i am having is in the code listed below.
def computerPlayer(): #randomly selects a rock paper or scissor for computer hand
c = random.randint(0, 2)
if c==0:
y=('rock')
if c==1:
y=('scissors')
if c==2:
y==('paper')
return y
in front of the bottom line return y i am getting a unexpected Indent error, i have tried correcting this over the past day now with no results, if i move it forward i get 'return' outside function, but when i move it back i get the unexpected indent, I am honestly at a complete loss here and im not sure where to go. Any help is great thanks.
the above problem is now fixed, but i know have a break outside of loop error. it is appearing at the end of my code now. any help is great thank you.
again = raw_input('do you wish to try again? (yes\no)\n :') #Ask the user if they want play again
if again == ('yes') or again == ('sure') or again == ('okay'):
print ('')
elif again == ('no') or again == ('nah') or again == ('nope') or again == ('screw you') or again == ('screw it'):
print ('FINE THEN!!! =^( \n (Enter>>>game()<<< if you change your mind)')
#breaks the loop
break
game()
Try this:
def computerPlayer():
'''
Randomly selects a rock paper or scissor for computer hand
'''
c = random.randint(0, 2)
if c == 0:
y = ('rock')
if c == 1:
y = ('scissors')
if c == 2:
y = ('paper')
return y
Indentation is important in python, it shows where your methods and control flows start and end. In your previous code, the if statements were not indented under the method and so python could not tell that it was apart of the computerPlayer() function.
According to PEP8 ( a style guide for python ) proper indentation is 4 spaces. For more information on PEP8 and its view on indentation, check here:
http://legacy.python.org/dev/peps/pep-0008/#indentation

Categories

Resources