Writing a pseudocode algorithm for GCSE - python

My text book asks me to "write pseudo code algorithm which inputs 10 numbers. Each time a number less than zero is input, program displays which number it is, and its value. When all numbers have been input, display the average of all the negative numbers. Your algorithm should allow for the fact that there may be no negative numbers".
The issue I have is that I'm unsure on how to write pseudo code correctly, so I've written it in python code-however, that is not necessarily the task. Furthermore, I've been able to more or less to everything but the issue where I need display the average of all the negative numbers has gotten me stuck... I'm not sure how to add that into my code and I am desperate! Need this for school tomorrow!
count = 0
nums = []
while count != 10:
num = int(input ("enter a number "))
nums.append(num)
if num < 0:
print (num)
neg_nums.append(num)
count = count+1
print (neg_nums)
I actually need to print the average of all the negative numbers, however I have no clue on how I can actually code that into this...

You almost had it. Just store only the negative numbers to the list and then in the end sum all of them up and divide by the amount of negative numbers. I also changed the loop from while loop to for loop, because it makes the code clearer and more compact:
neg_nums = []
for _ in range(10):
num = int(input("enter a number "))
if num < 0:
print(num)
neg_nums.append(num)
if neg_nums:
print(sum(neg_nums) / len(neg_nums))
else:
print("no negative numbers")
We also check in the end if there were some negative numbers inputted, so we don't end up calculating 0 / 0.

Related

I have a problem which is asking me to print the first N prime numbers based on user input, while loop not working as expected

When I run this through Python Tutor and my IDE it seems to run infinitely however I can't seem to get the while loop portion of my program to run properly.
first_n = int(input("How many prime numbers do you want to see, enter now: "))
count = 0 #counter variable
while count != first_n: #conditional statement, while count is not equal to the value of user input
for number in range(2,(first_n)**100): #made the range large enough so that I can retrieve n primes
if number > 1:
for i in range(2,number):
if number % i ==0:
break
else:
print(number)
count+=1 #count is increasing by 1 with each prime number printed
I tried placing the count+=1 portion of my code in different blocks as I believe this is where things are going wrong, however I can't seem to understand where/why things aren't going as expected.
For example: If I enter the value of 5, it should print the first 5 prime numbers (2,3, 5, 7, 11, 13).
However the result is that it runs an infinite loop instead.

Smallest/largest numbers program, input must stop once negative number is inserted

The purpose of this program is to find the smallest and largest values in a list. The moment the user inputs a negative number, the program should stop. Here is the code I have written so far:
user_inputs = []
number = int(input())
for i in range(number):
value = int(input())
if i >= 0:
user_inputs.append(value)
else:
break
print(min(user_inputs))
print(max(user_inputs))
As you can see, I am new to programming and still struggling to find the logic behind loops. Surely, this code is ridden with mistakes and any helpful improvements is much appreciated. Thanks in advance.
Brother one mistake that you have done is that you are using
for i in range(number):
basically by doing this you are telling compiler that repeat the code in for loop for "number" of times and obviously number would change every time user inputs a new number resulting in error
The right way to make the code do what you want is :
user_inputs = []
while True:
number = int(input('Enter a positive number : '))
if number >= 0 :
user_inputs.append(number)
else:
print(user_inputs)
print('Smallest number in list is : ',min(user_inputs))
print('Largest number in list is : ',max(user_inputs))
break
Here while loop will run continuously until a negative number has been input, so when a negative number is input the while loop woulb break .
You are checking
i
when you should be checking
value
you have to compare value
i.e. if value >= 0
you are using i which is the number of iteration

For Loops in Python (Output Smallest Input)

