Why is python skipping a line? - python-2.7

I'm pretty new to Python (just started teaching myself a week ago), so my debugging skills are weak right now. I tried to make a program that would ask a user-submitted number of randomly-generated multiplication questions, with factors between 0 and 12, like a multiplication table test.
import math
import random
#establish a number of questions
questions = int(input("\n How many questions do you want? "))
#introduce score
score = 1
for question in range(questions):
x = random.randrange(0,13)
y = random.randrange(0,13)
#make the numbers strings, so they can be printed with strings
abc = str(x)
cba = str(y)
print("What is " + abc + "*" + cba +"?")
z = int(input("Answer here: "))
print z
a = x*y
#make the answer a string, so it can be printed if you get one wrong
answer = str(a)
if z > a or z < a:
print ("wrong, the answer is " + answer)
print("\n")
#this is the line that's being skipped
score = score - 1/questions
else:
print "Correct!"
print ("\n")
finalscore = score*100
finalestscore = str(finalscore)
print (finalestscore + "%")
The idea was that every time the user gets a question wrong, score (set to 1) goes down by 1/question,so when multiplied by 100 it gives a percentage of questions wrong. However, no matter the number of questions or the number gotten wrong, score remains 1, so finalestscore remains 100. Line 26 used to be:
if math.abs(z)-math.abs(a) != 0:
but 2.7.3 apparently doesn't acknowledge that math has an abs function.
Such a simple accumulator pattern doesn't seem like it would be an issue, even for an older version of Python. Help?

Try score = score - 1.0/questions
The problem is that you're doing integer division, which truncates to the nearest integer, so 1/questions will always give 0.

The problem is that you are using integers for all of your calculations. In particular, when you calculate 1/questions, it truncates (rounds down) to an integer because both values in the calculation are integers.
To avoid this, you could instead use 1.0/questions to make the calculations use floating point numbers instead (and not truncate)

Related

Python 2 - Division times 10 returns 0 everytime

When the program divides two user inputted numbers, then times that, the program returns 0 every time
correct = input("User, Input the amount of correct answers. :")
points_possible = input("User, Input the amount of points possible. :")
score = correct / points_possible
grade = score * 10
print grade
The expected output
if (1/2) * 10 = 5, but will output 0
If you are using Python 2.7 version, the input that would be taken from the console would always be in the form of strings. So, you'll need to convert it to integers.
#code in Python 3.5
correct = int(input("User, Input the amount of correct answers. :"))
points_possible = int(input("User, Input the amount of points possible. :"))
score = correct / points_possible
grade = score * 10
print(grade)
The reason why you're just getting 0 in Python 2 is that if integers are given then you'll get integer division only. If you want float division, you need to make sure there is a decimal point somewhere so that Python knows it doesn't have to truncate the value to an int.
#code in Python 2.7
correct = float(raw_input("User, Input the amount of correct answers. :"))
points_possible = float(raw_input("User, Input the amount of points possible. :"))
score = correct / points_possible
grade = score * 10.0
print grade
it's because python needs you to make it understand that you divide by a float: you can either add .0 at the end of the diviser or type 10/float(2)

How do I get imaginary numbers without using cmath when calculating the quadratic equation?

