Breaking my code down into a loop - python

I am currently working on a battleship game to practice my programming skills. I have functional code but was wondering if anyone can help me break my code down into a for loop?
import random
def main():
board = []
for i in range(0,5):
board.append(random.randint(1,50))
print(board) #test purposes
guess=int(input("enter number between 1-50"))
if guess == board[0]:
print("hit")
board[0]="hit"
elif guess != board[0]:
print("miss")
board[0]="miss"
Note i want to carry out the if statement multiple times to check for board[0-5].
Instead of repeating it 5 times I was thinking of doing something like this:
for x in range(0,5):
if guess == board[x]:
print("hit")
board[x]="hit"
else:
print("miss")
board[x]="miss"
But this is not working as it takes just 1 input whereas I want it to take 5. For each input it has to check if input is equal to board[0-5]
Thank You in advance for any help.

write guess in a for loop,be careful about indentation
import random
def main():
board = []
for i in range(0, 5):
board.append(random.randint(1, 50))
guess = int(input("enter number between 1-50 : "))
print(board) # test purposes
if guess == board[0]:
print("hit")
board[0] = "hit"
elif guess != board[0]:
print("miss")
board[0] = "miss"

I'm not quite sure what you are trying to achieve, but I believe it to be this:
import random
def main():
board = []
for i in range(0,5):
board.append(random.randint(1,50))
print(board) #test purposes
guesses = []
try_nr = 0
while try_nr < 5:
try_nr += 1
guess = int(input("enter number between 1-50"))
guesses.append(guess)
for i in enumerate(guesses):
i = i[0]
if guesses[i] in board:
print("hit")
# board[0]="hit" --> not quite sure what you want to achieve here?
else:
print("miss")
# board[0]="miss" --> not quite sure what you want to achieve here?
NB1: There are other more neat/dense ways to code this, but this helps you to get going. See if you can perfect it for yourself if needed.
NB2: I have changed your elif statement into else. Your equation can only have two possible answers (either a hit or a miss). By using elif you are forcing python to reconsider/re-calculate your if-statement fully while using else it only considers the if-statement once.

You can use the enumerate() function to add a counter to your for loop. This will be useful.
board = [12, 4, 76, 2]
for index, number in enumerate(board):
print index, number
#output
# 0 12
# 1 4
# 2 76
# 3 2
You said you want to take 5 guesses? You could do something like this:
for i in range(5):
guess=int(input("enter number between 1-50"))
for index, number in enumerate(board):
if guess == number
print("hit")
board[index] = "hit"
else:
print("miss")
board[index] = "miss"

Related

i made an gusse counter with while loop for 3 trys and the counter stuck at 2

import random
import itertools as it
def guessthenumber():
play = input("do you want to play ?\nanswer yes or no :")
while play != "yes" :
if play == "no" :
quit()
else:
guessthenumber()
break
guessthenumber()
answer = random.randint(1, 5)
def random_func():
gusse = int(input("choose a number between 0 and 10"))
count = 3
while gusse != answer and count != 0 :
count -= 1
print(count)
print("wrong")
random_func()
break
random_func()
print("won")
Why does the guess count stop at 2 even with for loop?
The primary issue is as pointed out by #quamrana. When you call random_func you are adding a new stack frame that has a new count variable initialized to 3, so it immediately decrements, but then you add another call to random_func. You never return and pop this call off the stack, so there is no way to continue.
I don't see why ask if the caller wants to play. If it is the only thing the program does, running it is a pretty good indication. Also, is "gusse" a thing or just a misspelling of "guess".
You should avoid using quit() unless you are in an interpreter. You can use sys.exit, but in simple scenarios like this, returning and finishing the program is more simple.
Consider the following implementation with some slight improvements.
import random
def start(answer, tries):
while tries: # Continue while tries remain.
guess = int(input("choose a number between 0 and 10: "))
if guess == answer:
print("won")
return # Just return from the function.
tries -= 1 # Otherwise, decrement and continue.
print(f"wrong; tries remaining: {tries}")
if __name__ == "__main__":
answer = random.randint(1, 5)
start(answer, 3) # Begin the guessing part of the game.

How to find Where a List First Went out of Order in Python

