Finding 2 numbers and send a message about it - python-2.7

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

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"

Python 2.7 Coin Flip Program Crashes Every Time

I'm having this strange problem with a simple coin flip program where, instead of giving me some sort of error, whenever i run this code it just sort of crashes. I type in a yes or no answer and hit enter, but it does nothing. Then I hit enter again and it closes out completely.
import time
import random
constant = 1
FirstRun = True
def Intro():
raw_input("Hello and welcome to the coin flip game. Do you wish to flip a coin? (yes or no): ")
def CoinToss():
print "You flip the coin"
time.sleep(1)
print "and the result is..."
time.sleep(1)
result = random.randint(1,2)
if result == 1:
print "heads"
if result == 2:
print "tails"
while constant == 1:
if FirstRun == True:
Intro()
FirstRun = False
else:
answer = raw_input()
if answer == "yes":
CoinToss()
raw_input("Do you want to flip again? (yes or no): ")
else:
exit()
As you simply ignore the return value of the raw_input method, you don't know what the user is entered in order to break out of the loop.
Here is a simplified version of your program, note how I store the result of the raw_input method in result and use that to control the execution loop:
import random
import time
result = raw_input('Hello and welcome to the coin flip game. Do you wish to flip a coin? (yes or no): ')
while result != 'no':
print('You flip the coin....')
time.sleep(1)
print('...and the result is...')
toss_result = random.randint(1,2)
if toss_result == 1:
print('Heads')
else:
print('Tails')
result = raw_input('Do you want to flip again? (yes or no): ')
print('Goodbye!')

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

How to run the code from start after calculation?

What if i want to ask the user whether he wants to perform another calculation or not everytime the user makes a calculation and gets the answer? I just want the code to run again from start everytime user performs calculation
var = int(raw_input("Enter 1,2,3 or 4 for add,subtract,multiplication,division respectively: "))
if var == 1:
print "You chose to add.Lets add!! :)"
def main ():
total = 0.0
while True:
number = float(raw_input('enter a number: '))
total+=number
if number == 0:
break
print "your answer is:",total
main()
elif var == 3:
print "You chose to multiply.Lets multiply!! :) "
def main ():
total = 1.0
while True:
number = float(raw_input('enter a number:'))
total*=number
if number == 1:
break
print "the answer is", total
main()
Just put
while True:
around the whole thing. This will continue looping indefinitely. If you want the user to be able to choose to end the program, try:
while True:
...
continue = raw_input("Continue? (Y/N) ")
if continue.lower in ("n", "no"):
break

Using a dictionary to choose scenes in a game, but it's not playing the correct scene. Why?

At the start, if a random integer = 1, it will play a random event. The random event should be selected (also randomly) from a dictionary containing each scene name. Instead, it doesn't try to access the other scenes. It only runs each method(function?) in the order written. What am I doing wrong? Is this a bad way to go about this?
I'm still learning, so any pointers are appreciated!
from random import randint
from time import sleep
class RandomEvent(object):
def __init__(self, wallet):
self.wallet = wallet
def old_man(self):
#insert art
print "\nExcuse me, I have an unusual request."
print "My horoscope tells me it's my lucky day,"
print "but I don't have any money."
print "\nIf you'll let me borrow some money, I"
print "promise to give you half of all the winnings."
print "Do we have a deal?"
give_money = raw_input("(y)es or (n)o? ")
if give_money.lower() == "y":
print "\nFunds: $", self.wallet
how_much = int(raw_input("How much money will you give? $"))
if how_much <= self.wallet:
how_much *= randint(2,3)
print "Haha! I won $%d! Here's your share of the money, kiddo." % (how_much*2)
self.wallet += how_much
else:
print "Eh, kids these days... no faith in their elders... (grumble grumble)..."
sleep(2)
print "\nA few moments later you see the old man hit the jackpot at a slot machine."
return self.wallet
def robber(self):
#insert art
print "\nPsssst! Hey, you!"
#sleep(1)
print "\nYou glance down to see a knife discreetly placed"
print "to your stomach."
#sleep(1)
print "\nHand over all your cash. No funny business."
print "\nFunds: $", self.wallet
how_much = int(raw_input("How much money will you give? $"))
lie_success = randint(1,3)
if how_much == self.wallet:
self.wallet = 0
print "\nNice doin' business with ya."
print "The robber quickly disappears into a nearby crowd,"
print "taking all your money with him."
if how_much != self.wallet and lie_success == 1:
self.wallet -= how_much
print "\nNice doin' business with ya."
print "The robber quickly disappears into a nearby crowd,"
print "taking your money with him."
else:
print "\nYou think you're a wise guy, eh?"
sleep(2)
print "\nYou are dead. GAME OVER"
sleep(2)
exit()
return self.wallet
def pretty_woman(self):
pass
###----------------------GAME CODE BELOW---------------
funds = 500
encounter = 1
while True:
if encounter == randint(1, 1): # 1,1 FOR TESTING
story = RandomEvent(funds)
scene_list = {1: story.old_man(), 2: story.robber(), 3: story.pretty_woman()}
funds = scene_list[2] #randint(1,3)] FOR TESTING
else:
print "\n\n\nWelcome to Dreams Casino."
print "Where would you like to go?"
print "(1) Slot Machines"
print "(2) Roulette Table"
print "(3) Leave the Casino"
print "\nFunds: $", funds
game_choice = int(raw_input("> "))
You're calling the functions when creating your dictionary:
scene_list = {1: story.old_man(), 2: story.robber(), 3: story.pretty_woman()}
Since you want scene_list[1] to refer to your function, pass the function:
scene_list = {1: story.old_man, 2: story.robber, 3: story.pretty_woman}