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

View all comments

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.