I'm creating a vending machine program that simulates the action through a loop that ends when the user enters 0 but it doesn't print "0 to cancel" in the output. I tried putting it at the top before the if statements but, I want to be able to enter an input after the if statements are printed. So how could I fix that?
It says that user_val is undefined when I equal it to 0 but I did define it at the bottom.
If someone could help please!
print("*********************************")
print("Welcome to Vending Machine Bravo!")
print("*********************************")
print("If you would like to make a selection, please insert the appropriate currency into the machine.")
# Currency deposit [tag:tag-name]
num_5Dollars = 5.00
num_Dollars = 1.00
num_Quarters = .25
num_Dimes = .10
num_Nickels = .05
num_Pennies = .01
currency = [num_5Dollars, num_Dollars, num_Quarters, num_Dimes, num_Nickels, num_Pennies]
if num_5Dollars == 5.00:
print("5.00 for $5 bills")
if num_Dollars == 1.00:
print("1.00 for $1 bills")
if num_Quarters == .25:
print(".25 for Quarters")
if num_Dimes == .10:
print(".10 for dimes")
if num_Nickels == .05:
print(".05 for nickels")
if num_Pennies == .01:
print(".01 for pennies")
if int(float(user_val)) == 0:
print("0 to cancel")
user_val = float(input())
Your user_val defined under the line if int(float(user_val)) == 0.
And if you want to say to user 0 to cancel, you don't need to check int(float(user_val)) == 0, because while this doesn't happened, it won't print this instruction.
So basically, you need to remove if int(float(user_val)) == 0: line
Related
I am getting an error that I don't understand in this short program. The errors read
Traceback (most recent call last):
line 40, in <module>
main()
line 35, in main
totalCost = cleanCost * sizeFactor
UnboundLocalError: local variable 'cleanCost' referenced before assignment
It says that cleanCost is not assigned, but I believe I did assign it in the set price based on cleaning type area unless I am mistaken. If that is not properly assigned how do I assign it so that the variable can change based on input?
def main():
#Display welcome message
print ("Hello, welcome to Hannah’s Cleaning Service!")
#prompt user for house size
houseSize = int(input("How many bedrooms is your home?"))
#prompt user for type of cleaning
cleanType = str(input("What type of cleaning would you like \n 1=floors, \n 2=windows, \n 3=bathrooms, or \n 4=dusting?"))
#set price based on cleaning type
if (cleanType == 1):
cleanCost = 60
elif (cleanType == 2):
cleanCost = 50
elif (cleanType == 3):
cleanCost = 40
elif (cleanType == 4):
cleanCost = 30
#set multiplication factor based on house size
if (houseSize <= 2):
sizeFactor = 1
elif (houseSize == 3):
sizeFactor = 2
elif (houseSize >= 4):
sizeFactor = 3
#Calculate total price
totalCost = cleanCost * sizeFactor
#Display total cost
print ("Your total is $totalCost")
main()
You are running into an issue of scope/visibility. Since in your initial iteration of the code, "cleaningCost" is going in and out of scope within the various "if" tests". Following, is a tweaked version of your code with the two work variables initialized.
def main():
#Display welcome message
print ("Hello, welcome to Hannah’s Cleaning Service!")
#prompt user for house size
houseSize = int(input("How many bedrooms is your home?"))
#prompt user for type of cleaning
cleanType = str(input("What type of cleaning would you like \n 1=floors, \n 2=windows, \n 3=bathrooms, or \n 4=dusting?"))
cleanCost = 0 # Need to be initialized at this scope level
sizeFactor = 1
#set price based on cleaning type
if (cleanType == "1"): # Need to be checked as alphanumeric values
cleanCost = 60
elif (cleanType == "2"):
cleanCost = 50
elif (cleanType == "3"):
cleanCost = 40
elif (cleanType == "4"):
cleanCost = 30
#set multiplication factor based on house size
if (houseSize <= 2):
sizeFactor = 1
elif (houseSize == 3):
sizeFactor = 2
elif (houseSize >= 4):
sizeFactor = 3
#Calculate total price
totalCost = cleanCost * sizeFactor
#Display total cost
print ("Your total is", totalCost)
main()
Also, note that I tweaked the "cleanType" tests to be alphanumeric tests since your input statement sets up variable "cleanType" as a string.
With those tweaks, following was some sample output on my terminal.
#Una:~/Python_Programs/Cleaning$ python3 Cleaning.py
Hello, welcome to Hannah’s Cleaning Service!
How many bedrooms is your home?4
What type of cleaning would you like
1=floors,
2=windows,
3=bathrooms, or
4=dusting?1
Your total is 180
The big take-away is the scope of variables. Give those tweaks a try.
I'm trying to develop a code for the zombie dice game.
My problem is when the first player replies that he doesn't want to continue playing.
The game ends and I can't get the second player to play. Can someone help me?
import random
print("========== ZOMBIE DICE (PROTÓTIPO SEMANA 4) ==========")
print("========= WELCOME TO THE ZOMBIE DICE GAME! ========")
numeroJogadores = 0
while numeroJogadores < 2:
numeroJogadores = int(input("Enter the number of players: "))
print(numeroJogadores)
if numeroJogadores < 2:
print("NOTICE: You must have at least 2 players to continue!")
listaJogadores = []
for i in range(numeroJogadores):
nome = str(input("\nEnter player name: " + str(i+1) + ": "))
listaJogadores.append(nome)
print(listaJogadores)
dadoVerde = ("brain", "steps", "brain", "shot", "steps", "brain")
dadoAmarelo = ("shot", "steps", "brain", "shot", "steps", "brain")
dadoVermelho = ("shot", "steps", "shot", "brain", "steps", "shot")
listaDados = [dadoVerde, dadoVerde, dadoVerde, dadoVerde, dadoVerde, dadoVerde,
dadoAmarelo, dadoAmarelo, dadoAmarelo, dadoAmarelo,
dadoVerde, dadoVermelho, dadoVermelho]
print("\nSTARTING THE GAME...")
jogadorAtual = 0
dadosSorteados = []
tiros = 0
cerebros = 0
passos = 0
while True:
print("PLAYER TURN: ", listaJogadores[jogadorAtual])
for i in range (3):
numeroSorteado = random.randint(0, 12)
dadoSorteado = listaDados[numeroSorteado]
if (dadoSorteado == dadoVerde):
corDado = "Green"
elif (dadoSorteado == dadoAmarelo):
corDado = "Yellow"
else:
corDado = "Red"
print("Dice Drawn: ", corDado)
dadosSorteados.append(dadoSorteado)
print("\nThe faces drawn were: ")
for dadoSorteado in dadosSorteados:
numeroFaceDado = random.randint(0,5)
if dadoSorteado[numeroFaceDado] == "brain":
print("- brain (you ate a brain)")
cerebros = cerebros + 1
elif dadoSorteado[numeroFaceDado] == "tiro":
print("- shot (you got shot)")
tiros = tiros + 1
else:
print("- steps (a victim escaped)")
passos = passos + 1
print("\nCURRENT SCORE: ")
print("brins: ", cerebros)
print("shots: ", tiros)
if cerebros >= 13:
print("Congratulations, you've won the game!")
break
elif tiros >= 3:
print("You lost the game!")
break
else:
continuarTurno = str(input("\nNOTICE: Do you want to continue playing dice? (y=yes / n=no)")).lower()
if continuarTurno == "n":
jogadorAtual = jogadorAtual + 1
dadossorteados = 0
tiros = 0
cerebros = 0
passos = 0
if jogadorAtual > numeroJogadores:
print("Finalizing the game prototype")
else:
print("Starting another round of the current turn")
dadossorteados = []
print("======================================================")
print("===================== END OF THE GAME ====================")
print("======================================================")
Does anyone know what I'm doing wrong?
I'm new as a programmer. If anyone knows how to help me with this problem, I would be grateful.
EDIT: Well now the code just works. I can switch players just fine, but if you go through all the characters it crashes again since jogadorAtual gets too big for listaJogadores. I don't quite understand the game, but assuming you want to start back with the first player, an elegant way you can accomplish that is by doing modulus with the % operator, which divides two numbers but returns the remainder. If you divide the number of players by the size of listaJogadores, you'll always get a number inside listaJogadores's range.
# Change this...
print("PLAYER TURN: ", listaJogadores[jogadorAtual])
# ...to this
print("PLAYER TURN: ", listaJogadores[jogadorAtual % len(listaJogadores)])
If that's not what you need for your game, let me know.
Original answer: Is the game ending or is it crashing? When I run the game, it always crashes with:
File "C:\Users\me\Desktop\Untitled-1.py", line 56, in <module>
diceDrawns.append(diceDrawn)
AttributeError: 'int' object has no attribute 'append'
This is because after looping, you try to do diceDrawns.append(), but you've already replaced the diceDrawns list with an integer on line 87. I'm not sure if you meant to replace diceDrawn instead, but that's definitely the source of the problem.
An unrelated note: You can do += as a shorthand way to increment a variable by a certain amount, so you can replace a lot of instances of things like currentPlayer = currentPlayer + 1 with currentPlayer += 1, and the same can be done with any operator, so you could also do things like -= or *=
I'm trying to create a program that checks whether the credit card number the user inputed is either invalid, or from AMEX, MASTERCARD, or VISA. I'm using Luhn's formula. Here is a site that contains the explanation to the formula I'm using: https://www.geeksforgeeks.org/luhn-algorithm/
It works with all credit card numbers, except credit cards from AMEX. Could someone help me?
Here is my code:
number = input("Number: ")
valid = False
sumOfOdd = 0
sumOfEven = 0
def validation(credit_num):
global sumOfOdd
global sumOfEven
position = 0
for i in credit_num:
if position % 2 != 0:
sumOfOdd += int(i)
else:
product_greater = str(int(i) * 2)
if len(product_greater) > 1:
sumOfEven += (int(product_greater[0]) + int(product_greater[1]))
else:
sumOfEven += int(product_greater)
position += 1
def main():
if (sumOfOdd + sumOfEven) % 10 == 0:
if number[0] == "3":
print("AMEX")
elif number[0] == "5":
print("MASTERCARD")
else:
print("VISA")
else:
print("INVALID")
print(f"{sumOfOdd + sumOfEven}")
validation(number)
main()
Here are some credit card numbers:
VISA: 4111111111111111
MASTERCARD: 5555555555554444
AMEX: 371449635398431
I've found many different ways to calculate this formula, but I'm not sure if mine is correct.
I'm new in python, and I'm trying to make a simple quit, if the Input is empty or less then One int.
I'm getting an error which says - ValueError: invalid literal for int() with base 10: '', when entering nothing, just a enter on launch.
import sys
import os
import getpass
def clear(): return os.system('clear')
ballance = 500.00
# Garage Stockas
Wood_InStock = 600
Weed_InStock = 300
Gun_InStock = 15
Gun_Ammo_InStock = 500 * 30 # X30 Total 15000
# Kainos
Gun_Ammo_Price = 15.50
Wood_Price = 3.50
Weed_Price = 9.50
Gun_Price = 250.50
# Produktai
medis = '~ Elemental Wood ~'
weed = '~ Indoor Kush ~'
gun = '~ Shotgun ~'
gun_ammo = '~ Shotgun ammo 30x ~'
# Inventory
Wood_Inventory = 0
Weed_Inventory = 0
Gun_Inventory = 0
Gun_Ammo_Inventory = 0
# No Money
Not_Enough_Money = '~ Sorry you dont have enough money'
while True:
Shop_Pasirinkimas = int(input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun)))
if len(Shop_Pasirinkimas) < 1:
sys.exit("SOrry")
elif Shop_Pasirinkimas == 1:
clear()
WoodPirkimo_Skaic = int(input("How much {medis} would you like to buy? ".format(medis=medis) + "Wood Now in Stock - {woodins}\n".format(woodins=Wood_InStock)))
# Price per wood - 3.50
ballance -= ( Wood_Price * WoodPirkimo_Skaic)
Wood_Inventory += WoodPirkimo_Skaic
Wood_InStock -= WoodPirkimo_Skaic
print("~ In stock of {}, left {}".format(medis,Wood_InStock))
print("~ Successfully bought {}, Your Ballance is {}\n".format(medis,ballance))
print('Inventory:')
print("~ You have {}, of {}\n".format(Wood_Inventory,medis))
Buymore = input("Would you like to buy anything more?... Yes/No\n")
if "Yes" in Buymore or "yes" in Buymore:
continue
elif "No" in Buymore or "no" in Buymore:
break
else:
break
Let's look at only this part of the code:
while True:
Shop_Pasirinkimas = int(input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun)))
if len(Shop_Pasirinkimas) < 1:
sys.exit("SOrry")
The empty user input will be passed to int(), but an empty string cannot be converted to an int! So an error is raised.
What you should instead is to not convert the input to int first, and treat it as a string:
while True:
Shop_Pasirinkimas = input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun))
if len(Shop_Pasirinkimas) < 1:
sys.exit("SOrry")
elif int(Shop_Pasirinkimas) == 1: # convert to int here
clear()
...
int(x,base) function will return the integer object from any number or string. Base defaults to 10. If x is the string, its respective numbers should be within possible values with respect to that base.
As, nothing is entered, it's considered as invalid literal.
Hence, Please use the input as string which can solve the issue easily.
If user doesn't input an integer you will encounter an exception in Shop_Pasirinkimas = int(input(...)). Besides int has no len() so this will also cause error len(Shop_Pasirinkimas). You can do the following to accomplish what you are trying
while True:
try:
Shop_Pasirinkimas = int(input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun)))
if Shop_Pasirinkimas < 1:
sys.exit("SOrry")
elif Shop_Pasirinkimas == 1:
clear()
WoodPirkimo_Skaic = int(input("How much {medis} would you like to buy? ".format(medis=medis) + "Wood Now in Stock - {woodins}\n".format(woodins=Wood_InStock)))
# Price per wood - 3.50
ballance -= ( Wood_Price * WoodPirkimo_Skaic)
Wood_Inventory += WoodPirkimo_Skaic
Wood_InStock -= WoodPirkimo_Skaic
print("~ In stock of {}, left {}".format(medis,Wood_InStock))
print("~ Successfully bought {}, Your Ballance is {}\n".format(medis,ballance))
print('Inventory:')
print("~ You have {}, of {}\n".format(Wood_Inventory,medis))
Buymore = input("Would you like to buy anything more?... Yes/No\n")
if "Yes" in Buymore or "yes" in Buymore:
continue
elif "No" in Buymore or "no" in Buymore:
break
else:
break
except ValueError:
sys.exit("SOrry")
Ok I have a feeling that this is a simple simple issue but I have been staring at this code for about 10 hours now.
The issue I am having is in mastermind is that once I get it to recognize that I have the correct colors in the right spot I can get it to display the right spots with X and the wrong spots with O. I need to be able to convert that so instead of X and O I need it to tell the user that he/she has 2 blacks and one white
For example: The secret code is RGYB The user enters RGOY so then Python relays "You have 2 blacks(The R and G spots) and one 1 White (The Y because it's the right color just in the wrong index) As of right now I got it to display X for the right color in the right spot and anything else it is an O
I will post what I have been working with now but today I am at my wit's end
https://pastebin.com/HKK0T7bQ
if correctColor != "XXXX":
for i in range(4):
if guess[i] == tempCode[i]:
correctColor += "X"
if guess[i] != tempCode[i] in tempCode:
correctColor += "O"
print (correctColor + "\n")
if correctColor == "XXXX":
if attempts == 1:
print ("You think you are sweet because you got it right on the first try? Play me again!")
else:
print ("Well done... You needed " + str(attempts) + " attempts to guess.")
game = False
A few comments
X and O
you use X and 0 to denote the success, it will be easier and faster to use a list or tuple or booleans for this, that way you can use sum() to count how many colors and locations were correct. Then whether you represent that with X and O or red and white pins is a matter for later
compartmentalization
Your game logic (guess input, input validation, do you want to continue, etc) is mixed with the comparison logic, so it would be best to separate the different functions of your program into different methods.
This is an fineexample to introduce object oriented programming, but is so simple it doesn't need OO, but it can help. What you need is a method which takes a series of colours and compares it to another series of colours
Standard library
Python has a very extended standard library, so a lot of stuff you want to do probably already exists
Correct colours
to count the number of letters which occur in 2 strings, you can use collections.Counter
guess = "RGOY "
solution = "RGYB"
a = collections.Counter(guess)
b = collections.Counter(solution)
a & b
Counter({'G': 1, 'R': 1, 'Y': 1})
correct_colours = sum((a & b).values())
3
So the user guessed 3 colours correctly
Correct locations
can be solved with an easy list comprehension
[g == s for g, s in zip(guess, solution)]
[True, True, False, False]
sum(g == s for g, s in zip(guess, solution))
2
so the used put 2 colours on the correct location
This is a MasterMind I made in Python. Hope you like it and it helped you! :)
import random
import time
from tkinter import *
def select_level():
global level
level = level_selector.get()
root.destroy()
root = Tk()
level_selector = Scale(root, from_=1, to=3, tickinterval=1)
level_selector.set(0)
level_selector.pack()
Button(root, text="Select a difficulty level", command=select_level).pack()
mainloop()
cpc_1_digit = 0
cpc_2_digit = 0
cpc_3_digit = 0
cpc_4_digit = 0
p_1_digit = 0
p_2_digit = 0
p_3_digit = 0
p_4_digit = 0
correct_correct = 0
correct_wrong = 0
chances = 0
if level == 1:
chances = 15
elif level == 2:
chances = 10
else:
chances = 7
cpc_1_digit = random.randint(0, 9)
while cpc_2_digit == cpc_1_digit or cpc_2_digit == cpc_3_digit or cpc_2_digit ==
cpc_4_digit:
cpc_2_digit = random.randint(0, 9)
while cpc_3_digit == cpc_1_digit or cpc_3_digit == cpc_2_digit or cpc_3_digit ==
cpc_4_digit:
cpc_3_digit = random.randint(0, 9)
while cpc_4_digit == cpc_1_digit or cpc_4_digit == cpc_2_digit or cpc_4_digit ==
cpc_3_digit:
cpc_4_digit = random.randint(0, 9)
while chances > 0:
correct_correct = 0
correct_wrong = 0
answer = input("Enter a four-digit number with different digits (e.g 1476): ")
p_1_digit = int(answer[0])
p_2_digit = int(answer[1])
p_3_digit = int(answer[2])
p_4_digit = int(answer[3])
if p_1_digit == cpc_1_digit:
correct_correct = int(correct_correct) + 1
elif p_1_digit == cpc_2_digit or p_1_digit == cpc_3_digit or p_1_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_2_digit == cpc_2_digit:
correct_correct = correct_correct + 1
elif p_2_digit == cpc_1_digit or p_2_digit == cpc_3_digit or p_2_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_3_digit == cpc_3_digit:
correct_correct = int(correct_correct) + 1
elif p_3_digit == cpc_1_digit or p_3_digit == cpc_2_digit or p_3_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_4_digit == cpc_4_digit:
correct_correct = int(correct_correct) + 1
elif p_4_digit == cpc_1_digit or p_4_digit == cpc_3_digit or p_4_digit ==
cpc_2_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
print("")
if int(correct_correct) == 4:
print("Congratsulations! You found the computer's number!")
break
elif int(correct_wrong) > 0 or int(correct_correct) >= 1 and int(correct_correct)
< 4:
print("You got " + str(correct_correct) + " correct digit(s) in the correct
place, and " + str(correct_wrong) + " correct digit(s) but in wrong place.")
elif int(correct_correct) == 0 and int(correct_wrong) == 0:
print("You didn't guess any number, try again!")
else:
raise Exception("CheckError: line 69, something went wrong with the
comparings.")
exit()
print("")
chances = chances - 1
if chances == 0:
print("You lost... The secret number was " + str(cpc_1_digit) + str(cpc_2_digit)
+ str(cpc_3_digit) + str(cpc_4_digit) + ". Try again by rerunning the program.")
time.sleep(4)