How to use if condition inside a loop? - python

I want to solve a problem given by our teacher. The problem is: make a Python program that verifies if a number is a perfect square. If it's a perfect square it, shows a message and if not it shows another message.
This is my attempt:
n = int(input('choose a number'))
for i in range(1,n):
if n//i==i:
d=i
print(n,'is a perfect square and its root is,',d)
During my attempt, I couldn't add the else condition where the number is not a perfect square.

Using your range method and without importing math, you could have done this:
n = int(input('choose a number: '))
for i in range(1,n+1):
if i**2 == n: ## square the i and see if it equals n
print(n,'is a perfect square and its root is:',i)
break ## stop here
else:
if i == n: ## when all the i's have been tried, give up
print(n,'is not a perfect square')

you gave this a good go. Has your teacher taught you about importing modules yet? Basically, a module is like a Python file, and you can take functions from that file and use them in your file. One module is 'math' and holds a function called 'sqrt' that calculates the square root of a given number. If this square root is a whole number (has no remainder) the given number is square -- is not, it's not square. See the program I wrote below:
import math
num = int(input("Number = "))
square_root = math.sqrt(num)
if square_root % 1 == 0:
print(f"It's square. {int(square_root)} squared gives {num}")
else:
print("It's not square")

Related

Function call unresolved reference

for my coding course we had to make a lottery odds calculator, which has to include 2 functions and a main function. However, when I am trying to call one funtion to the main one I get the unresolved reference error. I don't know why it is doing it, this is the first exercise where I have 2 functions and a main. It might be that I have 2 bad/useless functions, since the instructions said to choose whatever functions seem logical.
from math import factorial
def fraction(prob):
frac=1/prob
return frac
def winProb(total, drawn):
facTot=factorial(total)
facDraw=factorial(drawn)
facBoth=factorial(total-drawn)
prob = float(facTot/(facBoth*facDraw))
return prob
def main():
total=int(input("Enter the total number of lottery balls: "))
drawn=int(input("Enter the number of the drawn balls: "))
if total < 0:
print("The number of balls must be a positive number.")
elif drawn <0:
print("The number of balls must be a positive number.")
elif drawn > total:
print("At most the total number of balls can be drawn.")
else:
print("The probability of guessing all", drawn, "balls correctly is 1/", fraction(prob))
if __name__ == "__main__":
main()
Unresolved reference comes when I try to call fraction(prob) in the last line
The full error probably tells you that prob is undefined. While you may have defined it within winProb it is out of the scope of main so it doesn't exist there yet. You need to define prob right after total and drawn within main:
prob = winProb(total, drawn)
Alternatively, replace fraction(prob) with fraction(winProb(total, drawn))

Riemann sum python

