This question already has answers here:
Formatting floats without trailing zeros
(21 answers)
Closed 1 year ago.
I just started coding for about a month now. I'm making my first actually useful program that finds the root/s of a quadratic equation. It's almost done and it needs a little bit more fixing but there's one thing I can't really seem to figure out.
Here's my code:
import math
filler = "Empty Here"
print("Please enter in integer coefficients a, b, and c")
operator_for_bx = " + "
operator_for_c = " + "
a = int(input("a="))
b = int(input("b="))
c = int(input("c="))
discriminant = b*b - 4*a*c
determinant = discriminant
root_positive = str(float((-b + math.sqrt(discriminant)) / (2*a)))
root_negative = str(float((-b - math.sqrt(discriminant)) / (2*a)))
root_one_real_sol = str(float((-b)/(2*a)))
if b < 0:
operator_for_bx = " - "
if c < 0:
operator_for_c = " - "
if a == 1:
print("Your quadratic equation is: " + "x^2" + operator_for_bx + str(abs(b)) + "x" + operator_for_c + str(abs(c)))
elif a == -1:
print("Your quadratic equation is: " + "-x^2" + operator_for_bx + str(abs(b)) + "x" + operator_for_c + str(abs(c)))
else:
print("Your quadratic equation is: " + str(a) + "x^2" + operator_for_bx + str(abs(b)) + "x" + operator_for_c + str(abs(c)))
if determinant == 0:
print("It only has 1 real solution.")
print("It's root is: " + root_one_real_sol + ".")
elif determinant >= 1:
print("It has 2 real solutions.")
print("The roots are: " + root_positive + " and " + root_negative + ".")
else:
print("It has 2 complex but not real solutions.")
You see, occasionally the answer I get for the roots turns out into a whole number. Which is fine and all, but the thing is I had to let it out as a float or else decimal numbers wouldn't work. So if ever a whole number would appear, it'd say "x.0",(x being whatever number came out) and I don't want a decimal point to be shown if it's a whole number so, how do should I make it so?
(Also yes I know this won't work for quadratic equations with 2 complex but not real solutions and I think I can fix that by myself- maybe I'll use the Try and Except stuff)
Here's an example code that could accomplish that:
x = [1.0, 2.0, 2.5, 3.5]
new_x = [int(i) if int(i) == i else i for i in x]
print(new_x)
Output:
[1, 2, 2.5, 3.5]
This uses list comprehension, but the main idea I want to show is that in order to check if something has nothing after "." you can just check that the int version of it is equal to the floating point version.
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 months ago.
name = input("Say your name: ")
integerr = input(name + " pick an integer ")
numberr = input(name + " pick another integer ")
This is where I get my error
if (integerr % numberr) >= 1:
print(integerr + " is divisible by " + numberr)
else:
print(integerr + " is not divisible by " + numberr)
You have two mistakes.
input always returns a string, as Simsteve7 mentioned. You can convert to an integer using int(), and convert to a string using str().
You need to check if integerr % numberr == 0, because that means that numberr divides into integerr evenly; thus integerr is divisible by numberr.
Below is a solution for Python 2:
name = input("Say your name: ")
integerr = int(input(name + " pick an integer "))
numberr = int(input(name + " pick another integer "))
if (integerr % numberr) == 0:
print(str(integerr) + " is divisible by " + str(numberr))
else:
print(str(integerr) + " is not divisible by " + str(numberr))
If you're using Python 3, you can use f-strings. That would look like this:
if (integerr % numberr) == 0:
print(f"{integerr} is divisible by {numberr}")
else:
print(f"{integerr} is not divisible by {numberr}")
def die():
first = str(randint(1, 6))
second = str(randint(1, 6))
total = first + second
print "You have rolled a " + first + " and a " + second + ", for a total score of " + total + "."
Standard die throwing game, but I'm struggling to print the values for individual die as well as the total. Treating as a string for individual, but then sum leads to concatenation rather than actual sum.
Thanks
Keep your variables as numbers and let print do the formatting:
def die():
first = randint(1, 6)
second = randint(1, 6)
total = first + second
print "You have rolled a", first, "and a", second, ", for a total score of", total, "."
Or you could do some formatting using str.format to have more control over the default inter-parameter spacing in the above:
print "You have rolled a {} and a {}, for a \
total score of {}.".format(first, second, total)
There are two ways to address your problem (and more still!). Firstly, you need to make sure you keep your integers as type int when adding them together, and then cast them to a string when you print them out.
You can do this like the below, using the str() casting method and + concatenation.
def die1():
"""Roll and print two dice using concat."""
first = randint(1, 6) # keep these as integers
second = randint(1, 6)
total = first + second # so addition works
# but now cast to str when printing
print "You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + str(total) + "."
But a handier way is to use the str.format() method to put placeholders in your string, and then let python cast and format the integer values for you. If you have big numbers with 4 or more digits, an advantage of this would be that you can use a string formatting code like "my big number: {0:d,}".format(1000000) to make your string output like "my big number: 1,000,000", which is much more readable.
def die2():
"""Roll and print two dice using str.format()."""
first = randint(1, 6)
second = randint(1, 6)
total = first + second
# or use the str.format() method, which does this for you
print "You have rolled a {0} and a {1}, for a total score of {3}.".format(first, second, total)
You can use casting to change the structure of the var. You can either use them as strings and for total use this line:
total = int(first) + int(second)
or use them as int and cast them to string in the print by using str(first) and str(second)
Best
print "You have rolled a " + str(first)
This would convert the int to a string, hence concatenating it.
Also, you can do
total = int(first) + int(second) to address the first issue.
You have two solutions:
Convert the numbers back to int before adding them:
def die():
first = str(randint(1, 6))
second = str(randint(1, 6))
total = str(int(first) + int(second))
print ("You have rolled a " + first + " and a " + second + ", for a total score of " + total + ".")
Convert the numbers into str before printing them:
def die():
first = randint(1, 6)
second = randint(1, 6)
total = first + second
print ("You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + str(total) + ".")
Either solution will work perfectly fine.
This would also work. Don't convert first and second to str until after you perform sum on them. Then remember to cast them as str in your print statement.
def die():
first = randint(1, 6)
second = randint(1, 6)
total = str(first + second)
print ("You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + total + ".")
Learning the basics of python and I am running across a problem. I'm sure it is a simple fix. I'm trying to get my program to get 20 different inputs before calculating the min, max, etc.
def main():
number = valueInput()
display(number)
def valueInput():
print("Please enter 20 random numbers")
values = []
for i in range(20):
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
values.append(value1)
return values
def display(number):
print("The lowest number is:", min(number))
print("The highest number is:", max(number))
print("The sum of the numbers is:", sum(number))
print("The average number is:", sum(number)/len(number))
main()
I can get it to work by repeating this line:
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
to the 20th number but there must be a way that makes it shorter and cleaner. Again I am a beginner so any explanation would be much appreciated.
All you have to do to fix your program is remove four spaces:
def valueInput():
print("Please enter 20 random numbers")
values = []
for i in range(20):
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
values.append(value1)
return values
The last line in the block above has been unindented by one level. Instead of returning after the first time through the loop, it lets the loop complete, and then returns the resulting list.
Also you can change your:
values = []
for i in range(20):
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
values.append(value1)
return values
part with:
values = [int(input("Enter a random number " + str(x + 1) + ": ")) for x in list(range(20))]
return values
You can check out build in functions
Why is this code wrong (from Python 3.3.2). All it outputs is 'invalid syntax' when I've looked over the code lots of times:
#Get the numbers from the useer
a = int(input("Enter number a: "))
b = int(input("Enter number b: "))
c = int(input("Enter number c: "))
d = a*b*c #Make d a times b times c
#Display the results
print (str(a) + " mutiplied by " + str(b) + "multiplied by" + str(c) " equals " + str(d)))
This is what it should output:
Enter number a: 5
Enter number b: 10
Enter number c: 3
5 multiplied by 10 multiplied by 3 equals 150
Thanks in advance
You forgot a + operator in that last line, and you have an extra close paren at the end of that line.
print (str(a) + " mutiplied by " + str(b) + "multiplied by" + str(c) " equals " + str(d)))
^^^ ^^^