Im a very new Python user (2.7) and have been working my way through the Learn Python The Hard Way course and up to chap 37 and decided to do read through some other learning materials and go over the basics again and do exercises there. I have been reading through this:
http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/ifstatements.html
and I just did this:
3.1.4.1. Graduate Exercise
Write a program, graduate.py, that prompts students for how many credits they have. Print whether of not they have enough credits for graduation. (At Loyola University Chicago 120 credits are needed for graduation.)
and this is my code for that:
print "How many credits do you currently have: "
credits = raw_input("> ")
if credits >= 120:
print "You have graduated!"
else:
print "Sorry not enough credits"
but no mater what number I input it just gives "Sorry not enough credits" as the answer every time, why? I have tried moving some things around and making it > instead of >= but nothing worked. Im sure this is something stupidly simple Im missing but I cant figure it out.
I've done several other if statement exercises in the LPTHW course similar to this and never had a problem.
raw_input() returns a string:
>>> credits = raw_input("> ")
> 150
>>> type(credits)
<type 'str'>
You need to cast it to int:
credits = int(raw_input("> "))
In your code, at the if statement you are comparing a str type with a int type. so it is not working as you axpected. Cast the credit as int
print "How many credits do you currently have: "
credits = raw_input("> ")
credits = int(credits)
if credits >= 120:
print "You have graduated!"
else:
print "Sorry not enough credits"
I am refering to the same material by Dr. Andrew Harrington and I am doing the same program, my program may look pretty much amatuerish so I would highly appreciate if someone can kindly refine it
def graduateEligibility(credits):
if credits >= 120:
print("Congratulations on successfully completing the course.....see you on graduation day!")
else:
print("Sorry! Your credits are below 120, please kindly retake the evaluaton tests")
def main():
E = float(input("Enter your English marks:"))
M = float(input("Enter your Mathematics marks:"))
P = float(input("Enter your Physics marks:"))
C = float(input("Enter your Chem marks:"))
Cf = float(input("Enter your Comp.Fundamentals marks:"))
Fin_Edu = float(input("Enter your finance marks:"))
Const = float(input("Enter your Constitutional.Stds marks:"))
R = float(input("Enter your Reasoning marks:"))
TotalCredits = (E+M+P+C+Cf+Fin_Edu+Const+R)
YourCredits = graduateEligibility(TotalCredits)
main()
For simplicity sakes i have taken 8 subjects each have 20 credits.
You need to accept integer input for that and also need to handle non integer inputs.
print "How many credits do you currently have: "
try:
credits = int(raw_input("> "))
if credits >= 120:
print "You have graduated!"
else:
print "Sorry not enough credits"
except ValueError:
print "Invalid input"
Output:
> 100
Sorry not enough credits
> 121
You have graduated!
> aaaa
Invalid input
Related
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!')
my_money = input('How much money do you have? ')
boat_cost = 20 + 5
if my_money < boat_cost:
print('You can afford the boat hire')
else :
print('You cannot afford the board hire')
Try this code snippet and see the original code problem:
my_money = int( input('How much money do you have? '))
boat_cost = 20 + 5
if my_money >= boat_cost:
print('You can afford the boat hire')
else :
print('You cannot afford the board hire')
input is normally a string. In order for this to work you need to convert it to an integrer by using y = int(x).
There is also an error in the if, albeit not a programming one, where it says that they can afford the hire if their money is less than the cost.
The correct code, without fixing the second error, would look like this:
mymoney = int(input('How much money do you have? '))
boatcost = 20 + 5
if mymoney < boatcost:
print('You can afford the boat hire')
else:
print('You cannot afford the board hire')
The input() function allows user input in the console.
But that input is a string, you cannot use it as a mathametical operation.
So int() is a function that takes a string and returns the integer.
you have to use int(input()) when you want to get an input that can only be a number.
so replace:
my_money = input('How much money do you have? ')
with
my_money = int( input('How much money do you have? '))
and your if statement logic is wrong it should be :
if(mymoney >= boatcost):
instead of
if(mymoney < boatcost):
you can afford the boat only when your price is same or higher
I am currently writing a Tipper program for the job, and I am having a lot of issues with it. The result keeps saying invalid syntax, and I have switched up so many things but it seems like I can never make it just right. To give you an example of this, here is my current code:
print("Now that your belly is full, how much is the fee?")
fee = input("Enter your fee: ")
print("Would you like to give us a tip?")
answer = input("Yes or no?")
if answer == no:
why = input("Why do you not want to tip us? Also, you don't have to answer. When done, just press enter.")
print("We understand. Here is your fee:", fee)
elif answer == yes:
tip = input("Would you like to tip 15 percent or 20 percent? ")
if tip == 15 :
cost1 = fee/15 + fee
elif tip == 20 :
cost2 = fee/20 + fee
else:
print("I do not understand.")
else:
print("I do not understand.")
print:("Have a wonderful day!")
So, yeah, to be honest with you I am not sure why it is not working, but could someone please answer? I am really stumped by this.
I fixed the bugs in your code and tested it, however the overall code structure can still be improved.
So what caused your program to crash?
"No" and "Yes" are both strings so you have to put them between " "
You have to convert the fee entered from the user to integer using int() function so that you can do math calculations on it.
You were calculating the tip wrongly, I fixed it using these calculations
15% >> Total = 1.15xfee
20% >> Total = 1.20xfee
Note: in the below code I used the math.ceil() function to round up the tip to a whole number.
To improve the user experience a bit, I also added a line that prints the total cost, including the tip, back to the user.
Here is the corrected code:
import math
print("Now that your belly is full, how much is the fee?")
fee = int(input("Enter your fee: "))
print("Would you like to give us a tip?")
answer = input("yes or no?")
if answer == "no":
why = input("Why do you not want to tip us? Also, you don't have to answer. When done, just press enter.")
print("We understand. Here is your fee:", fee)
elif answer == "yes":
tip = int(input("Would you like to tip 15 percent or 20 percent? "))
if tip == 15 :
cost = math.ceil(1.15 * fee)
print("Your total, including fee is, ", cost)
elif tip == 20 :
cost = math.ceil(1.20 * fee)
print("Your total, including fee is, ", cost)
else:
print("I do not understand.")
else:
print("I do not understand.")
print("Have a wonderful day!")
Here is a version that works. Now, there are still problems. First, it doesn't catch if they enter garbage that is not a number for the bill or for the tip. Second, it doesn't round the tip, because I don't know what currency you're using. But at least you can run this and get an answer.
print("Now that your belly is full, how much is the bill?")
fee = float(input("Enter your bill: "))
print("Would you like to give us a tip?")
answer = input("yes or no?")
if answer.lower() == 'no':
why = input("Why do you not want to tip us? Also, you don't have to answer. When done, just press enter.")
print("We understand.")
elif answer.lower() == "yes":
tip = int(input("What tip percentage do you use? "))
fee += fee * tip / 100
else:
print("I do not understand.")
print("Your total bill is", fee)
As mentioned in the comments, you need to wrap the answers you're testing for in quotes (double quotes ", or single quotes ' will do), because otherwise python will think they are variable names and not string literals, that you want to compare against.
Also, in the last print, you have a colon (:) that doesn't belong there.
Here is your code with those two issues fixed.
print("Now that your belly is full, how much is the fee?")
fee = input("Enter your fee: ")
print("Would you like to give us a tip?")
answer = input("Yes or no?")
if answer == 'no':
why = input("Why do you not want to tip us? Also, you don't have to answer. When done, just press enter.")
print("We understand. Here is your fee:", fee)
elif answer == 'yes':
tip = input("Would you like to tip 15 percent or 20 percent? ")
if tip == 15:
cost1 = fee / 15 + fee
elif tip == 20:
cost2 = fee / 20 + fee
else:
print("I do not understand.")
else:
print("I do not understand.")
print("Have a wonderful day!")
Also, this way of hard coding options and no easy way to skip questions (once answered 'yes' for example) makes for a very frustrating user experience, but that is another issue.
Edit:
You're also comparing strings to numbers, which will always be false, which saves you from the error, that trying to divide a string by a number would produce
I am trying to write a program that determines a person stage of life, whether the person is a baby, kid, teenager, adult or elder. The program starts with a variable that contains an input() function that allows the user to type in an age so the program can start running.
The issue is that when I type ages higher than 99, the program prompts that the person whose age has been typed in is a baby. So basically, according to the program someone who is 123 years old is a baby, which does not make sense.
age=input("enter the person's age: ")
if age<'2':
print('the person is a baby')
elif age=='2' and age<'4':
print('the person is a toddler')
elif age >='4' and age<'13':
print ('the person is a kid')
elif age>='13' and age<'20':
print('the person is a teenager')
elif age>='20' and age<'65':
print('the person is an adult')
elif age>='65':
print('the person is an elder')
I am wondering if I am making a mistake on my code, although it seems to me pretty straight forward. Anyways, I am guessing there is some theoretical knowledge that I am missing, if that is the case I would appreciate if you folks can shed some light on the whole issue.
What you are essentially doing here is comparing strings which does not translate to the behavior you are seeking. You will need to cast the input as int() first.
If you know the input is guaranteed to be formatted correctly, use:
age = int(input("enter the person's age: "))
However, nobody is perfect so it would be best to wrap in a try-except:
age = input("enter the person's age: ")
try:
age = int(age)
except:
# Handle exception
if age < 2:
# Do something
elif ...
# Do more stuff
You are comparing strings no integers thus '100' is less than '99' as the first and second characters are less.
You need to convert your input to an integer and thenuuse that for the comparisons and then you shall be fine.
You should convert age to an integer and then compare. You are comparing strings, and that gives you weird answers.
Reformatted code:
age_str=input("enter the person's age: ")
try:
age = int(age_str)
except:
print("Invalid Entry. Enter age as a number.")
exit(0)
if age < 2:
print('the person is a baby')
elif age == 2 and age < 4:
print('the person is a toddler')
elif age >= 4 and age < 13:
print('the person is a kid')
elif age >= 13 and age < 20:
print('the person is a teenage r')
elif age >= 20 and age < 65:
print('the person is an adult')
elif age >= 65:
print('the person is an elder')
Code also checks for invalid entries above. If anything other than an integer is entered, it throws an error.
I need help with an assignment I have for Intro to Python.
The assignment is to have the computer pick a random number between 1 and 100 and the user has to guess the number. If your guess is too high then you will be told. If your guess was too low then you will be told. It will continue repeating until you guess the correct number that was generated.
My issue is that if an input is a string then you would get a prompt saying that it is not a possible answer. How do I fix this issue?
P.S. If it would not be too much trouble, I would like to get tips on how to fix my code and not an answer.
Code:
import random
#answer= a
a= random.randint(1,100)
#x= original variable of a
x= a
correct= False
print("I'm thinking of anumber between 1 and 100, try to guess it.")
#guess= g
while not correct:
g= input("Please enter a number between 1 and 100: ", )
if g == "x":
print("Sorry, but \"" + g + "\" is not a number between 1 and 100.")
elif int(g) < x:
print("your guess was too low, try again.")
elif int(g) > x:
print("your guess was too high, try again.")
else:
print("Congratulations, you guessed the number!")
So if you want to sanitize the input to make sure only numbers are being inputted you can use the isdigit() method to check for that. For example:
g=input("blah blah blah input here: ")
if g.isdigit():
# now you can do your too high too low conditionals
else:
print("Your input was not a number!")
You can learn more in this StackOverflow thread.