I need to make a python function where i can find the surface with the riemann sum. This is what i have , and with the feedback of my teacher i am very close to it, but it does not work as properly as i want. the teacher said also something about try-catch what means that i need to make an extra code to control the answer (if im not wrong) To find the surface the uppper and the lower limits are asked and how many rectangles you want under the line like in the program.
(edit) I have made a new program , could you guys check if this is correct.
import math
def f(x): return math.sqrt(x) #Function in the left!
a = int(input("What is the lowerlimit?:"))
b = int(input("What is the upperlimit?:"))
n = int(input("How many division intervals do you want?:"))
dx = (b-a)/n;
xi = 0;
sum = 0;
for i in range(n):
xi = xi+dx;
sum = sum + f(xi)
print("The surface under the line is ", (sum*dx))
#einde programma!
import math
def f(x):
return math.sqrt(x) #Function in the left!
def positiveinput(message):
while True:
try:
c = int(input(message))
if c <= 0:
raise ValueError
break
except ValueError:
print("Oops! That was no valid number. Try again...")
a = positiveinput("What is the lowerlimit?: ")
b = positiveinput("What is the upperlimit?: ")
c = positiveinput("How many division intervals do you want?: ")
a = int(input("What is the lowerlimit?:"))
b = int(input("What is the upperlimit?:"))
c = int(input("How many division intervals do you want?:"))
dx = float((b-a)/c)
xi = a
Sum = dx
for i in range(0,c):
xi = a - dx
Sum = Sum + f(xi)
print("The surface under the line is ", (sum*dx))
There are a few issues with the code above:
1) Most importantly, You don't actually calculate the correct answer because you are assuming that the lower limit is equal to 0. Instead of writing xi=0 you should be writing xi=a!!! (Note that this will use the far end of each rectangle to calculate the height - if you want to use the lower end, and don't want to change any other code you will need to write xi = a - dx so you start on a. (Having said that, I wouldn't do it this way, but this is how to fix this without changing anything else).
2) Validation errors: There are a few things you should check:
That the values of a, b are valid numbers (note they shouldn't really have to be integers, just numbers). You can use float() to convert something to a number, just as you would use int() to convert to an integer.
that n is an integer and is not equal to 0, as that will raise an error, when you try and divide by n,
that n is not negative, as this will result in you getting the wrong value (with the code as it is).
Having said that, I would not write the code as it is. Using a for-loop and then incrementing your value is not a very pythonic thing to do. You might be interested to learn you can actually specify a lower bound and an upper bound using the range function. Experiment with:
for i in range(3,11,0.5):
print(i)
See what happens. I'm not going to give you a full solution, as this is a homework assignment, and it will benefit you most to work it out yourself, but hopefully this points you these things will point you in the right direction.
As #Sadap said, you can try something like this:
def positiveinput(message):
while True:
try:
n = int(input(message))
if n <= 0:
raise ValueError
break
except ValueError:
print("Oops! That was no valid number. Try again...")
a = positiveinput("What is the lowerlimit?:")
b = positiveinput("What is the upperlimit?:")
n = positiveinput("How many division intervals do you want?:")
Having this code as a guide, you can complete the list of errors verification that #tim-mccurrach have written in an answer to this post. Also you can check out this link where they make the Riemann Sum in a different way. For documentation about try-catch you can enter this link.

Creating a small program in python

I'm trying to make a program in Python 3.5 that asks the user to enter a number from 1 to 9. The the program will also guess a number from 1 to 9. If the user guesses the same number correctly, then the program will print Correct . Otherwise, the program will print Wrong. I wrote a program. Everything went fine with my code. However, when I guessed a number correctly, the program suddenly wrote Wrong instead of Correct. What am I doing wrong?
Here is my code:
print('Enter a number from 1 to 9')
x = int(input('Enter a number: '))
import random
random = print(random.randint(1,9))
if int(x) != random:
print ('Wrong')
else:
print ('Correct')
You are saving the result of a print() call (and masking random). print() returns None, so it will always be unequal to an integer, and therefore always "wrong."
import random
print('Enter a number from 1 to 9')
x = int(input('Enter a number: '))
r = random.randint(1,9)
if x != r:
print('Wrong')
else:
print('Correct')
Also note that I've moved the import statement to the top, avoided a second int() cast on something you've already done that to, and removed the space between the print reference and its arguments.
Here is the mistake,
random = print(random.randint(1,9))
You need to do something like this.
random = random.randint(1,9)
print(random)
Also, you have already converted the input to int so, you can do just this.
if x != random:
As pointed out your mistake is the line
random = print(random.randint(1,9))
But why?
functions (like print() take something, do something (with it) and give something back.
Example:
sum(3,4) takes 3 and 4, may add them and returns 7.
print("Hello World") on the other hand takes "Hello world", prints it on the screen but has nothing useful to give back, and therefore returns None (Pythons way to say "nothing").
You then assign None to the name random and test if it equals your number, which it (of course) doesn't.

Being told I have an infinite loop, but I'm unsure how to fix it. (Python Coding Course)

I'm currently in a python coding class and this is an assignment. I apparently have an infinite loop somewhere in my code, yet I can't seem to find it.
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
# At this point the program should take your now factorial and give you the fibonacci sequence
# takes your factorial and makes it the fibonacci
nterms = factorial
# first two terms
n1 = 0
n2 = 1
count = 2
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence:")
print(n1)
else:
print("Fibonacci sequence:")
print(n1,",",n2,end=', ')
while count < nterms:
nth = n1 + n2
print(nth,end=' , ')
# update values
n1 = n2
n2 = nth
count += 1
I've used both the debugging tool and attempted to find the problem myself by running the programming and attempting various break sequences but I'm just not grasping it.
There is no infinite loop in your code, both loops will finish in finite time. What is happening is that your teacher, without looking at your code, has discovered that the finite time is very, very long and mistaken this for an infinite loop.
The reason it's taking so long is that you have misunderstood the question - "I was asked to make a program that took an integer and gave me said factorial of an integer. Then give the Fibonacci sequence of the integer" - means find the factorial and Fibonacci sequence of the same integer rather than feeding the first result into the second. Simply replace the line nterms = factorial with the line nterms = num to fix the problem.
(See comments on question for additional information used in this answer)
First, you already know what a loop is and how it works. You should review the loop in your code and make sure any variable used is defined. Since this is an assignment, this is the best I can do for you, to be honest your problem is already solved.
Maybe try enclosing your code in a function with arguments/input-variables, this way your code might run smoother and better. Hope this helps.

UnboundLocalError, and TypeError

I am a beginner. My error is UnboundLocalError: local variable 'n' referenced before assignment. I have looked for answers but I dont understand most of the code.
def numberOfSquares(n):#This is where I get the user input.
n= int(input("Please input a number higher than 1 to be the number of squares drawn."))
while n < 0:
print("Please try another number.")
n= int(input("Please input a number higher than 1 to be the number of squares drawn."))
print("Thanks for your contribution!")
def main():# I call the other function in this one, and draw n number of squares. I have not even put #the different colors on it yet.
numberOfSquares(n)
import turtle
for i in range(n):
turtle.circle(40,steps= 4)
turtle.left(45)
turtle.forward(50)
n-=1
turtle.write("Colors of the Rain")
main()
It seems that you are misusing method variables. You are passing n to numberOfSquares while you really want to get a return value instead.
def number_of_squares():
# Your code here, and finally
return n
Then in your main():
n = number_of_squares()
As to the second error, you have a typo. The method turtle.cicrle receives steps argument not step.
turtle.circle(40, steps=4)
And finally, there is a strong naming convention in python. All methods should be lower-case with underscores like number_of_squares, not camel-case (numberOfSquares).

Categories