I'm a beginner to programming, I literally started programming like three days ago. Here is my program, it checks if you've passed all subjects, and as you guys can see, there are a lot of if conditions in it. I've read online that too many if conditions, or for loops can slow your program down, and that there is a more efficient way of doing it, that is by using some user-defined function. But, the problem is that I don't have the necessary knowledge to do so. It would be really helpful if you guys can tell me how to shrink my code down, and maybe make it more efficient.
# Take input
while True:
a = float(input("Enter your mark in Tamil: "));
b = float(input("Enter your mark in English: "));
c = float(input("Enter your mark in Chemistry: "));
d = float(input("Enter your mark in Physics: "));
e = float(input("Enter your mark in Non-major: "));
f = float(input("Enter your mark in Python: "));
# This part checks if you've got a minimum of 35% in every subject
if a >= 35.0 and a <= 100.0:
print("Pass in Tamil")
if a > 100.0:
print("Invalid input")
if a < 35.0:
print("Fail in Tamil")
if b >= 35.0 and b <= 100.0:
print("Pass in English")
if b > 100.0:
print("Invalid input")
if b < 35.0:
print("Fail in English")
if c >= 35.0 and c <= 100.0:
print("Pass in Chemistry")
if c > 100.0:
print("Invalid input")
if c < 35.0:
print("Fail in Chemistry")
if d >= 35.0 and d <= 100.0:
print("Pass in Physics")
if d > 100.0:
print("Invalid input")
if d < 35.0:
print("Fail in Physics")
if e >= 35.0 and e <= 100.0:
print("Pass in Non-major")
if e > 100.0:
print("Invalid input")
if e < 35.0:
print("Fail in Non-major")
if f >= 35.0 and f <= 100.0:
print("Pass in Python")
if f > 100.0:
print("Invalid input")
if f < 35.0:
print("Fail in Python")
# Display the total marks and the percentage secured by the user
if (a>100 or b>100 or c>100 or d>100 or e>100 or f>100):
print("Check your marks")
if (a<=100 and b<=100 and c<=100 and d<=100 and e<=100 and f<=100):
print("Your total:", a+b+c+d+e+f)
print("Your percentage:", ((a+b+c+d+e+f)/600)*100)
# Check if the user wants to do another calculation
next_calculation = input("Do you want to proceed with next calculation? (yes/no) ")
if next_calculation == "no":
break
if next_calculation != ("yes" or "no"):
print("Invalid input")
break```
Well done! And welcome to StackOverflow.
Codereview versus StackOverflow
This site (Stackoverflow) is for developers who are stuck at a problem. There is a sister-site, CodeReview, which does only that: reviewing code. Your question is a bit between both sites: you have a question (can this be more efficient / Pythonic), but your question is mostly a code review question. Check out the "How to ask" sections of both sites for more info.
Use functions
As I said: you're doing a great job. You're doing input, output (print) and if-then statements. You even have comments in your code, explaining what you're doing. Wonderfull!
Next step is to decompose your code into logical functions. I see that your comments are already pointing in the right direction (for example: "Take input" does exactly that). Now create a function (def function_name(function_arguments):) and think about what that function needs as input (function arguments) and what it should output (return value). For example in your code, you could have the following functions:
Ask the user for marks for a class. Input: class name. Output: a valid mark.
Print if the user failed or passed. Input: class name, mark.
You can create functions that perform this task. This cuts your code input (re)usable and manageable pieces. Add a comment at the beginning of the function that describes what it does.
Learn about lists and dicts
Lists and Dicts (dictionaries) are extremely useful datatypes in Python. Learn them. I included them in the example below. More (general) info on lists, dicts, sets, etc. in the official Python documentation or anywhere on the web.
Code style: PEP8
Try to code according to general accepted styling rules, called PEP8. Most important examples (for you as a beginner):
Give your variables meaningful names (not: a, b, c, etc.).
Don't use "magic numbers" in your code (0, 35, 100, 'yes', etc.). Create constants, define them at the top of the module, give them names in capitals (MEANING_OF_LIFE = 42).
Use 4 spaces as identation (not 1).
"More efficient" version of your code
Here is a rewrite of your code. I really hope this helps. There are many other ways to do this. But I tried to keep it simple and meaningful for you as a beginner.
MIN_MARK = 0.0
PASS_MARK = 35.0
MAX_MARK = 100.0
YES = ['yes', 'y']
def get_marks(classname: str) -> float:
""" Asks a mark for the given classname.
Checks the mark for a numeric value and
that the mark is between MIN_MARK and MAX_MARK (both included)
"""
while True:
mark = input(f'Enter your mark in {classname}: ')
if mark.isnumeric():
mark = float(mark)
if mark >= MIN_MARK and mark <= MAX_MARK:
return mark
else:
print(f'Enter a mark between 0 and 100; please try again!')
else:
print(f'{mark} is not a valid numeric value; please try again!')
def print_pass_or_fail(classname: str, mark: float) -> None:
""" Prints if classname is passed or failed.
Class if passed if mark >= PASS_MARK.
"""
if mark > PASS_MARK:
result = 'PASS'
else:
result = 'FAIL'
print(f'{result} in {classname} with scoe {mark}')
def main():
classes = ['Tamil', 'English', 'Chemistry',
'Physics', 'Non-major', 'Python']
marks = {}
proceed = True
while proceed:
for classname in classes:
marks[classname] = get_marks(classname)
for classname, grade in marks.items():
print_pass_or_fail(classname, grade)
print(f'Totale score: {sum(marks.values())}')
print(f'Average score: {sum(marks.values()) / len(marks) * 100}%')
proceed = input('Continue [y/n]')
proceed = proceed.lower() in YES
if __name__ == '__main__':
main()
Try it online!
comparing your code to another people's code is huge growing point, stackoverflow helps a lot with it
while int(input("Do you want to proceed with next calculation? '1' - yes, 0 - 'no': ")):
d = {i:float(input(f"Enter your mark in {i}: ")) for i in ['Tamil', 'English', 'Chemistry', 'Physics', 'Non-major', 'Python']}
l = [f"Pass in {k}" if 35 <=v <= 100 else ("Invalid input" if v>100 else f"Fail in {k}") for k,v in d.items()]
# This part checks if you've got a minimum of 35% in every subject
for i in l:
print(i)
# Display the total marks and the percentage secured by the user
if 'Invalid input' in l:
print('Check your marks')
else:
print("Your total: ", sum(d.values()))
print("Your percentage: ", sum(d.values())/600*100)
print("\n",'*'*40,'\n\n\n')
print('see you later!')
Related
I'm new to the coding world. I have a problem with adding up all of the users' input values, as I don't know how many there will be. Any suggestions?
This is how far I've gotten. Don't mind the foreign language.
import math
while(True):
n=input("PERSONS WEIGHT?")
people=0
answer= input( "Do we continue adding people ? y/n")
if answer == "y" :
continue
elif answer == "n" :
break
else:
print("You typed something wrong , add another value ")
people +=1
limit=300
if a > limit :
print("Cant use the lift")
else:
print("Can use the lift")
You don't need to import math library for simple addition. Since you did not mention that what error are you getting, so I guess that you need a solution for your problem. Your code is too lengthy. I have write a code for you. which has just 6 lines. It will solve your problem.
Here is the code.
sum = 0;
while(True):
n = int(input("Enter Number.? Press -1 for Exit: "))
if n == -1:
break
sum = sum+n
print(sum)
Explanation of the Code:
First, I have declared the variable sum. I have write while loop, inside the while loop, I have prompt the user for entering number. If user will enter -1, this will stop the program. This program will keep on taking user input until unless user type "-1". In the end. It will print total sum.
Output of the Code:
Here's something for you to learn from that I think does all that you want:
people = 0
a = 0
while True:
while True:
try:
n = int(input("PERSONS WEIGHT?"))
break
except ValueError as ex:
print("You didn't type a number. Try again")
people += 1
a += int(n)
while True:
answer = input("Do we continue adding people ? y/n")
if answer in ["y", "n"]:
break
print("You typed something wrong , add another value ")
if answer == 'n':
break
limit = 300
if a > limit:
print("Total weight is %d which exceeds %d so the lift is overloaded" % (a, limit))
else:
print("Total weight is %d which does not exceed %d so the lift can be operated" % (a, limit))
The main idea that was added is that you have to have separate loops for each input, and then an outer loop for being able to enter multiple weights.
It was also important to move people = 0 out of the loop so that it didn't keep getting reset back to 0, and to initialize a in the same way.
here is my code, it does run but the output is not the way it should be
formula = input("Enter a formula: ")
parenthesis = (formula.count("(,)"))
if parenthesis >= 1 :
print ("You have enteread a complete formula.")
else:
print ("You have incomplete set of parenthesis")
Maybe I'm oversimplifying in my head, but here is a simple way of doing it:
formula = input("Enter a formula: ")
open_brackets = formula.count("(")
close_brackets = formula.count(")")
if open_brackets == close_brackets:
print("You have entered a complete formula.")
else:
print("You have incomplete set of parenthesis")
I've been working on this simple program in Python just so I can start experimenting with Python and become more knowledgeable of Python and other programming languages in general by designing them in a way in which others can use them in an efficient manner without getting caught on the parts which make this code work. I've been doing this by having a simple program calculate "Angles in a triangle" as it's a simple subject. Recently, I replaced def(): commands with if statements as it cuts down typing to a minimum and making it generally easier for others however, when I try to run this code I get a syntax error message with N becoming highlighted on line 17.
def triangle():
N = int(input("Please enter the number of angles you currently have between 1 and 3: "))
if N == 1:
a = int(input("What's one of the angles?"))
b = int(input("What's the other angle in the triangle?"))
c = a + b
f = 180 - c
print(f)
print("If you'd like to continue, please type in triangle()")
elif N == 2:
a = int(input("What's the value of angle 1?"))
b = 180 - a
c = b /2
print(c)
print("If you'd like to continue, please type in triangle()")
else N == 3:
a = 180
b = 180 / 3
print(b)
print("If you'd like to continue, please type in triangle()")
But I'm getting a syntax error returned on elif N == 3:
Any tips would be great.
else does not have a condition.. remove it to just say
else:
or make it says
elif N == 3:
You have else N == 3:. That is not how the if..elif..else structure works - the else is a catch-all branch that is entered if none of the preceding if or elif conditions are satisfied. If you want to check specifically for N == 3 and no other values, use elif N == 3. If you want a catch-all condition, simply use else:.
elif N == 3:
Either you meant elif (which is Python for else..if), or else
If you meant plain else, it doesn't take a condition.
If you want to annotate that an else implies a certain condition is met, then I use a comment:
else: # N == 3
But that's considered bad style: only do that if you're sure N cannot have any other value than 1,2,3. In your case the user could also input any number 4,5,..,9 (or indeed 10 or larger, or indeed 0 or any negative number), and that will wrongly get handled by the N==3 branch.
Whereas if your last branch if elif N == 3, with no else-clause, invalid numbers will silently fail every branch in your tree.
So for completeness and sanity-checking, you might prefer to do:
...
elif N ==3:
# Handle N == 3 case
else:
print "Invalid number!"
Here is my code as show below:
menu= "Welcome to the menu\n" \
+ "Please select an option below:\n" \
+ ( "0 - Enter a number\n" + "1 - Display current number\n" + \
"2 - Divisibility checking\n" + "3 - Perfect checking\n" + \
"4 - Triangular checking\n" + "5 - Quit\n" )
x == ("")
while option!=5: # <<< Q2
print(menu)
option= int(input("Enter option: "))
if option==0:
x= int(input("What is your number?: "))
while x <=0:
x= int(input("Must be positive, please! What is your number?: ")
elif option==1: # <<< Q1
print("The current number is", x)
elif (x == ""):
print("No number yet - Please input a number and try again.")
x= int(input("What is your number?: "))
Q1:
I was wondering why I kept getting an error message for line 14 of my code, for the second elif statement.
Q2:
I was also wondering how, for my first while statement, I might define "option" for option!=5 and then print the menu if I had not prompted the user to enter an option yet.
Any help on these two cases would really be appreciated.
Thank you.
concerning your second elif-statement, I think you got the nesting wrong.
You have one outer decision tree, where you go through the available option, the tree is:
if option == 0 --> do a
elif option == 1 --> do b
elif option == 2 --> do c and so on
You don't need in inner elif, because it is NOT an else statement to the chosen option. You are just starting a new decision tree (You try to find if x is already assigned and if not ask for a number, otherwise show the number). Therefore the correct code should be:
elif option == 1:
if x == "":
print("No number yet - Please input a number and try again.")
x= int(input("What is your number?: "))
else:
print("The current number is", x)
elif option == 2
--> Handling of option 2
This should work. I took the freedom to put the if-statement first, otherwise you would get the output
"The current number is "
"No number yet - Please input a number and try again."...
I think this is pretty much what Ignacio meant, when he asked, if you knew what the elif belongs to.
I have two begininer programs, both using the 'while' function, one works correctly, and the other gets me stuck in a loop. The first program is this;
num=54
bob = True
print('The guess a number Game!')
while bob == True:
guess = int(input('What is your guess? '))
if guess==num:
print('wow! You\'re awesome!')
print('but don\'t worry, you still suck')
bob = False
elif guess>num:
print('try a lower number')
else:
print('close, but too low')
print('game over')``
and it gives the predictable output of;
The guess a number Game!
What is your guess? 12
close, but too low
What is your guess? 56
try a lower number
What is your guess? 54
wow! You're awesome!
but don't worry, you still suck
game over
However, I also have this program, which doesn't work;
#define vars
a = int(input('Please insert a number: '))
b = int(input('Please insert a second number: '))
#try a function
def func_tim(a,b):
bob = True
while bob == True:
if a == b:
print('nice and equal')
bob = False
elif b > a:
print('b is picking on a!')
else:
print('a is picking on b!')
#call a function
func_tim(a,b)
Which outputs;
Please insert a number: 12
Please insert a second number: 14
b is picking on a!
b is picking on a!
b is picking on a!
...(repeat in a loop)....
Can someone please let me know why these programs are different? Thank you!
In the second example, the user doesn't get a chance to enter a new guess inside the loop, so a and b remain the same.
In the second program you never give the user a chance to pick two new numbers if they're not equal. Put the lines where you get input from the user inside the loop, like this:
#try a function
def func_tim():
bob = True
while bob == True:
#define vars
a = int(input('Please insert a number: '))
b = int(input('Please insert a second number: '))
if a == b:
print('nice and equal')
bob = False
elif b > a:
print('b is picking on a!')
else:
print('a is picking on b!')
#call a function
func_tim()
in your 2nd program, if b > a, you will go back to the loop because bob is still true. You forgot to ask the user to input again.. try it this way
def func_tim():
while 1:
a = int(input('Please insert a number: '))
b = int(input('Please insert a second number: '))
if a == b:
print('nice and equal')
break
elif b > a:
print('b is picking on a!')
else:
print('a is picking on b!')
func_tim()
Your second program doesn't allow the user to reenter his guess if it's not correct. Put the input into the while loop.
Additional hint: Don't make checks like variable == True, just say while variable:.