While loop problem.The result isn't what I expected - python

I am new to Python and Stackoverflow in general, so sorry if my formatting sucks and I'm not good at English. But I have a problem with this code.
n = int(input("Fibonacci sequence (2-10): "))
a = 0
b = 1
sum = 0
count = 1
f = True
print("Fibonacci sequence up to {}: ".format(n), end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a = b
b = sum
sum = a + b
This is the result of the code
Fibonacci sequence (2-10): 2
Fibonacci sequence up to 2: 0 1
And this is the result that I expect.
Fibonacci sequence (2-10): 1
Invalid Number!
Fibonacci sequence (2-10): 15
Invalid Number!
Fibonacci sequence (2-10): 10
Fibonacci sequence up to 10: 0 1 1 2 3 5 8 13 21 34

Looks like you just need to add an additional validation step to make sure that the input is in the desired range. This should do it.
while True:
n = int(input("Fibonacci sequence (2-10): "))
if n<2 or n>10:
print("Invalid Number!")
else:
a = 0
b = 1
sum = 0
count = 1
f = True
print("Fibonacci sequence up to {}: ".format(n), end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a = b
b = sum
sum = a + b
break
Edit: To #Barmar's point, a loop on the outside would help avoid rerunning the code in case the input isn't within the desired range.

Related

How to print 100 values which are divisible by 3 and 5?

lower = int(input("Enter lower range limit:"))
upper = int(input("Enter upper b range limit:"))
Count = 0
for i in range(lower, upper+1):
if((i%3==0) & (i%5==0)):
Count += 1
print(count)
I want to print 100 values which are divisible by 3 and 5, but in count only 7 is showing, can anyone suggest what to do, it will be appreciated!
Use this
num = int(input("How many Numbers you want :"))
i=0
Count = 0
while(Count != num):
if((i%3==0) and (i%5==0)):
Count += 1
print(i)
i = i + 1
print("Count is :",Count)
Python program to print all the numbers
divisible by 3 and 5 for a given number
Result function with N
def result(N):
# iterate from 0 to N
for num in range(N):
# Short-circuit operator is used
if num % 3 == 0 and num % 5 == 0:
print(str(num) + " ", end = "")
else:
pass
Driver code
if name == "main":
# input goes here
N = 100
# Calling function
result(N)

Write a Python program that reads a positive integer n and finds the average of all odd numbers between 1 and n

This is the question:
Write a Python program that reads a positive integer n and finds the
average of all odd numbers between 1 and n. Your program should not
accept a negative value for n.
And here is my code, which curiously doesn't work:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
while b <= k:
if b % 2 == 1:
sum1 = sum1+b
b += 1
avg = sum/k
print(avg)
Example: input: 8 and output: 2.5, while it should be 4. Any tips?
if we use while True, the program will run until it receives a positive number. and when we get a positive number, then we execute the instructions and turn off the loop using a break
1 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = [i for i in range(1, n + 1) if i % 2 == 1]
print(sum(numbers) / len(numbers))
break
2 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = []
for i in range(1, n+1):
if i % 2 == 1:
numbers.append(i)
break
print(sum(numbers)/len(numbers))
3 version with counter
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
summ = 0
c = 0
for i in range(1, n+1):
if i % 2 == 1:
summ += i
c += 1
print(summ/c)
break
You have used sum (builtin function name) instead of sum1 (your variable name) in the 2nd last line. Additionally, you need to count the total number of odd numbers and divide using that number instead of the input.
Okay I reviewed the question and here is the answer:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
c = 0
while b <= k:
if b % 2 == 1: #determines if odd
sum1 = sum1+b
c += 1 #variable which counts the odd elements
b += 1 #counter
avg = sum1/c
print(avg)
sum = int(input("Enter a positive integer: "))
Oddtotal = 0
for number in range(1, sum+1):
if(number % 2 != 0):
print("{0}".format(number))
Oddtotal = Oddtotal + number

Python: Why does while loop exclude the first value?

I am trying to make a decimal to binary converter, however, I noticed that some values are being ignored and the last value is not being entered into the list I created.
#Here we create a new empty list.
binary = []
n = int(input("Enter number: "))
while n > 1:
n = n//2
m = n%2
binary.append(m)
binary.reverse()
print( " ".join( repr(e) for e in binary ))
This is your code after correction :
binary = []
n = int(input("Enter number: "))
while n > 0:
m = n%2
n = n//2
binary.append(m)
if len(binary)==0:
binary.append(0)
binary.reverse()
print( " ".join( repr(e) for e in binary ))
Your question is duplicate to this stackoverflow question check the link too.
good luck :)
As PM 2Ring suggested a tuple assignment may be the way to go. Makes your code shorter too :-) ... also changed n > 1 to n >= 1
binary = []
n = int(input("Enter number: "))
while n >= 1:
n, m = n // 2, n % 2
binary.append(m)
binary.reverse()
print( " ".join( repr(e) for e in binary ))
n = int(input("Enter number: "))
print("{0:0b}".format(n)) # one-line alternate solution
if n == 0: # original code with bugs fixed
binary = [0]
else:
binary = []
while n > 0:
m = n%2
n = n//2
binary.append(m)
binary.reverse()
print("".join( repr(e) for e in binary ))
Your algorithm is close, but you need to save the remainder before you perform the division. And you also need to change the while condition, and to do special handling if the input value of n is zero.
I've fixed your code & put it in a loop to make it easier to test.
for n in range(16):
old_n = n
#Here we create a new empty list.
binary = []
while n:
m = n % 2
n = n // 2
binary.append(m)
# If the binary list is empty, the original n must have been zero
if not binary:
binary.append(0)
binary.reverse()
print(old_n, " ".join(repr(e) for e in binary))
output
0 0
1 1
2 1 0
3 1 1
4 1 0 0
5 1 0 1
6 1 1 0
7 1 1 1
8 1 0 0 0
9 1 0 0 1
10 1 0 1 0
11 1 0 1 1
12 1 1 0 0
13 1 1 0 1
14 1 1 1 0
15 1 1 1 1
As Blckknght mentions in the comments, there's a standard function that can give you the quotient and remainder in one step
n, m = divmod(n, 2)
It can be convenient, but it doesn't really provide much benefit apart from making the code a little more readable. Another option is to use a tuple assignment to perform the operations in parallel:
n, m = n // 2, n % 2
It's a good practice, especially when you're new to coding, to work through your algorithm on paper to get a feel for what it's doing. And if your code doesn't give the expected output it's a good idea to add a few print calls in strategic places to check that the values of your variables are what you expect them to be. Or learn to use a proper debugger. ;)

