elif statement won't run in Python - python-2.7

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"

Related

Programm tries to append list with a string although it's not allowed

Hello i am pretty new to python and i am currently writing this program, where i try to find the min and max in a list that is created through inputing numbers sequentialy. When i give the programm the input: 5, a, 1 it gives me the following Error:
Traceback (most recent call last):
File "/home/juli/PycharmProjects/pythonProject/main.py", line 27, in <module>
mx = max(list,key=float)
ValueError: could not convert string to float: 'a'
Code:
def check_for_float(p_input):
try:
ipt = float(p_input)
return ipt
except (ValueError, TypeError):
print("Error, not a numeric input")
return False
list = []
while True:
ipt = input("Please enter a numeric value: ")
if ipt == "done":
break
check_for_float(ipt)
if ipt == type(float) or type(int):
list.append(ipt)
elif ipt == type(str):
continue
if list == []:
quit()
mx = max(list,key=float)
mn = min(list,key=float)
print(f"Maximum = {mx}; Minimum = {mn}")
I don't know why he has trouble converting the str into a float, because normally there shouldn't even be a str in the max() function. My goal is, that the programm leaves str out that's why i put the continue function there. Thanks for any help.
Just remove this part of your code
if ipt == type(float) or type(int):
list.append(ipt)
elif ipt == type(str):
continue
and add this code instead
check = check_for_float(ipt)
if check:
list.append(ipt)
else:
continue
This code will now filter out any character input and only append the valid numeric values into the list.
The complete code should look like this
def check_for_float(p_input):
try:
ipt = float(p_input)
return ipt
except (ValueError, TypeError):
print("Error, not a numeric input")
return False
list = []
while True:
ipt = input("Please enter a numeric value: ")
if ipt == "done":
break
check = check_for_float(ipt)
if check:
list.append(ipt)
else:
continue
if list == []:
quit()
mx = max(list,key=float)
mn = min(list,key=float)
print(f"Maximum = {mx}; Minimum = {mn}")

Finding 2 numbers and send a message about it

I need to find 2 random numbers from 1-100 and send a message:
to high or to low according to the random number,
This is the code I wrote..., it doesn't work after the first if...,
from random import randint
a = int(randint(1, 101))
guess = int(raw_input("guess the number:"))
while guess != a:
if guess > a:
print "bigger"
print guess
print a
elif guess < a:
print "smaller"
print guess
print a
else:
print "correct"
print guess
print a
break
guess = raw_input("guess a new number:")
from random import randint
a = randint(1, 101)
guess = input("guess the number:")
while True:
if guess > a:
print "your guess is too high"
elif guess < a:
print "your guess is too low"
else:
print 'You are correct'
break
guess = input("guess again:")
If I understood correctly your aim this code will work. It will stop when he guesses correctly the number. You had many mistakes with input and int. For future reference - if you use input() instead of raw_input() it will automatically pick the right type for the var.
In order to make your code work as intended just fix the input:
from random import randint
a = int(randint(1, 101))
guess = int(raw_input("guess the number:"))
while True:
if guess > a:
print "bigger"
print guess
print a
elif guess < a:
print "smaller"
print guess
print a
else:
print "correct"
print guess
print a
break
guess = input("guess a new number:") #not raw_input()

My score list is not getting updated. Python (Tic Tac Toe)

