[Code is working]How to shorten my code? Rock =/= rock? - python-2.7

I'm trying to make a simple 2 player game on python 2.7 .
The program will determine the result of a rock, paper, scissors game, given Player 1 and Player 2’s choices. The program will print out the result, score by each player and the total number of game played.
My question is:
The code doesn't work when "Rock" is the input.It works when "rock" is the input. Same goes to paper and scissors. How can I make it work?

1.The code doesn't work when "Rock" is the input.It works when "rock" is the input. Same goes to paper and scissors. How can I make it work?
From:
player_1 = str(input(">>Player 1? "))
player_2 = str(input(">>Player 2? "))
Add:
player_1 = str(input(">>Player 1? ")).lower()
player_2 = str(input(">>Player 2? ")).lower()
2.Both player must input their choices before the program can be terminated. That means when player 1's input "-1", the program doesn't terminate immediately. It will proceed to ask player 2 for input before it get terminated. How can I make the program terminate itself immediately when player 1's input is "-1"?
From:
player_1 = str(input(">>Player 1? "))
player_2 = str(input(">>Player 2? "))
Add:
player_1 = str(input(">>Player 1? "))
if (player_1=='-1'):
print 'End of game'
break
player_2 = str(input(">>Player 2? "))
3.My code is very long, any suggestions or tips on shortening it without sacrificing any of the function?
use function definitions. Sample:
if (player_1=='-1' or player_2=='-1'):
print 'End of game'
break
elif dif in [-1, 2]:
print ('Player 1 wins.')
score1 = score1 + 1
showScore()
elif dif in [1, -2]:
print('Player 2 wins.')
score2 = score2 + 1
showScore()
else:
print('Tie')
showScore()
continue
def showScore():
print '==================='
print 'Score:'
print 'Player 1: ' + `score1`
print 'Player 2: ' + `score2`
print 'Total game played: ' + `times`
print ''
Here's a good read

For starters, I converted your program to Python 3. It's better in every way. For one thing, it has a normal definition for input.
In general, if you have N of something, where N is greater than 1, it's better to use an array. If you see repetition, move the data into an array and call a function. When N is 2, you won't necessarily shorten the code (my version is longer than yours) but you'll avoid treating the players differently because they both pass through the same logic.
Put the main logic in a function, too, and reserve the "main" code for dealing with startup & command-line stuff.
When you see a string of elifs, that's also a use data instead indicator. In my victor function, I iterate over tuples of winning combinations. You might consider how to use a dict instead.
import sys, os
def print_results( msg, times, scores ):
print( (msg) )
print( '===================' )
print( 'Score:' )
print( 'Player 1: %d' % scores[0] )
print( 'Player 2: %d' % scores[1] )
print( 'Total game played: %d' % times )
print( '' )
def victor( inputs ):
results = ( ('rock', 'scissors'), ('scissors', 'paper'), ('paper', 'rock') );
for (a, b) in results:
if a == inputs[0] and b == inputs[1]:
return 1
if b == inputs[0] and a == inputs[1]:
return 2
return 0
def play(times, scores):
inputs = ['', '']
for (i, choice) in enumerate(inputs):
prompt = '>>Player %d? ' % (i + 1)
choice = input(prompt).lower()
if choice == '-1':
return False
inputs[i] = choice
result = victor(inputs)
if result == 0:
print_results('Tie', times, scores)
else:
scores[result - 1] += 1
print_results('Player %d wins' % result, times, scores)
times += 1
return True
print('''Welcome to play Rock, Paper, Scissors game. Enter -1 to end''')
scores = [0, 0]
times = 0
while play(times, scores):
pass
if scores[0] == scores[1]:
player = 'Tie'
else:
if scores[0] > scores[1]:
i = 1
else:
i = 2
player = 'Player %d' % i
print( '*******************' )
print( 'Winner: %s' % player )
print( '*******************' )

Related

elif statement won't run in Python