I'm writing this program at school where my teacher wants us to enter 5 numbers into a list, and if the list of numbers is not in order of least to greatest, it is to say where the list first went out of order.
My code:
#Function Definititions
def start():
list = []
for i in range(0,5):
number = int(input("Enter a number: "))
list.append(number)
flag = 0
i = 1
while i < len(list):
if(list[i] < list[i-1]):
flag = 1
i += 1
if(not flag) :
print("This list of numbers is true.")
else:
print("This list of numbers is false. List became out of order at", )
list = sorted(list, reverse=False)
print("True Version:",list)
return flag
#Main Program
start1 = start()
I wanna say where a list like, for example, 10,4,5,8,10 went out of order first, which would be at list[0] in that particular case. I can't add any shortcut functions already built into Python, and the part where my code says print("This list of numbers is false. List became out of order at", ) is where I wanna add it, which is why I left it blank in my program. Everything else in my program works fine, so it wouldn't matter too much if a solution can't be found, but if anyone does know what to do, I am all ears.
Something like this
# Function Definitions
def start():
my_list = []
for i in range(0, 5):
number = int(input("Enter a number: "))
my_list.append(number)
flag = False
i = 1
while i < len(my_list):
if my_list[i] < my_list[i - 1]:
# found out of order element
flag = True
print(f'Out of order at {my_list[i - 1]}') # print the element
break # no need to continue
i += 1
if not flag:
print("This list of numbers is true.")
return flag
# Main Program
start1 = start()

how can I reduce my code? A lot of it is repetitive

The code creates a random addition problem and spits out "Congratulations" if correct and "sorry...." if the inputted value is wrong. The while loop repeats this process until the user inserts "N" for the question "continue (Y/N):, at the same time it keeps track of how many questions have been answered, and which ones are correct. The code works fine, my problem is it has repetitive code. I was wondering if there is a way to shrink it.
**I appreciate everyone one's help and advice. I"m a noob that's just learning python **
import random
correct=0
count=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congraulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
while c == "Y":
count+=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congraulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
else:
print('Your final score is',correct,'/',count)
A first start, would be eliminating the code before the while, by initializing the count variable (which keeps track of the turns), in zero, and allowing the while loop to run the first turn, we just need to have a variable like want_to_play and by default it's True, so the first time we'll be playing, and at the end of the game If I don't input Y or y it will asume I don't want to play any more and set the variable to false, that way I can have all the turns ran by the while loop.
and you'll be getting something like this.:
from random import sample
correct = 0
count = 0 # STartint in turn zero
want_to_play = True # Control Variable
while want_to_play:
count += 1
# First turn this is zero, and adds one.
[num1, num2] = sample(range(0, 101), 2)
# Just another way of getting two random numbers from 1 up to (including) 100.
# Printing could be done in one line.
print(format(num1, '5d') + '\n+' + format(num2, '4d'))
answer = int(input('= '))
# The comparison really doesn't really hurt if you do it this way.
if answer == num1 + num2:
print('Congraulations!')
correct += 1
else:
print('Sorry the correct answer is', sum)
# HERE you ask if you want to play again or not, using a one line if
# you decide.
want_to_play = (True if 'y' == input('Continue (Y/N).lower():')
else False)
else:
print('Your final score is',correct,'/',count)
By initializing the variable c as "Y", the condition is met and the loop can be executed:
import random
correct=0
count=1
c = "Y"
while c == "Y":
count+=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congraulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
c = c.upper()
else:
print('Your final score is',correct,'/',count)
I also added the method upper() to the Y/N input so the user can also type it in lowercase
Try to move as much of the processing as possible into the loop. The first "paragraph" of your code was basically a duplicate of the main-loop. By creating the continuation variable c so that it drops straight into the loop, most of that first block could be removed.
import random
correct=0
count=0
c = 'Y'
while c == "Y":
count+=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2
if answer==sum:
print('Congratulations!')
correct+=1
else:
print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')
else:
print('Your final score is',correct,'/',count)
The two formula printing statements can also be reduced to a single one:
print(format(num1,'4d'))
print('+',num2)
could be
print( format(num1,'4d') + '+', num2 )
The variable sum could be removed, but it does make the code self-documenting, which is a good thing.

Creating a game where the computer guesses a value through inputs of <,> or =