I'm currently having trouble understanding how to make imaginary numbers appear when I'm doing the quadratic equation. My assignment is to make the quadratic equation, and get imaginary numbers but I'm having an extremely difficult time getting there.
any help you can offer would be great!
Here is the code i currently have:
import math
print "Hello, please insert 3 numbers to insert into the quadratic equation."
a = input("Please enter the first value: ")
b = input("Please enter the second value: ")
c = input("Please enter the third value: ")
rootValue = b**2 - 4*a*c
if rootValue < 0:
print (-b-(rootValue)**(.5)) / (2 * a)
if rootValue > 0:
print ((-b + (rootValue)**(1/2)) /(2 * a))
if rootValue == 0:
print -b/(2*a)
please help!!! i'm so stuck right now.
I think you have to do something with the problem if rootValue < 0; but I'm not sure how to do that.
I'm also not allowed to use 'import cmath', I'm supposed to make it so that you can just do this this way.
There are a couple of problems with your code besides how to represent complex numbers. Remember that if rootValue <> 0, there are ALWAY TWO roots:
(-b +/- sqrt(rootValue)/ 2a
It doesn't matter if the rootValue is positive or negative, there's still two roots. You are branching and only providing one of the two roots in each case. No need for the first two if statements
To make rootValue complex, so that you can have complex result when you take the square root, either set it equal to complex(b2 - 4*a*c, 0) or to (b2 - 4*a*c, 0) + 0j.
You want to raise things to the 0.5 power for each of the two roots, NOT the (1/2) power, as you've done in one statement
For completeness, you may want to deal with the a = 0 case.
If you still have problems, let us know.

More Decimal Places In Python

Here is my python code:
import math
import decimal as dec
import numpy as np
import matplotlib.pyplot as plt
c = 3e8
wave = np.array([253.6e-9,283e-9,303.9e-9,330.2e-9,366.3e-9,435.8e-9])
freq = c/wave
potent = np.array([2.6,2.11,1.81,1.47,1.10,0.57])
m,b = np.polyfit(freq,potent,1)
print m,b
e = 1.6e-19
planck = m*e
print planck
plt.plot(freq,potent,'r.')
x = np.linspace(0,10,11)
y = m*x + b
plt.plot(x,y,'b-')
To be specific, I am having trouble at the line containing y = m*x + b. The output of said line is
array([-2.27198136, -2.27198136, -2.27198136, -2.27198136, -2.27198136,
-2.27198136, -2.27198136, -2.27198136, -2.27198136, -2.27198136,
-2.27198136])
This result is due to the fact that the magnitude of slope 'm' is rather small, and the magnitude of 'b' is rather large. So, how might I overcome this obstacle?
Also, if I write plt.plot(freq,potent,'r.') and plt.plot(x,y,'b-'), will it overlay the plots?
The problem you are facing is called "Loss of significance" or "cancellation" It is rather a mathematical problem than a computer science one.
What you need to do is to change your algorithm so that cancellation does not occur any more. How to do this for simple cases is described here:
http://en.wikipedia.org/wiki/Loss_of_significance
But the change of the algorithm is not simple in some cases and may be impossible at all. If you do your calculation with more digits you do not really solve your problem. You rather postpone it. Once you change your numbers you might end up with the same problem again.
To display more decimal points add this to the end of your code:
print('%.60f' % value_x)
".60" indicates 60 decimal places to be displayed and "value_x" represents whatever value you want displayed.
I use this when I need to output the P-value as a real decimal number in addition to the default output which is in scientific notation.
Example:
In [1]: pearson_coef, p_value = stats.pearsonr(df['horsepower'], df['price'])
In [2]: print("The Pearson Correlation Coefficient is", pearson_coef, " with a P-value of P = ", p_value, "or ")
In [3]: print('%.50f' % p_value)
Out [4]: The Pearson Correlation Coefficient is 0.8095745670036559 with a P-value of P = 6.369057428260101e-48 or 0.00000000000000000000000000000000000000000000000637

While loop being skipped

I can't seem to get my while loop code to run inside my code. I bet it is very obvious but I cannot seem to find the answer for it. This program is supposed to let you choose how many numbers you want to have randomly chosen and the numbers it can be between. It seems that the while loop doesn't want to work. It skips the while loop and goes to the sleep(10). Thank you for the help!
import random
import time
from time import sleep
x = raw_input("Enter first number you want to be the minimum: ")
y = raw_input("Enter second number you want to be the maximum: ")
a = raw_input("Enter ammount of random numbers you want: ")
p = 1
while p >= a:
print "Your number is " + str(int(random.randint(x - 1,y + 1)))
p = p + 1
sleep(10)
raw_input returns a string. This means you are comparing a string to an integer for your while condition. A quick test shows integers are always "less than" strings.
>>> 10000 > '1'
False
>>> 10000 < '1'
True
Luckily, this behavior is changed in python3 where it throws a TypeError.

In python, how to convert specific values in a list to different values based on special conditions

I am trying to write a program that converts a percentage received in a class into a GPA format then eventually find the overall GPA. I want it to first prompt the user to input the amount of classes, then input the percentages. I am running into some trouble getting the program to convert the percentage into the GPA format (90 or greater equals 4, 80 to 89 equals 3, ect...). This is what I have so far
class_number = int(raw_input("How many classes do you have? "))
total_grade = list((raw_input("Enter Percentage: ")) for i in range(class_number))
a = total_grade
def alter(x):
if x >= 90:
return 4
elif x >= 80:
return 3
a = map(alter,a)
print a
The problem is that this only seems to output 4s no matter the original percentage.
Any help would be greatly appreciated! Thanks!
That's because x is actually a string. I think a string will always be greater than a number. You need to convert each item in total_grade to an int:
total_grade = list(int(raw_input("Enter Percentage: ")) for i in range(class_number))
Also, you can just use a list comprehension:
total_grade = [int(raw_input("Enter Percentage: ")) for i in range(class_number)]