Okay so I am practicing for loops in Python and I was wondering how could I make a user input 10 intergers then it would output the smallest one. I would know how to do this with a while loop for example:
Smallest = 0
count = 0
while count < 10:
Number = int(input("Enter a number >> "))
if Number < Smallest:
Smallest = Number
count = count + 1
print("{0} is the biggest value you have entered".format(Smallest))
But how do I do it in a for loop format? Here's what I have so far:
for i in range(10):
Number = int(input("Enter a Number >> "))
if Number < Smallest:
Smallest = Number
print("{0} is the smallest value you have entered.".format(Smallest))
Initialize your Smallest variable and all will works!
Smallest = int(input("Enter a Number >> "))
for i in range(9):
Number = int(input("Enter a Number >> "))
if Number < Smallest:
Smallest = Number
print("{0} is the smallest value you have entered.".format(Smallest))
What you have there, other than the fact you should initialise Smallest, is equivalent to the solution using your while statement.
So, assuming the while variant is considered correct, the for variant you have will suffice.
The reason I qualify it is because initialising Smallest to zero is actually the wrong thing to do. If your ten numbers are all greater than twenty (for example), Smallest will remain at zero, giving you the wrong answer.
One way to fix this (in both variants) is to change your if statement to:
if i == 0 or Number < Smallest:
which will set Smallest first time through the loop regardless (though it should be count in the while variant since that's using a different loop control variable).
Of course, as you learn more and more about the language, you'll come across the concept of things that are more "Pythonic" than others. An example of this is the rather more succinct:
Smallest = min(int(input("Enter a Number >> ")) for i in range(10))
which removes the need totally for an explicit check-and-replace strategy (that's still done, but under the covers of the min function).
If you want to get the smallest of the input numbers, you need to start with a minimum a bit bigger than 0... and that is a problem you have with your while loop. It will only work if the user inputs at least one negative number, else it will return 0.
Here is what I suggest:
smallest = float("inf")
for i in range(10):
number = int(input("Enter a Number >> "))
if number < smallest:
smallest = number
print("{0} is the smallest value you have entered.".format(smallest))
Note that I did not capitalize the variables, because to me it makes them look like classes. ^^
Since you are finding the Smallest values out of the input values from the user it is good practice to initially initialize the Smallest variable as maximum possible integer as below.
import sys
Smallest = sys.maxint
Then the rest of your loop will work as properly as it is.

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.

Finding numbers that are multiples of and divisors of 2 user inputted numbers

I have an assignment for Python to take 2 user inputted numbers (making sure the 1st number is smaller than the second) and to find numbers that are multiples of the first, and divisors of the second.. I'm only allowed to use a while loop (new condition my teacher added today..) I've done it with a for loop:
N_small = int(input("Enter the first number: "))
N_big = int(input("Enter the second number: "))
numbers = ""
if N_small > N_big:
print("The first number should be smaller. Their value will be swapped.")
N_small, N_big = N_big, N_small
for x in range(N_small, N_big+1, N_small):
if N_big % x == 0:
numbers += str(x) + " "
print("The numbers are: ", numbers)
I'm not asking for the answer to how to do this with a while loop - but I just need a hint or two to figure out how to start doing this... Can anyone enlighten me?
Thanks
You can convert any for loop into a while loop trivially. Here's what a for loop means:
for element in iterable:
stuff(element)
iterator = iter(iterable)
while True:
try:
element = next(iterator)
except StopIteration:
break
stuff(element)
Of course that's not what your teacher is asking for here, but think about how it works. It's iterating all of the values in range(N_small, N_big+1, N_small). You need some way to get those values—ideally without iterating them, just with basic math.
So, what are those values? They're N_small, then N_small+N_small, then N_small+N_small+N_small, and so on, up until you reach or exceed N_big+1. So, how could you generate those numbers without an iterable?
Start with this:
element = N_small
while element ???: # until you reach or exceed N_big+1
stuff(element)
element ??? # how do you increase element each time?
Just fill in the ??? parts. Then look out for where you could have an off-by-one error that makes you do one loop too many, or one too few, and how you'd write tests for that. Then write those tests. And then, assuming you passed the tests (possibly after fixing a mistake), you're done.
You don't have to iterate over all the numbers, only the multiples...
small, big = 4, 400
times = 1
while times < big / small:
num = times * small
if big % num == 0: print(num)
times += 1

Categories