Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to use an achievement system in my game. The game is like cookie clicker except you type and enter the letter "L" over and over and can upgrade the effect done by each type. I am trying to make it so when you get a certain amount of coins, like 1000, it will display that you have achieved the 1000 coins achievement, however it doesn't seem to work. Here is the code:
if coins == 1000:
print("")
print("You have a new achievement!")
print("[✔] - Earn 1,000 points")
print("You have 1/6 coin achievements")
print("")
if coins == 10000:
print("")
print("You have a new achievement!")
print("[✔] - Earn 10,000 points")
print("You have 2/6 coin achievements")
print("")
Your specific problem is that you're using the wrong comparator. If you use ==. you're checking if the value exactly equals. You're interested in when a player "achieves" the value, so switch your comparators out for >=. That way, when a player goes from 980 to 1001 points, 1001 >= 1000 evaluates to True.
Note this will print the text every time you check, even if they've already got the achievement, so perhaps something like the following would be useful:
has_1000_achievement = False
has_10000_achievement = False
if coins >= 1000 and not has_1000_achievement:
has_1000_achievement = True
print("")
...
The solution provided by P i would undoubtedly work, but I believe it's not something you're ready to fluently understand at your current level.
Edit: After the OP added a comment the question got a little more clear to me. Maybe you could try the following (which is of course just an example as the OP did not provide a minimal running peace of code):
# -*- coding: utf-8 -*-
numCoinAchievements = 0
nextCoinLevel = 1000
for coins in range(0, 100000, 33):
if coins >= nextCoinLevel:
numCoinAchievements += 1
if numCoinAchievements == 1:
nextCoinLevel = 10000
elif numCoinAchievements == 2:
nextCoinLevel = 15000
else:
break
print("")
print("You have a new achievement!")
print("[✔] - Earn %d points" % nextCoinLevel)
print("You have %d/6 coin achievements" % numCoinAchievements)
print("")
Of course you have to adept the code to your needs, but it should make the problem clear!
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 months ago.
Improve this question
I'm trying to do a number guessing game where the computer selects a random number and you have to guess it and get an output that's either: Your number is too high, too low or correct number + needed attempts.
However with this code:
import numbers
from random import randint
#set x to a random number between 1 and 50
randomnummer = randint(1,51)
print (randomnummer)
#counter = 0
#ask to input a number between 1 and 50 and check if input is valid
def nummer_eingabe():
usernummer = (input("Please enter a number between 1 and 50: "))
usernummer = int(usernummer)
#counter = counter + 1
if usernummer >= 1 and usernummer <= 50:
return usernummer
else:
print("Pleae enter a valid number.")
return nummer_eingabe()
#declare number from function
checked_user_nummer = nummer_eingabe()
#define counter
counter = 0
while checked_user_nummer != randomnummer:
counter += 1
if checked_user_nummer > randomnummer:
print("You need to guess lower. Try again :)")
nummer_eingabe()
continue
elif checked_user_nummer < randomnummer:
print("You need to guess higher. Try again :)")
nummer_eingabe()
continue
elif checked_user_nummer == randomnummer:
strcounter = str(counter)
print("Nice! You needed " + strcounter + " tries to find the right number")
break
#dont allow console to close right away
input()
it goes well until it gets stuck giving the same feedback (either too high or too low)
How do I get out of the While loop? I tried changing up the continue statement with a break but that just causes the code to stop after the second time the input was given.
Also please dont mind the print(randomnummer) on line 5; that's just for debugging purposes.
You never reassign the variable. You call nummer_eingabe() but you discard the result.
You're now in a stage where you no longer want to debug your code using print() statements but learn how to debug small programs.
Make sure you don't write code in Notepad and use a decent IDE like Pycharm instead. Set a breakpoint wherever your code gets stuck (just click left of the code and right of the line number)
and hit the little bug icon to debug it. You will be able to see the variables on the go. After each single line of code, check if they match your expectation
After entering a value of 10, you'll see that the variable is still 50 - a clear indicator that the value did not get updated because you didn't make use of the return value of the function.
Don't call the function again on the while, instead do a while to check for a "trigger" and then use your while checked_user_number != randomnummer:
Then instead of break use the trigger = False and end the while.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Below is my first python program. I am trying idea not yet covered in class as i hate staying stagnant and want to solve issues that may arise if i were to just use the info we've learned in class. As for my question, the program works but what were be ways to condense the code, if any? Thanks!
#This is a program to provide an itemized receipt for a campsite
# CONSTANTS
ELECTRICITY=10.00 #one time electricity charge
class colors:
ERROR = "\033[91m"
END = "\033[0m"
#input validation
while True:
while True:
try:
nightly_rate=float(input("Enter the Basic Nightly Rate:$"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter the Dollar Amount"+colors.END)
else:
break
while True:
try:
number_of_nights=int(input("Enter the Number of Nights You Will Be Staying:"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter a Number"+colors.END)
else:
break
while True:
try:
campers=int(input("Enter the Number of Campers:"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter a Number"+colors.END)
else:
break
break
#processing
while True:
try:
campsite=nightly_rate*number_of_nights
tax=(ELECTRICITY*0.07)+(campsite*0.07)
ranger=(campsite+ELECTRICITY+tax)*0.15 #gratuity paid towards Ranger
total=campsite+ELECTRICITY+tax+ranger #total paid per camper
total_per=total/campers
except ZeroDivisionError: #attempt to work around ZeroDivisionError
total_per=0 #total per set to zero as the user inputed 0 for number-
break #-of campers
#Output #Cant figure out how to get only the output colored
print("Nightly Rate-----------------------",nightly_rate)
print("Number of Nights-------------------",number_of_nights)
print("Number of Campers------------------",campers)
print()
print("Campsite--------------------------- $%4.2f"%campsite)
print("Electricity------------------------ $%4.2f"%ELECTRICITY)
print("Tax-------------------------------- $%4.2f"%tax)
print("Ranger----------------------------- $%4.2f"%ranger)
print("Total------------------------------ $%4.2f"%total)
print()
print("Cost Per Camper------------------- $%4.2f"%total_per)
The else in try statement is unnecessary. You can just put the break in the the end of the try statement. REF
In the end, in the print statements, I recommend you to use another types of formatting. You can use '...{}..'.format(..) or further pythonic is f'...{val}'. Your method is the oldest. More ref
You can remove both the outer while loops, as break is seen there at the top level, so the loops runs once only.
You can convert colors to an Enum class if desired (this is more of a stylistic choice tbh)
The line tax=(ELECTRICITY*0.07)+(campsite*0.07) can be represented as x*0.07 + y*0.07, which can be simplified to 0.07(x+y) or 0.07 * (ELECTRICITY + campsite) in this case.
Instead of manually padding the - characters in the print statements, you can use f-strings with simple formatting trick.
For example, try this out:
width = 40
fill = '-'
tax = 1.2345
print(f'{"Tax":{fill}<{width}} ${tax:4.2f}')
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I've been wonder how to clean up code to make my code easier and more readable for others reviewing my code. I'm fairly new to python, so I write everything into functions instead of using classes. Should I use more classes to better understand python more? I know that if the code works then it doesn't matter the way you did it but I just want to learn how to decrease my lines of code.
def paymentData():
calculateTotal = {}
remainingAmount = []
balance = int(raw_input('What is the balance of your bank account? \n'))
amount = int(raw_input('What is the amount you would like to subtract? \n'))
calculateTotal[balance]=amount
total = balance - amount
print('your total is: ' + str(total))
remainingAmount.append(total)
while True:
choice = raw_input('To continue press "Enter" or type "q" to exit (For options type "o"). \n')
if choice == '':
clearScreen()
paymentData()
break
elif choice.lower() == 'q':
clearScreen()
menuBudget()
break
elif choice.lower() == 'o':
return calculateTotal, remainingAmount
clearScreen()
options_menu()
break
else:
print('Invalid value.')
continue
This is a function from one of my programs that is a budget program that takes the value balance that the user puts in and subtracts it from the amount value.
This function calls three different functions, one of them being clearScreen() that clears the terminal:
def clearScreen(numlines=100):
if os.name == "posix":
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
os.system('CLS')
else:
print('\n' * numlines)
The options_menu() function that tells you the results of all the amount you put in (This is not completed nor do I plan to complete this project).
def options_menu():
print('Do you want to see all of you total amounts?\n(Enter 1 for Yes, 2 for no.)')
choice = int(raw_input())
if choice == 1:
time.sleep(3)
elif choice == 2:
menuBudget()
else:
print('Invalid Response.')
and the `menuBudget()` function that is the main menu for this script:
def menuBudget(): # this is a menu for budget fast.
menuRunning = True
while menuRunning:
print("""
1. payment calculator.
2. Comming Soon.
3. Comming Soon.
4. Exit/Quit.
""")
ans = input('Pick on the options above.\n')
if ans == 1:
clearScreen()
paymentData()
break
elif ans == 2:
print('Comming soon!')
continue
elif ans == 3:
print('Comming soon!')
continue
elif ans == 4:
break
else:
print('Unknown Option Seleted!')
continue
The use of classes means the use of OOP (Oriented Object Programmation). Sometimes your code will be very simple and doesn't need the use of classes. This paradigm depends of the type of project you want to build.
If you use imperative programmation, the best practice is to use functions as you're doing. If you want to improve your code, here are some tips :
Use meanful variable names
Use meanful function names
Sort your code into many files, feel free to have as much as you need. Try to call them once more with meanful names.
Simplify your code as much as needed, and use python libraries functions (this comes with experience). For example, use the max() function instead for re-write other functions.
Add comments to your code to make it re-usable even after month
Feel free to update this answer with other good-programmation pattern !
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to create a simple AI program which plays stick game. The problem is that I would like to subtract chosen stick from the total stick number. This simple code shows some error such as nonexisting value. I could not assign returning value for my values. Is there another way to subtracts value with functions?
import random
msg = input('Determine stick numbers:')
print('Stick number is determined as:', msg)
# First player move
def robot(stick):
y = stick % 4
if y==0:
y=randint(1,3)
mov=int(y)
print('machine chose:', mov)
total = stick-mov
return total
def human(stick2):
mov2= int(input('your turn:'))
print('human chose:', mov2)
total = stick2-mov2
return total
players= {
'1': robot,
'2': human
}
number1= input('Determine first player machine(1) or human(2):')
number2= input('Determine second player (1) or (2):')
player1=players[number1]
player2=players[number2]
print(player1, player2)
print('the game begins')
while True:
player1(int(msg))
if msg == 0: break
print('remained sticks:', msg)
player2(int(msg))
print('remained sticks:', msg)
if msg == 0: break
Your players are references functions:
players= {
'1': robot,
'2': human
}
Later you call them player1 and player2:
player1=players[number1]
player2=players[number2]
But when you use these functions you don't do anything with the return value:
player1(int(msg))
...
player2(int(msg))
So those functions return something, but you ignore the value. You need to either print that return value or assign it to a variable so you can do something with the value later.
Since your return values are called total perhaps you want:
total = player1(int(msg))
print('new total:', total)
return does work, of course; it returns a value. However in your code you are not capturing that value and it is immediately thrown away.
It's really not clear what you want, but perhaps you want something like this:
msg = player1(int(msg))
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am creating a quiz... and i want to make sure that people can choose how many question they want to answer..
Write a program for an application that let the user host a quiz game. The application will have a collection of questions with short answers. The program should ask the user how many question they want for their game. It will then ask that many questions in random order. When the user types in an answer, it will check the answer against the correct answer and keep track of the number of questions they got right. It will never ask the same question twice. When all the questions have been asked, or the user has quit (by typing "quit" as an answer), the program will print the score and the total number of questions asked
from random import * #random is a library. we need the randint function from it
def Main() :
Questions = [] # list of all the questions
Answers = [] # list of all the answers
setup(Questions, Answers)
while True :
target = int(input("How many questions do you want to answer? more than 1 and less than 11 "))
if target <= len(Questions) :
break
print("Sorry, I only have ", len(Questions), " in my databank")
# alternate version:
# target = int(input("How many questions do you want to answer? "))
# while target > len(Questions) :
# print("Sorry, I only have ", len(Questions), " in my databank")
# target = int(input("How many questions do you want to answer? "))
#
score = 0
numberAsked = 0
while len(Questions) > 0 :
qnNum = randint(0, len(Questions)-1)
correct = askQuestion(Questions[qnNum], Answers[qnNum])
numberAsked = numberAsked + 1
if correct == "quit" :
break
elif correct :
score=score+1
del Questions[qnNum]
del Answers[qnNum]
reportScore(score, numberAsked)
def reportScore(sc, numAsked) :
print("Thanks for trying my quiz, Goodbye", sc, " questions right out of ", numAsked)
#asks the user a question, and returns True or False depending on whether they answered correctly.
# If the user answered with 'q', then it should return "quit"
def askQuestion (question, correctAnswer):
print(question)
answer = input("your answer: ").lower()
if answer == "quit" :
return "quit"
elif answer == correctAnswer.lower() :
print("Well done, you got it right!")
return True
else :
print("You got it wrong this time!. The correct answer is ", correctAnswer)
return False
# Sets up the lists of questions
def setup(Questions, Answers) :
Questions.append("The treaty of Waitangi was signed in 1901")
Answers.append("FALSE")
Questions.append("Aotearoa commonly means Land of the Long White Cloud")
Answers.append("TRUE")
Questions.append("The Treaty of Waitangi was signed at Parliament")
Answers.append("FALSE")
Questions.append("The All Blacks are New Zealands top rugby team")
Answers.append("TRUE")
Questions.append("Queen Victoria was the reigning monarch of England at the time of the Treaty")
Answers.append("TRUE")
Questions.append("Phar Lap was a New Zealand born horse who won the Melbourne Cup")
Answers.append("TRUE")
Questions.append("God Save the King was New Zealand’s national anthem up to and including during WWII")
Answers.append("TRUE")
Questions.append("Denis Glover wrote the poem The Magpies")
Answers.append("TRUE")
Questions.append("Te Rauparaha is credited with intellectual property rights of Kamate!")
Answers.append("FALSE")
Questions.append("Kiri Te Kanawa is a Wellington-born opera singer")
Answers.append("FALSE")
Main()
The main issue is in your while loop - you aren't doing anything with target, which is what is supposed to be governing the number of questions asked. Without going too crazy on suggested modifications, try replacing the code around your while loop with this:
score = 0
numberAsked = 0
while numberAsked < target:
qnNum = randint(0, len(Questions))
correct = askQuestion(Questions[qnNum], Answers[qnNum])
numberAsked = numberAsked + 1
if correct == "quit" :
break
elif correct :
score=score+1
del Questions[qnNum]
del Answers[qnNum]
This will loop while numberAsked is less than target. Your current issue is that your loop is governed by the length of the Questions list, which starts at 10 and decreases by 1 on each iteration. Therefore no matter what your target is, the loop will cycle through all of the questions.