Collatz sequence

How can I take an integer as input, of which the output will be the Collatz sequence following that number. This sequence is computed by the following rules:
if n is even, the next number is n/2
if n is odd, the next number is 3n + 1.
e.g. when starting with 11
11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
This is my code now:
n = int(raw_input('insert a random number'))
while n > 1:
if n%2 == 0:
n_add = [n/2]
collatz = [] + n_add
else:
n_add2 = [3*n + 1]
collatz = [] + n_add2
print collatz
if I execute this and insert a number, nothing happens.
You are never changing the number n, so it will be the same each time round. You are also only printing if the number is odd. Also, square brackets [] indicate an array - I'm not sure what your goal is with this. I would probably rewrite it like this:
n = int(raw_input('insert a random number'))
while n > 1:
if n%2 == 0:
n = n/2
else:
n = 3*n + 1
print n
You might want to take some time to compare and contrast what I'm doing with your instructions - it is almost literally a word-for-word translation (except for the print
It is a little unclear from your code if you want to just print them out as they come out, or if you want to collect them all, and print them out at the end.
You should be modifying n each time, this will do what you want:
n = int(raw_input('insert a random number'))
while n > 1:
n = n / 2 if not n & 1 else 3 * n + 1 # if last bit is not set to 1(number is odd)
print n
## -- End pasted text --
insert a random number11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
Using your own code to just print out each n:
n = int(raw_input('insert a random number'))
while n > 1:
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
print n
Or keep all in a list and print at the end:
all_seq = []
while n > 1:
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
all_seq.append(n)
print(all_seq)
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
elif number % 2 == 1:
number = number * 3 + 1
print(number)
try:
num = int(input('Please pick any whole number to see the Collatz Sequence in action.\n'))
collatz(num)
except ValueError:
print('Please use whole numbers only.')
I've also been working on it for a while now, and here's what I came up with:
def collatz (number):
while number != 1:
if number == 0:
break
elif number == 2:
break
elif number % 2 == 0:
number = number // 2
print (number)
elif number % 2 == 1:
number = 3 * number + 1
print (number)
if number == 0:
print ("This isn't a positive integer. It doesn't count")
elif number == 2:
print ("1")
print ("Done!")
elif number == 1:
print ("1")
print ("Done!")
try:
number = int(input("Please enter your number here and watch me do my magic: "))
except (ValueError, TypeError):
print ("Please enter positive integers only")
try:
collatz(number)
except (NameError):
print ("Can't perform operation without a valid input.")
Here is my Program:
def collatz(number):
if number % 2 == 0:
print(number//2)
return number // 2
elif number % 2 == 1:
print(3*number+1)
return 3*number+1
else:
print("Invalid number")
number = input("Please enter number: ")
while number != 1:
number = collatz(int(number))`
And the output of this program:
Please enter number: 12
6
3
10
5
16
8
4
2
1

working with negative numbers in python

I am a student in a concepts of programming class. The lab is run by a TA and today in lab he gave us a real simple little program to build. It was one where it would multiply by addition. Anyway, he had us use absolute to avoid breaking the prog with negatives. I whipped it up real quick and then argued with him for 10 minutes that it was bad math. It was, 4 * -5 does not equal 20, it equals -20. He said that he really dosen't care about that and that it would be too hard to make the prog handle the negatives anyway. So my question is how do I go about this.
here is the prog I turned in:
#get user input of numbers as variables
numa, numb = input("please give 2 numbers to multiply seperated with a comma:")
#standing variables
total = 0
count = 0
#output the total
while (count< abs(numb)):
total = total + numa
count = count + 1
#testing statements
if (numa, numb <= 0):
print abs(total)
else:
print total
I want to do it without absolutes, but every time I input negative numbers I get a big fat goosegg. I know there is some simple way to do it, I just can't find it.
Perhaps you would accomplish this with something to the effect of
text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
a = int(split_text[0])
b = int(split_text[1])
# The last three lines could be written: a, b = map(int, text.split(','))
# but you may find the code I used a bit easier to understand for now.
if b > 0:
num_times = b
else:
num_times = -b
total = 0
# While loops with counters basically should not be used, so I replaced the loop
# with a for loop. Using a while loop at all is rare.
for i in xrange(num_times):
total += a
# We do this a times, giving us total == a * abs(b)
if b < 0:
# If b is negative, adjust the total to reflect this.
total = -total
print total
or maybe
a * b
Too hard? Your TA is... well, the phrase would probably get me banned. Anyways, check to see if numb is negative. If it is then multiply numa by -1 and do numb = abs(numb). Then do the loop.
The abs() in the while condition is needed, since, well, it controls the number of iterations (how would you define a negative number of iterations?). You can correct it by inverting the sign of the result if numb is negative.
So this is the modified version of your code. Note I replaced the while loop with a cleaner for loop.
#get user input of numbers as variables
numa, numb = input("please give 2 numbers to multiply seperated with a comma:")
#standing variables
total = 0
#output the total
for count in range(abs(numb)):
total += numa
if numb < 0:
total = -total
print total
Try this on your TA:
# Simulate multiplying two N-bit two's-complement numbers
# into a 2N-bit accumulator
# Use shift-add so that it's O(base_2_log(N)) not O(N)
for numa, numb in ((3, 5), (-3, 5), (3, -5), (-3, -5), (-127, -127)):
print numa, numb,
accum = 0
negate = False
if numa < 0:
negate = True
numa = -numa
while numa:
if numa & 1:
accum += numb
numa >>= 1
numb <<= 1
if negate:
accum = -accum
print accum
output:
3 5 15
-3 5 -15
3 -5 -15
-3 -5 15
-127 -127 16129
How about something like that? (Uses no abs() nor mulitiplication)
Notes:
the abs() function is only used for the optimization trick. This snippet can either be removed or recoded.
the logic is less efficient since we're testing the sign of a and b with each iteration (price to pay to avoid both abs() and multiplication operator)
def multiply_by_addition(a, b):
""" School exercise: multiplies integers a and b, by successive additions.
"""
if abs(a) > abs(b):
a, b = b, a # optimize by reducing number of iterations
total = 0
while a != 0:
if a > 0:
a -= 1
total += b
else:
a += 1
total -= b
return total
multiply_by_addition(2,3)
6
multiply_by_addition(4,3)
12
multiply_by_addition(-4,3)
-12
multiply_by_addition(4,-3)
-12
multiply_by_addition(-4,-3)
12
Thanks everyone, you all helped me learn a lot. This is what I came up with using some of your suggestions
#this is apparently a better way of getting multiple inputs at the same time than the
#way I was doing it
text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
numa = int(split_text[0])
numb = int(split_text[1])
#standing variables
total = 0
if numb > 0:
repeat = numb
else:
repeat = -numb
#for loops work better than while loops and are cheaper
#output the total
for count in range(repeat):
total += numa
#check to make sure the output is accurate
if numb < 0:
total = -total
print total
Thanks for all the help everyone.
Try doing this:
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
ans = num1*num2
if num1 > 0 or num2 > 0:
print(ans)
elif num1 > 0 and num2 < 0 or num1 < 0 and num1 > 0:
print("-"+ans)
elif num1 < 0 and num2 < 0:
print("Your product is "+ans)
else:
print("Invalid entry")
import time
print ('Two Digit Multiplication Calculator')
print ('===================================')
print ()
print ('Give me two numbers.')
x = int ( input (':'))
y = int ( input (':'))
z = 0
print ()
while x > 0:
print (':',z)
x = x - 1
z = y + z
time.sleep (.2)
if x == 0:
print ('Final answer: ',z)
while x < 0:
print (':',-(z))
x = x + 1
z = y + z
time.sleep (.2)
if x == 0:
print ('Final answer: ',-(z))
print ()

Categories

Resources