I am trying to create a game where i think of a number in my head. And then the computer guesses the number through me telling it if its guess is too low or high.
This is what I've come up with but i am pretty lost tbh.
maxguess = 100
minguess = 1
count = 0
print("Think of a number between {} and {}".format(minguess,maxguess))
def midpoint(maxguess, minguess) :
z = ((maxguess + minguess)/2)
def guessing(x) :
print("Is you number greater (>) , equal (=) ,or less (<) than" ,z,)
print("please answer <,=, or >! >")
x = input()
if x == (">") :
minpoint = z
count += 1
continue
elif x == ("<") :
maxpoint = z
count += 1
continue
elif x == ("=") :
print ("I have guessed it!")
count += 1
break
print("I needed {} steps!".format(count))
Purposely not a complete solution, but some hints for you:
I'd recommend avoiding the global variables like count, maxguess, and minguess. Instead, make a function that holds all these variables.
Change your midpoint function to return z instead, then call it inside your guessing function.
Your continue and break functions would need to be inside a for or while loop. Since you aren't sure how many iterations you need to guess the number, I think a while loop would make sense here
Your functions are never run. On a style point, bring all your 'main' statements down to the bottom so they're together. After the prompt to think of a number, you need to call the guessing() function. When you call it, you should pass the minguess and maxguess values to it.
I can see what you're trying to do with the if...elif statements, but they need to be in a while True: block. So should the three statements preceding them so the script repeatedly asks for new advice from you.
Either bring the content of the midpoint() function into guessing() or make it return the value of z.
You also offer the user a choice of '>1' but don't handle it - and you don't need it as far as I can tell.
You never use minpoint or maxpoint - and you dont need them. Call the midpoint function instead and pass it the appropriate values, e.g., if '>', z = midpoint(z, maxguess).
Also, you're going to spend forever trying to get it to guess as you are using floats. Make sure everything is an integer.
Finally, you should add some code to manage input that isn't expected, i.e., not '<', '>' or '='.
Good luck!
minguess=1
maxguess=100
z=50
count=0
print("Think of a number between 1 and 100")
condition = True
while condition:
z=((maxguess + minguess)//2)
print("Is your number greater (>) , equal (=) ,or less (<) than" ,z,)
print("Please answer <,=, or >! >")
x = input()
if x == (">"):
minguess=z
count += 1
elif x == ("<") :
maxguess=z
count += 1
elif x == ("=") :
print ("I have guessed it!")
count += 1
condition=False

How can I make a loop with changing random numbers?

I want to make a game that will generate multipication equations. I want to make it that you will get a simple multipication equation (ex: 5*6) and when you answer it, the program will tell you if you are correct, and then will go to the next random equation.
I know how to make it with a lot of different random numbers, but this will make the code very long and not ellegant.
I need a way to generate two different random numbers every time, without having to make a data base of let's say 20 different random numbers. Does anyone know how to do it?
Thanks!
This is the code I've wrote so far:
import random
import sys
import os
random_num1 = random.randrange(1, 10)
random_num2 = random.randrange(1, 10)
print(random_num1, 'X', random_num2, '=', )
def multiplication(random_num1, random_num2):
sumNum = random_num1 * random_num2
return sumNum
one = input()
if(int(one) == multiplication(random_num1, random_num2)):
print('true')
else:
print('false')
Put all of your code into a while loop that never ends using while True: (and don't forget to move everything inside by one tab to the right).
It's advisable to move def multiplication out of the while loop though.
You could easily do it with a function and a while loop. Let's say, you want to play 10 times and want the score at the end.
def multiplication(random_num1, random_num2):
sumNum = random_num1 * random_num2
# Indentation fixed
return sumNum
def play() :
random_num1 = random.randrange(1, 10)
random_num2 = random.randrange(1, 10)
print(random_num1, 'X', random_num2, '=', )
one = input()
if(int(one) == multiplication(random_num1, random_num2)):
return 1
else:
return 0
if __name__ == '__main__' :
number_of_play = 10
cpt = 0
result = 0
while cpt < number_of_play :
cpt+=1
cpt += play()
print "Wow you perform {} out of {}".format(result, number_of_play)
Here it is a simple example made by me (EDITED with "try" statement):
from random import randint
while 1:
numA = randint(0,9)
numB = randint(0,9)
result = numA * numB
print("\nFirst number:", numA)
print("Second number:", numB)
while 1:
try:
userResult = int(input("Insert your multiplication result: "))
break
except:
print("Error! The given digit is not a number. Retry :")
if userResult == result:
print("Bravo! That's right!")
else:
print("Damn! That's wrong!")
I've tried to be as clear as possible. I hope it was useful for you.

Categories