I just started making a game like thing, and for some reason, the elif loop isn't doing anything when "upgrade" is entered.
choclate = 0
multiplier = 1
multipliercost = 10
x = 1
while x == 1:
if input() == (("choclate") + str(choclate+multiplier)):
choclate = choclate+multiplier
print("\nYou now have " + str(choclate) + " choclate.\nMultiplier Upgrade Cost: " + str(multipliercost) + " choclate\n")
elif input() == "upgrade":
multiplier = multiplier*2
choclate = choclate-multipliercost
multipliercost = multipliercost*2.5
print("You have upgraded your multiplier to " + str(multiplier))
I am very new to coding, so I don't really know what to call this problem.
If you call input() twice, then the user needs to key in twice in each round.
if you expect the user to key in only once, then you also need to call input() once in each round, and store it into a variable.
Here is the fix.
choclate = 0
multiplier = 1
multipliercost = 10
x = 1
while x == 1:
# save the input into variable
key_in = input()
print(("choclate") + str(choclate+multiplier))
if key_in == (("choclate") + str(choclate+multiplier)):
choclate = choclate+multiplier
print("\nYou now have " + str(choclate) + " choclate.\nMultiplier Upgrade Cost: " + str(multipliercost) + " choclate\n")
elif key_in == "upgrade":
multiplier = multiplier*2
choclate = choclate-multipliercost
multipliercost = multipliercost*2.5
print("You have upgraded your multiplier to " + str(multiplier))
Related
I'm making a small program that shoots out math problems and requires an answer to pass. It works fine, but all the randint values I generate stay static for as long as the progran is running. I figured if I change:
Tehtävä = random.choice(Laskut)
Into a function it should refresh with the loop. Problem is I can't for the life of me figure out how to do that. Would it even work for what I'm trying? The randint values are determined in a seperate list. Heres the rest of the code:
Peli = 1
while Peli != 2:
pulma = 1
refresh = 1
Tehtävä = random.choice(Laskut)
while pulma == 1:
ratkaisu = float(input(Tehtävä.problem + "\n:"))
if ratkaisu == Tehtävä.answer:
pulma += 1
refresh += 1
print("oikein")
elif ratkaisu == "loppu":
pulma += 1
refresh += 1
Peli += 1
else:
print("väärin")
Here are the values I used:
import random
class Algebra:
def __init__(self, problem, answer):
self.problem = problem
self.answer = answer
#Muuttujat
#erotus ja summa
a = random.randint(1,99)
b = random.randint(1,99)
c = random.randint(1,99)
d = random.randint(1,99)
#jako ja kerto
e = random.randint(1,10)
f = e*random.randint(1,10)
g = random.randint(1,10)
#Kysymykset
Kysymys_M = [str(a) + "+" + str(b) + "-x=" + str(c),
str(a) + "-" + str(b) + "-x=" + str(a),
str(a) + "-" + str(b) + "-" + str(c) + "-x=" + str(d),
str(e) + "*x=" + str(f),
str(f) + ":x=" + str(e),
"x:" + str(e) + "=" + str(g)]
#Vastaukset
Vastaus_M = [a+b-c,
-b,
a-b-c-d,
f/e,
f/e,
e*g]
Laskut = [
Algebra(Kysymys_M[0], Vastaus_M[0]),
Algebra(Kysymys_M[1], Vastaus_M[1]),
Algebra(Kysymys_M[2], Vastaus_M[2]),
Algebra(Kysymys_M[3], Vastaus_M[3]),
Algebra(Kysymys_M[4], Vastaus_M[4]),
Algebra(Kysymys_M[5], Vastaus_M[5]),]
(If I have packed too much information please let me know.)
So for my python class, we’ve been instructed to create a for loop that will ask the user to input a quantity of an item sold, where the string literal is supposed to be “Quantity of item 1: ” and so on, for a total of 5 different items. Then it calculates the price of the item * the quantity and comes up with a total for each SEPERATE item. The gimmick is that we can’t use lists and it HAS to be a for loop. The professor also gave us a hint that we’ll be using if/else/elif statements.
The code I’ve come up with so far is
for x in range(1,6):
quantity = int(input("quantity of item " +str(x)+ " : "))
if x == 1:
total = quantity * 2.50
elif x == 2:
total = quantity * 1.98
elif x == 3:
total = quantity * 5.75
elif x == 4:
total = quantity * 3.45
elif x == 5:
total = quantity * 4
print(quantity)
The problem with this code is that it only prints the totals of the last elif statement. I’m trying to refrain from making too many variables as that would defeat the purpose of the loop.
Hi and welcome to Stack Overflow!
Probably what you're missing is that = operator override whatever was in that variable before, so everytime you do total = something, total gets overridden to something.
Probably what you want to use is +=, which will add to total what you want.
You want to use += rather than just = because = overwrites what was previously in the variable when you want to keep the total sum.
You also made a mistake with the print statement. Presumably you want the total, but the variable you have in the print is quantity.
See the working code below.
total = 0
for x in range(1,6):
quantity = int(input("quantity of item " +str(x)+ " : "))
if x == 1:
total += quantity * 2.50
elif x == 2:
total += quantity * 1.98
elif x == 3:
total += quantity * 5.75
elif x == 4:
total += quantity * 3.45
elif x == 5:
total += quantity * 4
print(total)
for x in range(1,6):
quantity = int(input("quantity of item " + str(x)+ " : "))
if x == 1:
total = quantity * 2.50
Print("quantity: " + str(x) + " Total: " + str(total))
elif x == 2:
total = quantity * 1.98
Print("quantity: " + str(x) + " Total: " + str(total))
elif x == 3:
total = quantity * 5.75
Print("quantity: " + str(x) + " Total: " + str(total))
elif x == 4:
total = quantity * 3.45
Print("quantity: " + str(x) + " Total: " + str(total))
elif x == 5:
total = quantity * 4
Print("quantity: " + str(x) + " Total: " + str(total))
The reason why your code only prints the last item because you didn't save the previous values. When you assigned quantity equal to a variable that changes each loop, it replaces the previous value.
for example:
for i in range(3):
num = i
print(num)
Because num will be replaced by the next value in this loop. We know the last value in range(3) is 2.
Since print statement is outside of for loop, it does not get affected by the loop and only print the last value which again is 2.
If you want all of them in one string, you can concatenate them into a string by first declaring a variable assign to an empty string where you can store the values. See below:
for x in range(1,6):
FinalOutput = ""
quantity = int(input("quantity of item " + str(x)+ " : "))
if x == 1:
total = quantity * 2.50
FinalOutput += "Quantity: " + str(x) + " Total: " + str(total) + " , "
elif x == 2:
total = quantity * 1.98
FinalOutput += "Quantity: " + str(x) + " Total: " + str(total) + " , "
elif x == 3:
total = quantity * 5.75
FinalOutput += "Quantity: " + str(x) + " Total: " + str(total) + " , "
elif x == 4:
total = quantity * 3.45
FinalOutput += "Quantity: " + str(x) + " Total: " + str(total) + " , "
elif x == 5:
total = quantity * 4
FinalOutput += "Quantity: " + str(x) + " Total: " + str(total) + " , "
print(FinalOutPut)
I'm new to python, and I'm trying here to make some math, in Quanity, and balance. But that function in define, don't do anything to balance, and quanity. When I print them they are still the stock.
Ballance = 7000 # 7K DEMO
# SANDELYS
Indica_WEED_QUANITY = 600
AMAZON_QUANITY = 18
STEAM_GIFT50_QUANITY = 4
# Price
STEAM_GIFT50_PRICE_PER1 = 50 # Each
Indica_WEED_PRICE_PER1 = 8
Amazon_Prime_PRICE_PER1 = 25 # Each
def PickForShopItem():
ShopPick = int(input("~ PRODUCT ID = "))
if ShopPick == 1:
clear()
while True:
Pasirinxm = input("Would You like to continue buying ~ Indica WEED KUSH * ?\n* Y/N: ")
if "Y" in Pasirinxm or "y" in Pasirinxm:
clear()
BuyKiekis = int(input("~ How many you would to buy of " + Indica_WEED_NAME + "?\n "))
Indica_WEED_QUANITY - BuyKiekis # Atimam Ir paliekam sandari mazesni
Bendra_Suma = ( BuyKiekis * Indica_WEED_PRICE_PER1)
print(Bendra_Suma)
Ballance = 500
print(Ballance - Bendra_Suma)
print("Sandelio Kiekis po pirkimo " + str(Indica_WEED_QUANITY))
print(Ballance)
break
elif "N" in Pasirinxm or "n" in Pasirinxm:
print("xuine iseina")
break
elif " " in Pasirinxm or len(Pasirinxm) < 1:
print("PLease dont do shit")
continue
break
elif ShopPick == 2:
print("Darai")
elif ShopPick == 3:
print("hgelo")
Indica_WEED_NAME = "~ Indica WEED KUSH *
I think the problem you have is that:
Indica_WEED_QUANITY - BuyKiekis
does not update the variable "Indica_WEED_QUANITY" (and you have the same problem in the line print(ballance - BendraSuma))
In Python, that statement will just work out a value, but you aren't telling the program to save or store it anywhere. Do this:
Indica_WEED_QUANITY = Indica_WEED_QUANITY - BuyKiekis
Python also allows you to do this with a -= operator:
Indica_WEED_QUANITY -= BuyKiekis
will update Indica_WEED_QUANITY by subtracting the BuyKeikis amounts.
I am working on a Hangman game, but I am having trouble replacing the dashes with the guessed letter. The new string just adds on new dashes instead of replacing the dashes with the guessed letter.
I would really appreciate it if anyone could help.
import random
import math
import os
game = 0
points = 4
original = ["++12345","+*2222","*+33333","**444"]
plusortimes = ["+","*"]
numbers = ["1","2","3"]
#FUNCTIONS
def firstPart():
print "Welcome to the Numeric-Hangman game!"
def example():
result = ""
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
return ori
# def actualGame(length):
#TOP LEVEL
firstPart()
play = raw_input("Do you want to play ? Y - yes, N - no: ")
while (play == "Y" and (points >= 2)):
game = game + 1
points = points
print "Playing game #: ",game
print "Your points so far are: ",points
limit = input("Maximum wrong guesses you want to have allowed? ")
length = input("Maximum length you want for the formulas (including symbols) (must be >= 5)? ")
result = "" #TRACE
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
test = eval(result[:-1])
v = random.choice(plusortimes) #start of randomly generated formula
va = random.choice(plusortimes)
formula = ""
while (len(formula) <= (length - 3)):
formula = formula + random.choice(numbers)
formula2 = str(v + va + formula)
kind = ""
for i in range(2,len(formula2)):
if i % 2 == 0:
kind = kind + formula2[i] + formula2[0]
else:
kind = kind + formula2[i] + formula2[1]
formula3 = eval(kind[:-1])
partial_fmla = "------"
print " (JUST TO TRACE, the program invented the formula: )" ,ori
print " (JUST TO TRACE, the program evaluated the formula: )",test
print "The formula you will have to guess has",length,"symbols: ",partial_fmla
print "You can use digits 1 to 3 and symbols + *"
guess = raw_input("Please enter an operation symbol or digit: ")
a = 0
new = ""
while a<limit:
for i in range(len(formula2)):
if (formula2[i] == partial_fmla[i]):
new = new + partial_fmla[i]
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
a = a+1
print new
guess = raw_input("Please enter an operation symbol or digit: ")
play = raw_input("Do you want to play ? Y - yes, N - no: ")
The following block seems problematic:
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
Python does not allow modification of characters within strings, as they are immutable (cannot be changed). Try appending the desired character to your new string instead. For example:
elif formula2[i] == guess:
new += guess
else:
new += '-'
Finally, you should put the definition of new inside the loop directly under, as you want to regenerate it after each guess.
So I have to create a game of craps that takes into account bets for an assignment. So far, my code works in that the dice rolls are correct and other little tidbits the assignment called for. But now I don't know how to record each game as a win / lose for the player or computer so that the pot can be added to the winner's money. I realize that my code is half doe, isn't finished, and doesn't run as is, but I just seriously need some help from someone. Please and thank you. Here are more specific directions on my assignment:
http://www.ics.uci.edu/~kay/courses/i42/hw/labA.html
import random
def craps():
print("Welcome to Sky Masterson's Craps Game")
handle_commands()
def handle_commands(): # Collection -> Collection (plus interaction)
""" Display menu to user, accept and process commands
"""
playerInitial = 500
compInitial = 500
MENU = "How much would you like to bet?: "
while True:
bet = float(input(MENU))
if bet <= playerInitial:
human_game()
elif bet > playerInitial:
print("Sorry, you can't bet more than you have")
def handle_commands2():
MENU2 = "Would you like to play again? (y or n): "
while True:
response = input (MENU2)
if response=="y":
counter = counter + multipleGames()
elif response=="n":
while ( counter < 2000):
roll = random.randint(1, 6) + random.randint(1,6)
updateCount(roll)
counter += 1
print ("Thank you for playing." + "\n" + "\n" + "Distribution of dice rolls: " + "\n")
return
else:
invalid_command(response)
def invalid_command(reponse):
"""print message for invalid menu command.
"""
print("Sorry; '" + response + "' isn't a valid command. Please try again.")
def play_game():
"""prints shooters roll results
"""
diceRoll = 0
roll = random.randint(1, 6) + random.randint(1, 6)
updateCount(roll)
diceRoll = diceRoll + 1
point = 0
print("The roll is " + str(roll))
response = (roll)
if response== 7 or response== 11:
print("Natural; shooter wins" + "\n" + "Thank you for playing")
handle_commands2()
elif response== 2 or response== 3 or response== 12:
print("Crapped out; shooter loses" + "\n" + "Thank you for playing")
handle_commands2()
else:
print("The point is " + str(roll))
point = roll
secondRoll = 0
handle_commands()
while (secondRoll !=point) and (secondRoll != 7):
secondRoll = random.randint(1, 6) + random.randint(1, 6)
updateCount(secondRoll)
diceRoll += 1
print("The roll is " + str(secondRoll))
handle_commands()
if secondRoll== point:
print ("Made the point; shooter wins." + "\n" + "Thank you for playing")
handle_commands2()
elif (secondRoll == 7):
print ("Crapped out; shooter loses." + "\n" + "Thank you for playing")
handle_commands2()
return diceRoll
def multipleGames():
gameCounter = 0
while (gameCounter <= 2000):
print("Your game: ")
gameCounter += play_game()
print("\n")
print("Computer's game: ")
gameCounter += play_game()
print( "\n")
return gameCounter
def updateCount(point):
count =List[point] + 1
List[point] = count
List = {2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0}
def human_game():
playerInitial = 500
compInitial = 500
while True:
play_game()
if
playerInitial += bet
compInitial += bet
counter = 0
counter = counter + multipleGames()
playerInitial -= bet
craps()
for point in List:
print("%2d" %(point) + ": " + "%3d" %(List[point]) + " " + "(" + ("%2d" % (int((List[point])/2000*100)))+ "%" + ")" + " " + ("*" *(int((List[point])/2000*100))))
Use classes:
import random
class Human:
def __init__(self):
self.name = 'Human'
self.wins = []
self.losses = []
self.bets = []
self.total = 0
class Computer:
def __init__(self):
self.name = 'Computer'
self.wins = []
self.losses = []
self.bets = []
self.total = 0
class Game:
def __init__(self):
self.rolls = []
self.currentPlayer = None
def roll(self):
self.rolls.append(random.randint(1, 6))
if __name__ == '__main__':
human = Human()
computer = Computer()
game = Game()
game.roll()
print games.rolls
I won't code all of it for you, but using classes will make things much simpler.