r/learnpython • • 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")
511 Upvotes

73 comments sorted by

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:

a = int(input("a? "))
b = int(input("b? "))
c = int(input("c? "))  

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:

if discriminant < 0:
    print("Discriminant =")
    print(discriminant)
    print("No value for x possible")  

can be written as:

if discriminant < 0:  
    print(f"Discriminant = {discriminant}. No value for x possible")  

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:

if discriminant < 0:  
    print(f"Discriminant =\n{discriminant}\nNo value for x possible")  

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

45

u/shiny_arbok Jul 13 '20

Thanks for the tip! The book I'm learning from, Automate the Boring Stuff, hasn't talked about f-strings yet, so I didn't know about them, but now that you told me, I'll try to make use of them in future programs :)

14

u/omarsika Jul 13 '20

He talks about it in the section on string formatting which im sure you'll reach quite. I'm currently taking the video course on udemy and he explains it really well!

13

u/shiny_arbok Jul 13 '20

Yeah I had a feeling that it would be discussed in a later chapter... Currently I'm on chapter 4, which teaches things about lists

That one's a bitch to learn tho in my opinion

5

u/jarvis125 Jul 13 '20

Believe me, you'll love lists once you get used to them. Probably one of the most useful data structure in python.

4

u/Beefy-py Jul 13 '20

You'll find even more topics that are a bitch to learn. But you'll get them if you use them frequently.

1

u/tdubbau Jul 13 '20

A walk in the park next to the regular expressions chapter, IMO haha! :) longest 1.5 hours of video lessons (+ the book) I’ve ever watched, and I still don’t feel I “recall enough” to move forward yet.

5

u/black_daveth Jul 14 '20

move forward anyway, you don't need to memorise everything off by heart and nobody does anyway (unless its core to their day to day work of course).

most important thing to remember is what regular expressions are and how they might be able to make your life easier - just enough to be able to recognise good opportunities to use them - then when said opportunities arise you RTFM.

2

u/Beefy-py Jul 13 '20

They are really useful

3

u/physicsking Jul 13 '20

Why fstrings vs string concatenation? I suppose fstrings might be slightly easier to read, but is there other downsides of concatenation?

10

u/NFLAddict Jul 13 '20

not sure I understand your question. There is more than one way to concat strings. fstrings are used for concatenation. They are far easier to read, and support various forms of string formatting. Just a couple examples:

If I have two strings:

s1 = 'string1'
s2 = 'string2'

print(f"I have two strings: {s1} and {s2}")
>> I have two strings: string1 and string2

But, they don't have to be strings. They can be of any type:

name = "Bob"
salary = 100_000

print(f"{name} makes ${salary} each year")
>> Bob makes $100000 each year

#Let met just format that last bit more nicely:   

print(f"{name} makes ${salary:,.2f} each year")
>> Bob makes $100,000.00 each year

I can't think of a reason to not use them

1

u/remuladgryta Jul 14 '20

I can't think of a reason to not use them

I can think of 2 off the top of my head:

  • When you want to support Python versions < 3.6

  • When you want to format a value that isn't in scope. You could do that with a callback instead, but you might not want to have to deal with potential side-effects.

1

u/PlanetaryGhost Jul 13 '20

From my understanding, it's just cleaner coding and (for most people) looks cleaner.

1

u/sdmcclain Jul 14 '20

In general, it's wise to be wary of concatenating strings, because they are immutable data structures in Python (so every concatenation creates a new object).

For printing a couple of things to stdout it's not big deal, but if you are considering using += to append to a string in a loop, then it's definitely better to append the individual strings to a list, and use a " ".join() to create the final string once you have all of the data.

1

u/xain1112 Jul 14 '20

Is there a difference between f"...{x}..." and "...{}...".format(x)?

1

u/NFLAddict Jul 14 '20

If you're only passing in a couple parameters, I'd say there's not really a huge difference, but when you're dealing with several, or potentially more, f-strings are so much more readable, given that its far more explicit: not to mention less prone to error. As you don't have to remember the order, and its clear to anyone reading, what value is being passed in where.

1

u/r_booza Jul 14 '20

. No value for x possible") 

. is the same thing as writing else or is there a difference to else?

1

u/NFLAddict Jul 14 '20

an else in what sense?
I was showing OP, a way to write the 3 different print statements in one print statement. no value for x possible is what OP chose to printout, when the value of the discriminant was less than zero.

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 cmath package. If you change the import math line to:

import cmath then 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.

https://docs.python.org/3/tutorial/errors.html

1

u/CommentRipper Jul 25 '20

The way you treasure your loved ones is incredible.

1

u/CommentRipper Jul 25 '20

You're an awesome friend.

1

u/CommentRipper Jul 25 '20

You're a great listener.

7

u/[deleted] 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

u/yuhyuh_ Jul 13 '20

You are correct

2

u/[deleted] 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

u/[deleted] 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

u/[deleted] 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

u/[deleted] Jul 13 '20

good for you man carry on never give up

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 char

char = 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

u/shiny_arbok Jul 13 '20

I see, thanks!

2

u/[deleted] Jul 14 '20

Congo !

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

u/buffafboii Jul 13 '20

wait, you guys are actually reading the books?

4

u/Beefy-py Jul 13 '20

That's cool for a first program.

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

u/skellious Jul 13 '20

so I just threw one in there for practice

This made me laugh, thanks.

3

u/[deleted] 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

u/Python119 Jul 14 '20

Congratulations and Happy Cake Day!!!

2

u/[deleted] 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

u/RobinsonDickinson Jul 13 '20

I wish i understood math lol

2

u/iggy555 Jul 13 '20

👍🏿

2

u/1987_akhil Jul 13 '20

Cheers and keep going.

2

u/SweetJinx Jul 13 '20

Way to go... Cheers.

1

u/[deleted] Jul 13 '20

Congratulations! Keep up the good work!

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

u/Slightlysalty24 Jul 13 '20

Nice! Keep it up

0

u/[deleted] Jul 13 '20

[deleted]

2

u/shiny_arbok Jul 13 '20

Thanks for the tip, I'll check it out :)

0

u/[deleted] Jul 14 '20

[removed] — view removed comment

1

u/shiny_arbok Jul 14 '20

print("( ͡° ͜ʖ ͡°)")