r/learnpython • u/shiny_arbok • Jul 13 '20
I wrote my first program today!
I'm a couple of days into learning Python and today I wrote my very first program for an idea I came up with myself, not because the book told me to!
It's a program to determine the value of the discriminant and x in an equation that follows "ax² + bx + c = 0", anyway here's the code:
# This is for calculating the discriminant when trying to find x in "ax² + bx + c = 0"
import math
try:
print("a?")
a = int(input())
print("b?")
b = int(input())
print("c?")
c = int(input())
def discr(a,b,c):
discriminant = b ** 2 - 4 * a * c
if discriminant < 0:
print("Discriminant =")
print(discriminant)
print("No value for x possible")
elif discriminant == 0:
print("Discriminant =")
print(discriminant)
print('x =')
print((-b)/(2*a))
elif discriminant > 0:
print("Discriminant =")
print(discriminant)
print('x = ')
print((-b + math.sqrt(discriminant))/(2*a))
print('x = ')
print((-b - math.sqrt(discriminant))/(2*a))
discr(a,b,c)
except ValueError:
print("That's not a number")10
u/otanan Jul 13 '20
This looks great! There are already some great Python related comments posted, but a more mathy one/building off of the comment about “editing and improving” try going the step further! You ask for inputs and then cast them as integers, so if I give a=3.5, you’ll use the formula for a=3, but the quadratic formula doesn’t care about that! Try improving it to take in even float (decimal) values too!
Want to take it even further? Python natively supports complex numbers (cool right?) I don’t know how familiar you may be with them, but in the case of a negative discriminant you can still get out solutions! (Although they will be complex)
Want to take it even further? Try complex coefficients (a, b, c)
Keep up the good work!!
1
u/shiny_arbok Jul 13 '20
Okay so if I change the int(input()) to float(input()), it should work just fine?
Also I'm not that familiar with either Python or complex numbers, so I don't really know what that means
2
u/otanan Jul 13 '20
Yes for changing to floats!
As for the complex numbers, try looking into them, at a very basic level they serve as expanding on the real numbers (think, every normal number you work with, from -20, to 42.6423, to pi, to 10^100), where this expansion is done by allowing a definition of sqrt(-1).
In the case of solving the following quadratic: x^2+1=0, you've noticed that you'll get a negative discriminant and sure enough, if you just try
math.sqrt(-1)you'll get an error, but complex numbers allow us to make sense of these kinds of things! If you allow complex numbers you can use the quadratic formula to solve any quadratic, no need for the error handling for negative discriminants!Look into the
cmathpackage. If you change the import math line to:
import cmaththen use
cmath.sqrt(-1)You'll get something different! It's a complex number! I claim that this number actually is the square root of -1! How can you check that this is true?
It's a lot of fun to play around with these kinds of things, and the great thing about programming is that you can dive into all kinds of rabbit holes just as soon as you've found them! Explore!
1
u/shiny_arbok Jul 13 '20
Oh THAT's what complex numbers are! I forgot for a moment, it's like, the complex number is named 'i', right? I've seen that in my last high school year in math class but it didn't really stick with me apparently
Also is programming really such a big rabbit hole? I usually have a hard time exiting rabbit holes, so that'd be a good thing in this case, right?
2
u/otanan Jul 13 '20
It's a great thing in this case ;)
Unfortunately one of the things that new programmers often struggle with (I definitely know that I did) is that we can learn all of these new concepts in theory, but we often have no idea how to play with them in practice. Sure I understand object inheritance now, but I want to write a program and I have no clue what to write. Exploring those rabbit holes is one way you're exercising your creativity and will help you really consolidate these new programming ideas (wait! an enemy and a follower in a game are just both examples of NPC's, maybe I can write an object called NPC that handles most of the code for them and have them each inherit from the NPC class)
You're doing exactly that with this example quadratic solver, keep going!
2
u/shiny_arbok Jul 13 '20
It took me a while to come up with an idea though, if I have an idea in mind I usually can do my thing but the problem I often have (in life in general, not only with programming) is that I don't know where or how to start. So I'll have to work on that
2
u/otanan Jul 13 '20
Don't worry, I know very few people that know how to start, and often the few times they do it's only because they're already had that roadblock before with a very similar problem and have now learned how they can tackle it differently, and that will only come with practice (and rabbit holes). So don't ever feel bogged down because you aren't sure how to start just yet, keep working on it, not just with programming, but with life in general.
One benefit also of programming is the logic and problem solving skills that it teaches you, so doing these things with a computer will also teach you how to start in life!
2
u/shiny_arbok Jul 13 '20
Well that last part of your comment sounds great!
As long as I don't start answering my exam questions in programming language, that is... (right now I'm studying biomedical lab tech, but it isn't really for me, I'm thinking of changing to something else, maybe even programming, I'm testing the waters a bit)
2
u/PyTec-Ari Jul 14 '20
Only issue you will face is if they don't put a number in but a letter. The program will crash. Good practice would dictate you try and account for this by using a try/except:
try: a = float(input("Please enter a float: ")) except ValueError as e: print(e) print("We didn't crash!") >> Please enter a float: a >> could not convert string to float: 'a' >> We didn't crash!So we can print the error and your program won't crash, letting you prompt the user to try again.
You can determine what sort of error is going to occur by actually making the eror happen and watching the logs. So if I don't use the try/except I got:
Traceback (most recent call last): File "/Users/xyz/file.py", line 1, in <module> a = float(input()) ValueError: could not convert string to float: 's'Its bad practice but you can do a a blanket exception that will catch every error:
try: a = float(input("Please enter a float: ")) except Exception as e: print(e)It will handle every error, but good practice is to know the errors you're going to receive and handle them accordingly.
1
1
1
7
Jul 13 '20
Nice! So it's a quadratic equation solver, if I understand it correctly. You implemented this formula? Congratulations :-)
6
u/shiny_arbok Jul 13 '20
Indeed I used that formula! I remembered making a similar program on my TI-84, so I thought "Hey why not try doing it in Python?"
1
2
Jul 13 '20
nice! now you could make a quadratic solver it just a few lines of code from here and you'll make a quadratic equation solver
2
u/shiny_arbok Jul 13 '20
I think I could do something like that... maybe a program that asks "do you need to calculate x or y?" after inputting the values for a, b, and c
If you say 'x', I can do an "if" statement where it follows this program, and if you say 'y', an "elif" statement where you enter the 'x' value and then it calculates y
Thanks for the idea, I'll definitely try it out!
2
Jul 13 '20
you're welcome and you'd need a system of 2 equations containing x and y if you're gonna solve for x or y i think you know that and after making that you could learn tkinter and make an app that let's you visuallize vectors in 2d space and also visuallizes the addition and subtraction of vectors and takes the dot product and cross product and the determinant of 2 vectors that's what i made just a few weeks ago and im super proud of it and then you could move on to python scripts that can take the derivative of a function or solves an integral or even a differential equation solver or a partial differential equation solver or you could do something else different like making neural networks or making a web scraper whatever you know? just keep making stuff, keep making stuff while you're learning that's the best way to learn
3
u/shiny_arbok Jul 13 '20
Whoa, whoa, that sounds a bit too complicated for where I'm at yet, it'll take me some time to get there hahaha
Congratulations on making that app though!
2
Jul 13 '20
thanks! If you already know the maths then you can probably do it after a few months of learning but all the best i hope you get amazing at coding also after a year of python learn c or c++ it's good to know a lower level language
2
u/shiny_arbok Jul 13 '20
I'm thinking of officially switching my studies to programming next year (because what I'm doing now isn't doing it for me), so chances are big I'll learn other programming languages too! Right now I'm just learning Python to test the waters a bit, to see if programming is something I'd actually like to do as a career.
And who knows, maybe I'll develop a groundbreaking app in a couple of years, that everyone will use in their daily lives
2
2
u/MotuUk Jul 13 '20 edited Jul 13 '20
Well done mate! Looks good.
Couple of pointers that it doesn't look like anyone else has picked up on. For one, I would put your method discr() outside of the try block. It will only be defined by the python compiler once it has passed all of the input calls, or never if you get an error (could lead to issues in a longer piece of code).
Another thing, there isn't much point in the try catch block in the first place as if the error is handled or not it still ends the program, but I guess it let's you know! Instead, what I've done in the past (example is from an old hangman game of mine) is something along the lines of:
def get_char():
while True:
char = input('choose a char: ')
if char == "":
print("Please enter a char")
elif len(char) > 1 and len(char) < 1:
print("Please only enter one letter")
elif not char.isalpha():
print("Please enter a valid character")
else:
return charchar = get_char()
But change this for getting an int.
Edit: pastebin link due to horrible formatting...
2
u/shiny_arbok Jul 13 '20
Thanks for the tip! I just used the try-except part for practice actually, as the book I'm following just handled that in the previous chapter, so I thought I'd implement it for fun and to get familiar with the concept
Also no offense intended, but your code is a bit... hard to figure out, since it's all right behind each other, so I can't really see what bit belongs to which block
2
u/MotuUk Jul 13 '20
Sorry, I copied and pasted it on mobile. Would explain a lot. Ive edited the original to a pastebin link.
As for the try catch block, I totally understand, but just thought I'd throw in a little 2 cents!
2
u/shiny_arbok Jul 13 '20
It's all good, reddit mobile can be a formatting bitch
And thanks for your 2 cents, I think it would be good for me to see how others would tackle the same problem, so that I can learn different ways of how to approach stuff! I'm only learning to program for a couple of days now and I'm eager to learn!
1
u/MotuUk Jul 13 '20
Yeah, the whole point of that get_char being in another method is that you can validate the user input, whilst reusing code but in a way that keeps the main part of your code clean and easier to follow. Plus you can reuse that method for each of the a, b and c. It also eliminates the need to put your entire block of code into a try catch statement (which is a little cumbersome)
2
2
2
u/hipstergrandpa Jul 14 '20
Nice! One thing I’m not sure is covered by other comments is the use of the ‘try/except’ being used here. Generally, you want to use try and except to catch and gracefully handle known sources of that exception, rather than blanketing the entire function. The idea is to isolate problems for debugging so you know exactly where some issue may occur. In this case, you want to catch a value error from user input. The best place to put the try and except then would be around just the inputs, as you’ll get a value error when you try to cast the input into an int. If you get an unrelated error that happens to be a value error as well, you’d have a harder time determining where it came from as your program will just tell you it isn’t a number, when that may not be the source of error at all. Something I learned that I thought you would find helpful :)
1
u/shiny_arbok Jul 14 '20
Yeah other comments have mentioned similar things, but still, thanks for the tip! :)
3
4
1
u/skellious Jul 13 '20
Its good but why is it all in a giant try except?
you're casting all the values to int, so if they cast properly then your program should function and if they dont then it will raise a type error at that point.
4
u/shiny_arbok Jul 13 '20
The book I'm learning Python from talked about try except statements, so I just threw one in there for practice
3
3
Jul 14 '20
My first python program on my own was a quadratic equation solved and plotter. I felt like such a badass lol
4
u/Nebulezz Jul 13 '20
Looks good! Seems to be alot of print statements though that could be reduced, e.g. print("The discriminant is:", discriminant) instead of 2x print lines
2
2
2
Jul 14 '20
Your try clause doesn't have to cover all of you code. Only the sections where it might be raised are necessary (int(input)).
2
2
2
2
1
1
1
u/uSrNm-ALrEAdy-TaKeN Jul 13 '20
Looks great! If you want to try something else to advance it, try doing the print statements with f-strings or str.format
0
0
0
118
u/NFLAddict Jul 13 '20
cheers!
I like that your first program involved some math :)
But keep going!
one great way to learn, is to take it a step further; now that you completed a program, see if there's anything you can improve!
Just like with a paper, where someone might write a first draft, but afterwards, maybe they want to polish it up a bit. edits etc.
same can be done (and is often done), in programming. where you get your idea out; and then you can fix it up.
so, only take this as constructive and as a way to help you improve!
you can actually place the string you wanted to printout before input, inside the function
input(*inside*)so you can prompt for a,b,c like so:
Another thing, and I encourage you to learn more about them (google/youtube etc). is f-strings!
fstrings allow you to pass in a value between curly brackets {inside here}, and have it included in the string
perhaps more clear through example:
your lines:
can be written as:
unless you wanted them to printout on separate lines. in which case
"\n"is very useful as it signals a new line.so if you instead wrote:
that would behave, like you originally had it, but just all on one neat line. of course that's just one way: and I encourage you to play around with it a little bit, so I intentionally won't say anything about the other elif statements. but perhaps you can figure out a way to rewrite that with f-strings in a print()
but again: nice job