I am relatively new to python, and have been working on a problem to find the prime numbers between two inputs. I have a solution that works (helped somewhat by online searching too), but am unsure on why the else statement shown below should not be at the same tab setting as the if statement. If it is, though, it doesn't work correctly. Can anyone clarify this for me?
My code is here:
n1 = int(input("Enter the lower number: "))
n2 = int(input("Enter the higher number: "))
for num in range(n1, n2 + 1):
if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
print(num)
You're seeing Python's (rather unique) for:else: pattern, to execute something when a break is not encountered within the for suite:
When the items are exhausted, the suite in the else clause, if present, is executed, and the loop terminates.
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. [...]
Related
I am new to python and I am taking a summer online class to learn python.
Unfortunately, our professor doesn't really do much. We had an assignment that wanted us to make a program (python) which asks the user for a number and it determines whether that number is even or odd. The program needs to keep asking the user for the input until the user hit zero. Well, I actually turned in a code that doesn't work and I got a 100% on my assignment. Needless to say our professor is lazy and really doesn't help much. For my own knowledge I want to know the correct way to do this!!! Here is what I have/had. I am so embarrassed because I know if probably very easy!
counter = 1
num = 1
while num != 0:
counter = counter + 1
num=int(input("Enter number:"))
while num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
There are a couple of problems with your code:
You never use counter, even though you defined it.
You have an unnecessary nested while loop. If the number the user inputs is even, then you're code will continue to run the while loop forever.
You are incorrectly using the else clause that is available with while loops. See this post for more details.
Here is the corrected code:
while True:
# Get a number from the user.
number = int(input('enter a number: '))
# If the number is zero, then break from the while loop
# so the program can end.
if number == 0:
break
# Test if the number given is even. If so, let the
# user know the number was even.
if number % 2 == 0:
print('The number', number, 'is even')
# Otherwise, we know the number is odd. Let the user know this.
else:
print('The number', number, 'is odd')
Note that I opted above to use an infinite loop, test if the user input is zero inside of the loop, and then break, rather than testing for this condition in the loop head. In my opinion this is cleaner, but both are functionally equivalent.
You already have the part that continues until the user quits with a 0 entry. Inside that loop, all you need is a simple if:
while num != 0:
num=int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
I left out the counter increment; I'm not sure why that's in the program, since you never use it.
Use input() and If its only number specific input you can use int(input()) or use an If/else statement to check
Your code wasn't indented and you need to use if condition with else and not while
counter = 1
num = 1
while num != 0:
counter = counter + 1
num = int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
Sample Run
Enter number:1
Odd 1
Enter number:2
Even 2
Enter number:3
Odd 3
Enter number:4
Even 4
Enter number:5
Odd 5
Enter number:6
Even 6
Enter number:0
Even 0
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.
My Error
Python throws a syntax error pointed at the last "e" of "else:", preceded by an if statement and inside a while loop.
My Objective
Test if certain parameters are true, if true then go to the beginning of the loop and if not true then perform certain statements and increment a value.
My Source Code
from random import randint
def returnDigRoot(num):
digs = []
while len(str(num)) != 1:
num = str(num)
for each in num:
digs.append(each)
num = int(num)
digs = [int(i) for i in digs]
num = sum(digs)
return(num)
def rnum():
return(randint(1,99999))
ran_nums = []
sols = []
it = 1
The problem area is here
while it <= 3:
print("Generating numbers")
current = randint(1,99999)
print("randomly intializing the 'current' int value")
print("testing if the digital root is greater than 6")
if returnDigRoot(current) > 6:
print("going back to start of loop")
continue
print("testing if it isnt")
else:
ran_nums.append(current)
print("append 'current' to ran_nums")
sols.append(returnDigRoot(current))
print("appending its digital root to sols")
it += 1
print("incrementing the iterator variable")
My Research
I looked at many questions on StackOverflow and other sites and could not find a solution to my problem; most problems people had with else statements were related to tabbing errors, preceding errors (which I checked for), no preceding if statement, or multiple else statements.
Thanks in advance for any help.
print("testing if it isnt") needs to be indented. As it stands, your code doesn’t really relate the if with the else because of the indentation. It’s like writing something like this in C:
if(<condition>)
{
<action>
}
prinf(...)
else
{
<action>
}
Just align the print line with the rest of the code under the if statement.
The line:
print("testing if it isnt")
isn't indented correctly. You can't have anything in between an if block and the else block.
Your statement:
print("testing if it isnt")
is indented to the wrong level; that makes the else: that follows an independent statement, which is syntactically wrong. Probably you meant that print statement to follow the else and be indented one level.
This is most likely a indentation/space/tabbing issue since I copy pasted the code and I don't get any errors. Though I am on Python 2.7.10. (Repasting it here to ensure you can copy paste the same and try):
from random import randint
def returnDigRoot(num):
digs = []
while len(str(num)) != 1:
num = str(num)
for each in num:
digs.append(each)
num = int(num)
digs = [int(i) for i in digs]
num = sum(digs)
return(num)
def rnum():
return(randint(1,99999))
ran_nums = []
sols = []
it = 1
while it <= 3:
current = randint(1,99999)
if returnDigRoot(current) > 6:
continue
else: # this is where the error is pointed
ran_nums.append(current)
sols.append(returnDigRoot(current))
it += 1
On an unrelated note, that while loop will take a long time to exit since the exit criteria is very small (two current <=36 only will cause exit).
I have previously studied Visual Basic for Applications and am slowly getting up to speed with python this week. As I am a new programmer, please bear with me. I understand most of the concepts so far that I've encountered but currently am at a brick wall.
I've written a few functions to help me code a number guessing game. The user enters a 4 digit number. If it matches the programs generated one (I've coded this already) a Y is appended to the output list. If not, an N.
EG. I enter 4567, number is 4568. Output printed from the list is YYYN.
import random
def A():
digit = random.randint(0, 9)
return digit
def B():
numList = list()
for counter in range(0,4):
numList.append(A())
return numList
def X():
output = []
number = input("Please enter the first 4 digit number: ")
number2= B()
for i in range(0, len(number)):
if number[i] == number2[i]:
results.append("Y")
else:
results.append("N")
print(output)
X()
I've coded all this however theres a few things it lacks:
A loop. I don't know how I can loop it so I can get it to ask again. I only want the person to be able to guess 5 times. I'm imagining some sort of for loop with a counter like "From counter 1-5, when I reach 5 I end" but uncertain how to program this.
I've coded a standalone validation code snippet but don't know how I could integrate this in the loop, so for instance if someone entered 444a it should say that this is not a valid entry and let them try again. I made an attempt at this below.
while myNumber.isnumeric() == True and len(myNumber) == 4:
for i in range(0, 4)):
if myNumber[i] == progsNumber[i]:
outputList.append("Y")
else:
outputList.append("N")
Made some good attempts at trying to work this out but struggling to patch it all together. Is anyone able to show me some direction into getting this all together to form a working program? I hope these core elements that I've coded might help you help me!
To answer both your questions:
Loops, luckily, are easy. To loop over some code five times you can set tries = 5, then do while tries > 0: and somewhere inside the loop do a tries -= 1.
If you want to get out of the loop ahead of time (when the user answered correctly), you can simply use the break keyword to "break" out of the loop. You could also, if you'd prefer, set tries = 0 so loop doesn't continue iterating.
You'd probably want to put your validation inside the loop in an if (with the same statements as the while loop you tried). Only check if the input is valid and otherwise continue to stop with the current iteration of your loop and continue on to the next one (restart the while).
So in code:
answer = [random.randint(0, 9) for i in range(4)]
tries = 5
while tries > 0:
number = input("Please enter the first 4 digit number: ")
if not number.isnumeric() or not len(number) == len(answer):
print('Invalid input!')
continue
out = ''
for i in range(len(answer)):
out += 'Y' if int(number[i]) == answer[i] else 'N'
if out == 'Y' * len(answer):
print('Good job!')
break
tries -= 1
print(out)
else:
print('Aww, you failed')
I also added an else after the while for when tries reaches zero to catch a failure (see the Python docs or maybe this SO answer)
I wrote a program in Python to generate prime numbers
here is the program
def genPrimes(n):
primes = [2] # primes generated so far
last = 3 # last number tried
while last <= n:
for p in primes:
if last % p == 0 and math.sqrt(p) <= last:
break
else:
primes.append(last)
last += 2
return primes
http://codepad.org/d33tsQyT
This program is producing a right answer. If you see the indentation for else: statement it is wrongly placed. if i try to place the else statement in if block interpreter is showing memory error. Can anyone tell why this is happening.
Thanks in advance
Maries
The else is actually attached to the for loop, and executes if the program doesn't break out of the loop. In your case, it executes if none of the primes divide into the number, so the number is prime and gets appended to the list.
See also the documentation.
It's not placed incorrectly, python is assuming you're using a for-else loop.
From the docs:
When used with a loop, the else clause has more in common with the
else clause of a try statement than it does that of if statements: a
try statement’s else clause runs when no exception occurs, and a
loop’s else clause runs when no break occurs.