How do I turn whole floating point numbers into integers? [duplicate] - python

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.

Related

Why does my code think 100 is smaller than 50? [duplicate]

This question already has answers here:
Comparing numbers give the wrong result in Python
(4 answers)
Closed 11 months ago.
I coded a small project that you can enter two numbers in and it will tell you what's smaller and what's bigger, what's the difference between them and if they're equal, but the code thinks that 100 is smaller than 50.. I've also entered numbers like 50;70 and 60;70, but then it says the correct thing which is that the first number is smaller than the second one. I don't understand what's wrong, and how can I fix it? Here's my code, you can run it yourself so you can see what will happen.
import math
import time
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
difference = num1 - num2
if str(num1) > str(num2):
print("--" + str(num1) + " is greater than " + str(num2) + ".")
print("--The difference between " + str(num1) + " and " + str(num2) + " is " + str(difference) + "." )
elif str(num1) < str(num2):
pass
print("--" + str(num1) + " is smaller than " + str(num2))
print("--The difference cannot be calculated because " + str(num1) + " is smaller than " + str(num2) + ".")
else:
print(str(num1) + " and " + str(num2) + " are equal.")
The problem, as several commenters have pointed out, is that you're doing a string conversion on the input numbers.
As integers, 50 < 100, but for strings, ordering is done alphabetically - and "1" comes before "5", so "100" < "50".
Drop the str() calls and you should be good.

Is there a way to add to a variable every time an if statement is true

if a == tru:
correct += 1
qq = str(q)
aa = str(a)
print("you answered correctly! \n" + qq + " does equal " + aa)
print()
What I want to do is every time a equals tru, the variable correct adds 1. I tried using a while loop, but I think I set it up wrong because then correct remained zero. Is there any way to fix this?
Edit:
import random
u = input("how many questions?\n")
y = int(u)
for x in range(y):
s = random.randint(1,12)
r = random.randint(1,12)
q = (str(s) + " * " + str(r))
a = int(input(q + "="))
tru = (s*r)
correct = 0
if a == tru:
correct += 1
qq = str(q)
aa = str(a)
print("you answered correctly! \n" + qq + " does equal " + aa)
print( )
elif a != tru:
qq = str(q)
aa = str(a)
truu = str(tru)
print("sorry, " + qq + " does not equal " + aa)
print(qq + " equals " + truu)
print( )
o = str(l)
print("You got "+ o +" out of "+ u)
This will add more context. The code asks how many questions you want, then gives you basic multiplication questions and tells you whether it is correct. I want to add a message that says "you got ___ out of ___" at the end. Please tell me if you have any other suggestions on how to do this.
Edit 2:
I had correct=0 in a for loop, meaning every time it looped correct was reset. Whoops. Anyway, if you come across this and want to use it to help teach basic multiplication, just move the correct=0 out of the for loop and it should work.
It's difficult to say exactly what could be going wrong given the code you've submitted, but as long as correct is stored outside your loop, incrementing it in this way should work just fine. Below is a working example that demonstrates this.
test = [[True, "Question 1"], [False, "Question 2"], [True, "Question 3"]]
correct = 0
for a, q in test:
if a:
correct += 1
print("You answered correctly!")
print(f"{q} does equal {a}")
else:
print("Incorrect answer.")
print(f"{q} does not equal {a}")
print()
print(f"{correct} out of {len(test)} questions were answered correctly.")
Output
You answered correctly!
Question 1 does equal True
Incorrect answer.
Question 2 does not equal False
You answered correctly!
Question 3 does equal True
2 out of 3 questions were answered correctly.

How do I make a repeating 'if' statement until a condition is met?

I'm trying to make a python program that runs the Euclidian algorithm. This is my current code:
a = float(input())
b = float(input())
aplha = float(a/b)
omega = float(b/a)
import math
if a > b:
print(str(a) + " = " + str(b) + " * " + str(math.floor(aplha)) + " + " + str(a%b))
elif b > a:
print(str(b) + " = " + str(a) + " * " + str(math.floor(omega)) + " + " + str(b%a))
else:
print("Both numbers have the same value. The greatest common denominator is 1.")
How do I make it so that the if and elif keeps repeating themselves until a%b = b%a = 0?
Here is one way to implement the Euclidean algorithm.
import math
a = float(input())
b = float(input())
# The greatest common denominator of a and b
def gcd(a,b):
while (b != 0):
t = b
b = a % b
a = t
return a
if (a > b):
print(f'{a} = {b} * {math.floor(a/b)} + {a%b}')
else:
print(f'{b} = {a} * {math.floor(b/a)} + {b%a}')
print(f'The greatest common denominator of {a} and {b} is {gcd(a,b)}')
if a==b it is not necessarily true that the GCD is one. Consider a = 150 and b = 150 as a counter example. The greatest common denominator of a and b is 150. gcd(a,b) = 150.
Also a note on print(f'string{var}').
Print f-string is new in Python 3 and really helpful for printing the value of variables. The way it works is
>>> var = 5
>>> print(f'The value of var is {var}')
"The value of var is 5"

