Adding quit command in python - exit

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

Related

Trying to create a new list of Odd numbers from a user inputted list?

This is my code. I have looked at many similar codes and have mine set up exactly how I should. I do not receive an error!
The problem is the output I receive is [11]. When the user inputs [1,2,3,4,5,6,7,8,9,11]. Why is it only pulling one odd number??
totlist = []
max_int = 10
oddlist = []
while len(totlist) < max_int:
nums = int(input('Enter a number: '))
totlist.append(nums)
def find_odds(totlist, oddlist):
if len(totlist) == 0:
return
v = totlist.pop()
if v % 2 == 1:
oddlist.append(v)
find_odds(totlist,oddlist)
print(oddlist)
You have forgoot the loop boucle inside the function
def find_odds(totlist, oddlist):
for item in range(len(totlist)) : # here
if len(totlist) == 0:
return
v = totlist.pop()
if v % 2 == 1:
oddlist.append(v)

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"

This code is saying Invalid Syntax, and pointing out at my "guessNum" variable. What is wrong?

from random import randint
myNumber = randint(1000,9999)
guessNum = 0
correctNumbers = 0
Input = False
Userguess = 0
print ("Welcome to Guess The Number")
print ("try to guess my number between 1000 and 9999")
while Input == False:
Userguess = int(raw_input("Guess a number betweeb 1000 and 9999: ")
guessNum += 1
if Userguess == myNumber:
print("Well Done, you guessed the number in" + str(NumberGuesses) + "guesses")
Input = True
The program is a guess the number game where the user has to guess a randomly generated number between 1000 and 9999.
Missing bracket at line no 13.
Userguess = int(raw_input("Guess a number betweeb 1000 and 9999: "))

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

something wrong with my password generator

I made a password generator - I'm only 16 so it's probably not the best- and it outputs 8 0 and ones like 01100101 and then enderneath that it outputs the password. Well when there is a "10" in the password like FG4v10Y6 it will add another character so instead of it being FG4v10Y6 it would be FG4v10Y6M so it has nine or more characters depending on how many "10" are in it.
I'm not sure why it's doing this please help. THanx!
import pygame
import random
pygame.init()
#letters
reg = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
CAP = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
final_pass = []
num_let_list = []
new_list = []
i = 0
file = open("password_test","w")
def num_list_gen(num_list):
for i in range(8):
num_let_list.append(random.randint(0,1))
i += 1
for each in num_let_list:
each = str(each)
new_list.append(each)
print ''.join(new_list)
def CAP_reg_num(final_pass,num_let_list,CAP,reg):
for each in num_let_list:
if each == 0:
cap_reg = random.randint(0,1)
if cap_reg == 0:
let1 = random.randint(0,25)
final_pass.append(reg[let1])
if cap_reg == 1:
let1 = random.randint(0,25)
final_pass.append(CAP[let1])
if each == 1:
num1 = random.randint(0,10)
num1 = str(num1)
final_pass.append(num1)
def main(CAP,reg,num_let_list,final_pass):
num_list_gen(num_let_list)
CAP_reg_num(final_pass,num_let_list,CAP,reg)
print ''.join(final_pass)
file.write(''.join(final_pass))
file.close
main(CAP,reg,num_let_list,final_pass)
why did the code come out all weird on the post in some places and how do you fix it?
Your password generator is flipping a coin to choose between adding a letter or a number. When it chooses to add a number, you choose the number to add with:
num1 = random.randint(0,10)
However, this doesn't return a single digit number. It returns one of 11 possible values: the numbers between 0 and 10 inclusive. So one time in 11, it will add the number 10 to the string, which is, of course, two digits.
You want:
num1 = random.randint(0,9)
instead to add a single digit.