Tips For an Intro Python Program [closed] - python

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}')

Related

Stuck in while loop and it doesnt work how I thought it would work [closed]

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.

python quiz with subject options [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
print("plese choose a topic of your liking")
History = ('History')
Music = ('Music')
Computer_science = ('Computer science')
print (History, Music, Computer_science)
History = print("when did the Reichstag fires begin?")
one = ("1) 1937")
two = ("2) 1933")
three = ("3) 1935")
print (one, two, three)
guess = int(input())
if guess == 2: #this makes it so any option appart from 2 is outputed as 'wrong'
print ("well done")
else:
print("wrong")
I have created the first part of my python quiz, It took me a while to figure out, I have also created a list that contains 3 different subjects, Do any of you know how to assign a button to each element within my subject list? If this does not make any sense, please let me know (I'm new to this site)
to get this sort of behaviour you can make an input before everything else which determines what subject you choose based on user input. so something REAL simple like:
subject = int(input("Please choose what subject you would like
(number):\n[1]History\n[2]Maths\n[3]Geography\n"))
if subject == 1:
print("You have chosen History")
elif subject == 2:
print("You have chosen Maths")
elif subject == 3:
print("You have chosen Geography")
else:
print("that is not an available option")
This is probably the simplest it can get with menus... If you type 1 and press enter you get history and so on. i dont know how your program works but do what fits in.
There are probably better ways too this is just what I remember doing back in the day. Very simple stuff

Achievement system in and IDLE python game using pycharm [closed]

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!

Basic Error Capture - for inputs - Python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to error capture my variables that are set by a user input. So far I have done this but was wandering if there are any simpler or more efficient ways of doing this:
while number1error == 1:
try:
number1 = float(input("Please enter the value of number1"))
break
except ValueError:
print("Please enter an integer")
As you can see this would take up a lot of space if I had a lot of inputs from the user. Any better suggestions would be appreciated.
Would this help?
totalReTries = 10
acquiredValue = None
PROMPT_MESSAGE = "Please enter the valid value: "
typeOfInteredData = float
rangeOfData = range(10, 20)
for currentRetry in range(1, totalReTries):
print "Attempt %d of %d" % (currentRetry, totalReTries)
try:
acquiredValue = input(PROMPT_MESSAGE)
except ValueError:
print("Incorrect data format. Please try again.")
continue
if type(acquiredValue) != typeOfInteredData:
print "Incorrect data type. Please try again."
continue
elif not acquiredValue in rangeOfData:
print "Incorrect data Range. Please try again."
continue
break
if not acquiredValue:
print "ERROR: Failed to get a correct value"
else:
print "The acquired value is: " + str(acquiredValue)
Adapting this into a function, as suggested above, would be a good idea too.
Regards

python - Is it possible to combine 2 functions together to create 1 function? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is it possible to combine these functions together to create 1 function?
def checkinput():
while True:
try:
name=input("whats your name?")
return name
except ValueError:
print("error!")
Combined with:
def checkage():
while True:
try:
age=input("whats your age?")
return age
except ValueError:
print("error!")
Thanks in advance!
You can refactor the code to create one function that handles both cases, by recognizing the parts that are the same, and parameterizing the other parts.
def check_value(prompt):
while True:
try:
val=input(prompt)
return val
except ValueError:
print("error!")
The only difference between the two functions (other than trivial differences like variable names) was the prompt shown by the input function. We make that a parameter to the new unified function, and call it like this:
x = check_input("What's your name?")
y = check_input("What's your age?")
Why you expect input to possibly raise a ValueError is a different question.
If you want to generalize your code, you could write one function that can ask any number of questions.
You can create a function that looks like this:
def ask_a_question(prompt):
while True:
try:
answer = input(prompt)
except ValueError:
print("Error!")
else:
return answer
For example, in your main() function, you could have a list of prompts:
prompts = {
'name': 'What is your name?',
'age': 'How old are you?',
'dog': 'Do you love dogs more than cats? (yes, you do)',
}
And finally you would create a loop that would ask all your questions one by one:
answers = {} # a dictionary of answers
for key, prompt in prompts.items():
answers[key] = ask_a_question(prompt)
Hopefully that gives you some ideas on how to reduce duplication of similar functions.
You can easily call a function from other functions:
def check_user_data():
checkinput()
checkage()
But really, this is a silly thing to do. If you just want their name and age you'd be better off doing something like this:
def get_user_info():
name = input("What is your name? ")
age = input("What is your age? ")
return name, age
You're never going to get a ValueError when you're just taking input - if you were doing int(input('What is your age? ')) you could get a ValueError, but otherwise the rest of your code is superfluous.
Yes!
def check_input_and_age():
return checkinput(), checkage()

Categories

Resources