Python Factorial Program - Printing the Equation

I am writing a program that calculates the factorial of a number, I am able to display the correct answer, however along with the answer I need the actual calculation to display, I am having trouble with that. So for example, when the user enters 4, I need it to display as:
I have been trying to figure out the right code, but do not know what to do.
Here is the code I have so far
number = int(input("Enter a number to take the factorial of: "))
factorial = 1
for i in range(1, number + 1):
factorial = factorial * i
print (factorial)
Right now, it displays the correct answer, however I need for it to include the equation as well as follows: 4! = 1 x 2 x 3 x 4 = 24
The simplest approach is to construct the string as you are iterating:
equation = str(number) + "! = "
factorial = 1
for i in range(1, number + 1):
factorial = factorial * i
equation += str(i) + "x"
equation = equation[:-1] + " = " + str(factorial)
print(equation)
Note that this method appends an unwanted 'x' after the last factor. This is removed by equation[:-1].
Alternatively, you could append this one-line solution to the end of your code. It uses the join method of the string class to concatenate an array of strings:
print(str(number) + "! = " + "x".join(str(n) for n in range(1, number + 1)) + " = " + str(factorial))
As you loop through the numbers to be multiplied, you can append each number's character to a string containing the equation, e.g ans, and print it at last. At the end of the code, I omitted the last letter because I didn't want an extra 'x' to be displayed.
def fact(number):
num_string=str(number)
factorial = 1
ans=num_string+"!="
for i in range(1, number + 1):
factorial = factorial * i
ans+=str(i)+"x"
ans=ans[:-1]
print(ans)
return factorial
fact(4)
You can append each value to the list and then print the equation using the f-string:
num = 5
l = []
f = 1
for i in range(1, num + 1):
f *= i
l.append(i)
print(f"{num}! = {' x '.join(map(str, l))} = {f}")
# 5! = 1 x 2 x 3 x 4 x 5 = 120

Python - Error when correct answer is inputted

When I choose question 3, even I do put in the right answer(value_c * value_d, it tells me that it is incorrect. Help?
import random
value_a = random.randint(100, 999)
value_b = random.randint(100, 999)
value_c = random.randint(21, 89)
value_d = random.randint(21, 89)
value_e = random.randint(81, 100)
value_f = random.randint(81, 100)
print('''Straight to the point. Pick an option.
1. 2 numbers with 3-digit values added.")
2. 2 numbers with 3-digit values added and then multiplied by 2.
3. 2 numbers with 2-digit values and less than 89 multiplied.
4. 2 numbers with 2-digit values and between 80 and 100 multiplied.
5. 3 random numbers added or subtracted.''')
question = int(input("Choose the type of question you want: "))
print("\n")
if question == 1:
answer = int(input(str(value_a) + " + " + str(value_b) + " : "))
if answer == value_a + value_b:
print("Dayum quicc mafs, trie again if yu wand.")
else:
print("Bed mafs.")
elif question == 2:
answer = int(input( "(" + str(value_a) + "+" + str(value_b) + ")"+ "*2" + " : "))
if answer == 2*(value_a + value_b):
print("Dayum quicc mafs.")
else:
print("Bed mafs, trie again.")
this is the part where my answer never seems to be right:
elif question == 3:
answer == int(input(str(value_c) + " * " + str(value_d) + " : "))
print(value_c, value_d)
if answer == value_c * value_d:
print("Dayum quicc mafs.")
else:
print("Bed mafs, trie again.")
In Python, a single = means assignment. You used a double == which is an equality operator. Don't confuse the two, since the answer is not being assigned. Below I have changed the == to =.
elif question == 3:
answer = int(input(str(value_c) + " * " + str(value_d) + " : "))
print(value_c, value_d)
if answer == (value_c * value_d):
print("Dayum quicc mafs.")
else:
print("Bed mafs, trie again.")

Categories