I have a very simple issue here but not sure how to resolve it because I am new to Python.
I am writing a code to do calculations using if looping and would like to see the all the results generated by each loop.However, by running my current code below, it is only displaying the final result which should be 1.
Can anyone point out the problem and correct it?
n=int(raw_input("Enter a number: "))
while n !=1:
if n % 2 ==0:
n=n/2
else:
n=n*3+1
print n
The question above code is writing up for is as following:
given an integer n≥1, if n is even, divide by 2. If n is odd, multiply by 3 and add 1. Repeat this process with the new value of n. As far as anyone can tell, this always ends up with n=1
For example:
Enter a number: 22
22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
Python works based on indentation, if you have programmed with other languages before you may not have come a cross this. If you don't indent your code properly Python wont understand.
n=int(raw_input("Enter a number: "))
while n !=1:
if n % 2 ==0:
n=n/2
else:
n=n*3+1
print n
Will run the while loop and at the end print the final answer as you have said.
On the other hand,
n=int(raw_input("Enter a number: "))
while n !=1:
if n % 2 ==0:
n=n/2
else:
n=n*3+1
print n
Loops through until n doesn't equal one printing n each time.
Python is one of the few languages that works like this so this won't matter in other languges but does in python.
Indent your print n statement to put it inside the loop.
The indentation of the last print is wrong. Try this:
n=int(raw_input("Enter a number: "))
while n !=1:
if n % 2 ==0:
n=n/2
else:
n=n*3+1
print n
Related
Recently I was given a challenge to my coding skills by my teacher since he saw that I was already knowledgeable in what he was teaching. The question is as follows.
Create a program that prompts the user for 2 numbers. The program will then display all the prime numbers in between the two given numbers, including the given numbers. Note: You cannot assume the first input is bigger than the second input.
So I took this question and built a fairly simple algorithm and ran it and it worked. I opened it today to find out for some reason my output is occasionally wrong, for example when you input 8 and 29 I get 27. I am looking for HINTS as to what is wrong with my logic because I cannot for the life of me figure out what Im doing wrong. I dont want straight up fixes because I would like to learn as much from this and doing it as much as possible by myself.
numbers = [int(input("First Number")), int(input("Second Number"))]
numbers.sort()
numList = []
#Removing Even Numbers
for num in range(numbers[0],numbers[1] + 1):
if num % 2 != 0:
numList.append(num)
#Checking For Prime Numbers
for currNum in numList:
#Set Start number to divide
i = 2
while i < currNum:
#Checks if the currNum can be divisble by i and is a whole number
if currNum % i != 0:
i = i + 1
else :
numList.remove(currNum)
break
print(numList)
From what I have learned from testing this out it seems like 27 is never checked during my for loop or while loop even though it is in the numList array.
Never remove items form a list you are iterating over.
Instead create a new list:
numbers = [int(input("First Number")), int(input("Second Number"))]
numbers.sort()
primes = []
for num in range(numbers[0], numbers[1] + 1):
#Set Start number to divide
i = 2
while i < num:
#Checks if the currNum can be divisble by i and is a whole number
if num % i == 0:
break
i += 1
else:
primes.append(num)
print(primes)
This is my code. I am trying to find the prime numbers before or equal to the integer inputted. However, it seems that the loop stops when it sees an integer in the range that fits the requirements. Unfortunately, this is not I wanted it to do. I would like to make it run through all the tests in the range before making the judgement. Is this possible? If so, how do I do this? Thank you.
def getNumber(main):
n = int(input())
return n
def isPrime(n):
list=[2]
if n > 1:
for i in range(2, n+1):
for a in range (2, n):
if i*a != i and i%a != 0 and i%2 != 0:
list.append(i)
break
return "\n".join(map(str, list))`
def main():
n = getNumber(main)
print(isPrime(n))
main()
You've got your logic a bit wrong. Here's what your code is doing:
Examine numbers in increasing order from 2 to the inputted n.
For each number i, check if any number a between 2 and n divides i
If a divides i, add i to the list, and then move to the next i
This isn't going to get you a prime number. In fact, I'm having trouble figuring out what it will give you, but a prime number probably isn't it. Look at this function instead, which will return all the prime numbers less than or equal to the given number - you can compare it to your code to figure out where you went wrong:
def getPrimesLessThanOrEqualTo(n):
if n <= 1: # Anything 1 or less has no primes less than it.
return "" # So, return nothing.
list = [2] # 2 is the lowest prime number <= n
for i in range(3, n+1): # We start at 3 because there's no need to re-check 2
for a in list: # Instead of iterating through everything less than
# i, we can just see if i is divisible by any of
# the primes we've already found
if i % a == 0: # If one of the primes we've found divides i evenly...
break # then go ahead and try the next i
list.append(i) # Now, if we got through that last bit without
# hitting the break statement, we add i to our list
return "\n".join(list) # Finally, return our list of primes <= i
If you wanted to be more efficient, you could even use range(3, n+1, 2) to count by twos - thus avoiding looking at even numbers at all.
You can use a if/else block if your break is never executed by any item in the iterable the else statement will triggered. https://docs.python.org/3/tutorial/controlflow.html 4.4 demonstrates this accomplishing this almost exact task.
n = int(input('Enter number: '))
if n <= 1:
print('No primes')
else:
primes = []
for i in range(2, n +1):
for k in range(2, i):
if not i % k:
break
else:
primes.append(i)
print(*primes)
# Enter number: 50
# 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
I am planning to create a program which basically lists the Fibbonacci sequnce up to 10,000
My problem is that in a sample script that I wrote I keep getting the error 'int' object is not iterable
My aim is that you enter a number to start the function's loop.
If anyone would help out that would be great
P.S I am a coding noob so if you do answer please do so as if you are talking to a five year old.
Here is my code:
def exp(numbers):
total = 0
for n in numbers:
if n < 10000:
total = total + 1
return total
x = int(input("Enter a number: "), 10)
exp(x)
print(exp)
numbers is an int. When you enter the number 10, for example, the following happens in exp():
for n in 10:
...
for loops through each element in a sequence, but 10 is not a sequence.
range generates a sequence of numbers, so you should use range(numbers) in the for loop, like the following:
for n in range(numbers):
...
This will iterate over the numbers from 0 to number.
As already mentioned in comments, you need to define a range -- at least this is the way Python do this:
def exp(numbers):
total = 0
for n in range(0, numbers):
if n < 10000:
total = total + 1
return total
You can adjust behavior of range a little e.g. interval is using. But this is another topic.
Your code is correct you just need to change :
for n in numbers:
should be
for n in range(0, numbers)
Since you can iterate over a sequence not an int value.
Good going, Only some small corrections and you will be good to go.
def exp(numbers):
total = 0
for n in xrange(numbers):
if n < 10000:
total += 1
return total
x = int(input("Enter a number: "))
print exp(x)
I am new to Python and would like a simple code to be executed however due to my understanding of the syntax I am not able to create it.
I would need to create a range between 1 to 10 and create an input function to search if this number is within this range. My code looks like this:
range=[1,10]
i=0
for i in len(range):
if (i) > 1 and (i) < c:
print ("HH")
However there is an error. Any solutions with explanations?
range is a function so you can either use
if i in range(1,10):
or
if i >= 1 and i < 10:
In your code, you made a variable that happened to be named range but it was actually just a list with two int elements in it.
The following might help you understand a bit better. First of all avoid calling your variable range as this is a Python function. It is used to return a list of numbers. It can take two parameters, a starting number, and an ending number. The ending number is not included in the list, so for 1 to 10 you need range(1,11).
c = int(input("Enter search number: "))
for i in range(1, 11):
if 1 < i < c:
print(i, "HH")
else:
print(i)
This would display:
1
2 HH
3 HH
4 HH
5
6
7
8
9
10
I am not sure which version of Python you are using. If it is earlier than Python 3, then remove the brackets from the print statements.
If you just want to see if the entered number is in a certain range, something like the following would be suitable:
c = int(input("Enter search number: "))
if 1 <= c <= 10:
print("The number {} is in the range 1 to 10".format(c))
else:
print("The number {} is not in range".format(c))
You would then see it display:
Enter search number: 5
The number 5 is in the range 1 to 10
I'm trying to print the factors of the number 20 in python so it goes:
20
10
5
4
2
1
I realize this is a pretty straightforward question, but I just had a question about some specifics in my attempt. If I say:
def factors(n):
i = n
while i < 0:
if n % i == 0:
print(i)
i-= 1
When I do this it only prints out 20. I figure there's something wrong when I assign i=n and then decremented i, is it also affecting n? How does that work?
Also I realize this could probably be done with a for loop but when I use a for loop I can only figure out how to print the factors backwards so that I get: 1, 2, 5, 10....
Also I need to do this using just iteration. Help?
Note: This isn't a homework question I'm trying to relearn python on my own since it's been a while so I feel pretty silly being stuck on this question :(
while i < 0:
This will be false right from the start, since i starts off positive, presumably. You want:
while i > 0:
In words, you want to "start i off at n, and decrement it while it is still greater than 0, testing for factors at each step".
>>> def factors(n):
... i = n
... while i > 0: # <--
... if n % i == 0:
... print(i)
... i-= 1
...
>>> factors(20)
20
10
5
4
2
1
The while condition should be i > 0 and not i < 0 because it will never satisfy it as i begins in 20 (or more in other cases)
Hope my answer helps!
#The "while True" program allows Python to reject any string or characters
while True:
try:
num = int(input("Enter a number and I'll test it for a prime value: "))
except ValueError:
print("Sorry, I didn't get that.")
continue
else:
break
#The factor of any number contains 1 so 1 is in the list by default.
fact = [1]
#since y is 0 and the next possible factor is 2, x will start from 2.
#num % x allows Python to see if the number is divisible by x
for y in range(num):
x = y + 2
if num % x is 0:
fact.append(x)
#Lastly you can choose to print the list
print("The factors of %s are %s" % (num, fact))