Here is what happens.
mc_move
creates scores list and gives it to mc_update_score as an argument.
mc_update_score does all the calculations and updates the list (i checked it by print at the end of mc_update_score function.
But, on the next iteration in mc_move the scores list is set to initial value - all zeros. Though it is supposed to be the list with values from mc_update_score.
What do i miss here?
def mc_update_scores(scores, board, player):
print "scores at the begining of the function is"
print scores
for i in empty_list_score:
# iterate through all the squares of the board
col = i[1]
row = i[0]
if board.check_win() == provided.DRAW:
scores[row][col] += 0
#print score[row][col]
elif board.check_win() == provided.PLAYERX:
if board.square(row,col) == provided.PLAYERX:
scores[row][col] += SCORE_CURRENT
elif board.square(row,col) == provided.PLAYERO:
scores[row][col] -= SCORE_OTHER
else:
scores[row][col] += 0
# print score[row][col]
elif board.check_win() == provided.PLAYERO:
if board.square(row,col) == provided.PLAYERO:
scores[row][col] += SCORE_CURRENT
elif board.square(row,col) == provided.PLAYERX:
scores[row][col] -= SCORE_OTHER
else:
scores[row][col] += 0
print
print "Scores at the end"
print scores
def mc_move(board, player, trials):
global empty_list_score
empty_list_score =board.get_empty_squares()
scores = [[0 for col in range(board.get_dim())]for row in range(board.get_dim())] # create score board
# Here we create the scores list just once at function call and from here on
# it only gets updated. Like each element is getting changed by +1 or - 1.
# i do not see any spot where the entire list is being created again or
#emptied = e.g. is set to all zeros.
num = 0
while num < trials:
board_c = board.clone() # create new board for every iteration
mc_trial(board_c, player) # play a full game for every iteration
mc_update_scores(scores, board_c, player) # update score for every
#iteration after the game is played.
num +=1

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

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( '*******************' )

Issue with an exception from a class, how to get it to return the main-script?

I'm having an issue with an exception in my class. I want it to return to my main-script if that's even possible, or any solution which will avoid any crashing of my program. I'll show you the code.
Here's the main script:
from requestnew import requestNew
def chooseCountry():
countryc = input("Enter which country your city is in(in english): ")
rq.countrychoice.append(countryc)
def chooseCity():
cityc = cityc = input("Enter the name of the city: ")
rq.citychoice.append(cityc)
def makeForecast():
try:
for day in rq.data['forecast']['simpleforecast']['forecastday']:
print ("Country: ", rq.countrychoice[-1], "City: ", rq.citychoice[-1])
print (day['date']['weekday'] + ":")
print ("Conditions: ", day['conditions'])
print ("High: ", day['high']['celsius'] + "C", '\n' "Low: ", day['low']['celsius'] + "C", '\n')
except Exception as e:
print ("\nHave you typed in the correct country and city?\nBecause we got a" ,'"',e,'"', "error\nplease try again!")
return menu
if __name__ == '__main__':
"""Introducion"""
print ("\nThis program lets you see a weather forecast for your choosen city.")
rq = requestNew()
while True:
try:
print("\nWhen you have typed in country and city, press 3 in the menu to see the weather forecast for your choice.\n")
menu = int(input("\nPress 1 for country\nPress 2 for city\nPress 3 to see forecast\nPress 4 to exit\n"))
if menu == 1:
chooseCountry()
elif menu == 2:
chooseCity()
elif menu == 3:
rq.forecastRequest()
makeForecast()
elif menu == 4:
print ("\nThank you for using my application, farewell!")
break
elif menu >= 5:
print ("\nYou pressed the wrong number, please try again!")
except ValueError as e:
print ("\nOps! We got a ValueError, info:", e, "\nplease try again!")
continue
And here is my class code:
import requests
import json
class requestNew:
def __init__(self):
self.countrychoice = []
self.citychoice = []
def countryChoice(self):
self.countrychoice = []
def cityChoice(self):
self.citychoice = []
def forecastRequest(self):
try:
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + self.countrychoice[-1] + "/" + self.citychoice[-1] + ".json")
self.data = r.json()
except #?
As you can see above I use an exception in the def forecastRequest(self):. The problem is I don't know which exception and how to return it correctly to avoid any program crashes.
If you look at my main-script you can see that I have while True: to loop everything from the menu.
Everything in the program works correctly except if I press 3; elif menu == 3: without choosen both country from def chooseCountry(): or city from def chooseCity():.
This is because I'm using a list in my class and then print it in the def forecastRequest(self): like this; countrychoice[-1] to get the last appended list-item from input. And when I press 3 in the menu without choosing country or city, the list will be empty.
My question is, is there any way to let the except #? in def forecastRequest(self): to return the user to the menu in my main-script? Or is there any other way to avoid the program of crashing if the list is empty when I try to make the request?
Sorry for my english, and sorry if my explaining is messy, I've tried my best for it to be relatively easy to understand as possible.
If you want control to return to the main loop, catch the exception in the main loop:
elif menu == 3:
try:
rq.forecastRequest()
except IndexError:
# self.countrychoice[-1] will raise an IndexError if self.countrychoice is empty
# handle error
else:
makeForecast()