This is my code. The last ELIF statement it keeps saying is wrong when ran from codeacademy labs - BATTLESHIP GAME EXERCISE!
from random import randint
board = []
#
# All code functions here
for x in range(0, 5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
# All game variables for row and col guessing
ship_row = random_row(board)
ship_col = random_col(board)
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
# Prints the variable chosen randomly
print ship_row
print ship_col
#
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sank my battleship!"
THIS STATEMENT. CODEACADEMY KEEPS SAYING IS WRONG EVEN THOUGH IT RUNS
WHAT'S WRONG WITH IT?
elif guess_row not in range(0, len(board)-1) or guess_col not in
range(0, len(board)-1):
print "Oops, that's not even in the ocean"
# final else statement. Prints missed battleship msg
# end of code
else:
print "You missed my battleship!" # msg lost game
board[guess_row][guess_col]="X" # shows guess var
print_board(board)
# end of code. Last else statement.
I don't know how did you even make it run since python is so picky with spaces.
maybe that's it but codecademy let you run it in their console for some reason, if you call the file with python installed on your pc it doesn't run.
from random import randint
board = []
# All code functions here
for x in range(0, 5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
# All game variables for row and col guessing
ship_row = random_row(board)
ship_col = random_col(board)
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
# Prints the variable chosen randomly
print ship_row
print ship_col
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sank my battleship!"
# THIS STATEMENT. CODEACADEMY KEEPS SAYING IS WRONG EVEN THOUGH IT
# RUNS
# WHAT'S WRONG WITH IT?
elif guess_row != (0, len(board)-1) or guess_col != range(0, len(board)-1):
print "Oops, that's not even in the ocean"

Beginner Python Game. Create records file

I am learning Python and did this little game where you try to guess the number the Computer has generated.
from random import randint
def guess():
play = 0
while play != 'exit':
numbercomp = randint(1, 9)
tries = 0
humanno = 0
while numbercomp != humanno:
humanno = int(raw_input("What is my number, from 1 to 9? "))
if numbercomp == humanno:
tries = tries + 1
print('you are right, nice!')
elif numbercomp < humanno:
tries = tries + 1
print('my number is smaller than yours')
else:
tries = tries + 1
print('my number is bigger than yours')
print 'you got it in', tries, 'tries'
play = raw_input('press any key to play , type "exit" to leave')
print "Good bye!"
exit()
while True:
try:
guess()
except ValueError:
print('that was not a number from 1 to 9!')
I wonder what would be a way to save the best score (less tries) and the name of the holder into a file and have the program show this information up every time it starts. Less important would be making this file encrypted in some way.
Also, if you spot that the could would be done in a more elegant fashion I would appreciate feedback.
For instance something you could is like this
if tries > score:
pickle.dump( favorite_color, open( "save.p", "wb" ) )
If the trys are lower than the high score then it changes the highest score.
then to open it just do
highscore = pickle.load( open( "save.p", "rb" ) )
and you can just print the high score when the function is first ran.

Adding quit command in python

import random
def main():
Interger_list = []
guessTry = 0
print('Hello!')
print('Want to play guess my interger?')
print('My interger is between -10 and 10')
interger = random.randint(-10, 10)
while True:
print('Take a guess. ')
guess = input()
Interger_list.append(guess)
guess = int(guess)
guessTry = guessTry + 1
if guess < interger:
print('too low')
if guess > interger:
print('too high')
if guess == interger:
print('Winner')
guessTry = str(guessTry)
print('You guessed my interger in ' + guessTry + ' guesses!')
for guess in Interger_list:
print(guess)
main()
i'm trying to add a quit command but have been hitting a wall.
if guess == q
break
I keep getting error.
You want to compare to the string q, so you should do
if guess == 'q':
break
after your guess = input()

(Super beginner) Can someone explain what's going wrong with my lists?

Ok, so, this is the longest code I've ever written, so I apologize if it's a bit messy. First computer science assignment ever.
def main():
#generate random value
import random
rand = random.randint(1, 99)
#instructions
print("""The purpose of this exercise is to enter a number of coin values
that add up to a displayed target value. Enter coins as 1=penny, 5-nickel,
10-dime, 25-quarter. Hit return after the last entered coin value.""")
#defining function for 'first coin'
def firstCoin ():
coins = []
global coins
coin = int(input("Enter first coin: "))
if coin > rand:
print("Sorry, total value exceeds", rand, "cents.")
again = input("Try again (y/n): ")
if again == "y" or "Y":
main()
else:
sys.exit() #ends program
elif coin in possible:
coins.append(coin)
nextCoinplease()
#defining function for 'next coin'
def nextCoinplease ():
while True:
nextcoin = (input("Enter next coin: "))
if nextcoin in possible:
coins.append(nextcoin)
elif nextcoin == "":
break
else: print("Invalid entry.")
#making lists
possible = [1, 5, 10, 25]
print("Enter coins that add up to", rand, "cents, one per line.") #program start
firstCoin ()
sumcoin = sum(coins)
print(sumcoin)
if sumcoin == rand:
print("Correct!")
else:
print("Invalid entry.")
firstCoin()
main()
So, this is my issue. For some reason, user input in the function nextCoinplease does not get added to the list "coins", only the first input from the function firstCoin does. This means that sum(coins) is literally only the first input. I cannot for the life of me figure out why, so any input would be greatly appreciated, thanks!
You have two input statements, one to get coin and one to get nextcoin. They are different. What's the difference?
(I'm deliberately not giving the answer outright because from what you've written so far, I am sure you can figure this one out given this hint.)
The return type of input is a string, so nextcoin in possible always fails since possible only contains integers. Try using int() to parse the input as an integer.
Your code never gets to check if the rand is equal to sumCoin, so it never stopped. I've fixed the problem, this code works now.
Demo on repl.it
What did I do?
I moved your if statement that checked if rand == sumCoin at the beginning of the while loop in nextCoinPlease(), so that it will check the sumCoin value before entering each next coin value and will stop once it equals rand.
Code:
import random
import sys
def main():
rand = random.randint(1, 99)
print('''The purpose of this exercise is to enter a number of coin values \
that add up to a displayed target value. Enter coins as 1=penny, \
5=nickel, 10-dime, 25-quarter. Hit return after the last entered \
coin value.''')
coins = []
def firstCoin():
coin = int(input("Enter first coin: "))
if coin > rand:
print('Sorry, total value exceeds ', rand, ' cents.')
again = input('Try again? (y/n): ')
if again == 'y' or 'Y':
main()
else:
sys.exit()
elif coin in possible:
coins.append(coin)
nextCoinPlease()
def nextCoinPlease():
while True:
sumCoin = sum(coins)
print('Total Value: ' + str(sumCoin))
print ''
if sumCoin == rand:
print('Correct! You Win!')
sys.exit()
elif sumCoin > rand:
print('You exceeded the total value! You lose! Try again!')
sys.exit()
nextCoin = (input('Enter next coin: '))
if nextCoin in possible:
coins.append(nextCoin)
elif nextCoin == "":
break
else:
print('Invalid entry.')
possible = [1, 5, 10, 25]
print('Enter coins that add up to', rand, 'cents, one per line.')
firstCoin()
main()

My if/elif statement only returns if [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
I just want to start by saying i have only just started programing and am only interested in learning.
in a very simple turn-based fighting game, i give my player the choice to attack or defend but when i input a "d" for defend it will return the attack code.
import random
import time
play = 'y'
name = ' '
playerHp = 20
attack = 4
enemyHp = 0
enemyAttack = 0
def intro ():
global name
print('''
welcome to the scary forrest!
dangerous monsters live in this
area and you must destroy or
be destroyed! attack and defend
correctly and you may survive.''')
time.sleep (2)
print ('what is your name, adventurer?')
name = input()
def randomEnemy ():
x = random.randint (3,5)
global enemyHp
global enemyAttack
enemyHp = x * 5
enemyAttack = x
print('''A goblin has jumped out to attack you, prepare to fight!''')
def battle ():
global enemyHp
global enemyAttack
global playerHp
global attack
while enemyHp > 0 and playerHp > 0:
print ('you have ' + str(playerHp) + ' health left')
time.sleep (2)
print ('the goblin has ' + str(enemyHp) + ' health left')
time.sleep (2)
print ('(a)ttack or (d)efend)
choice = input()
if choice == 'a' or 'attack':
finalattack = attack + random.randint (-1,2)
print ('you swing at the goblin and do ' + str(finalattack) + ' damage')
time.sleep(2)
print ('the goblin strikes you for ' + str(enemyAttack) + ' damage')
playerHp = playerHp - enemyAttack
enemyHp = enemyHp - finalattack
choice = 0
elif choice == 'd' or 'defend':
print ('the goblin strikes at you!')
print ('but you block his attack')
heal = random.randint (5,6) - enemyAttack
playerHp += heal
print ('you heal for ' + str(heal) + ' Hp')
choice =0
if playerHp <= 0:
print('you lose... noone finds your body because the \ngoblin drags you into his cave')
if enemyHp <= 0:
print ('you stand victorious over your foe, but noone is \nreally impressed except yo\' momma')
intro()
randomEnemy()
battle()
is there a problem with my if statement?
if some one can help me and use small words that would be greatly appreciated.
Yes, you need to test their choice with:
if choice == 'a' or choice == 'attack':
and:
elif choice == 'd' or choice == 'defend':
Your original statement:
elif choice == 'a' or 'attack':
Will always yield True as the string 'attack' is effectively True (not to mention it should be if and not elif; thanks to #chepner for spotting that).
(I haven't checked all your code).
The problem is that
elif choice == 'a' or 'attack':
is not doing what you think. Python's parser evaluates it as:
elif bool(choice == 'a') or bool('attack'):
and the boolean value of a non empty string is True. What you want is:
if choice == 'a' or choice == 'attack':
Note that I have replaced elif by a simple if, as it is the first one. (elif is short for else if).