Tips for completing this python task - python

I'm very new to coding and python and would like some help with finishing this small assignment I've been given.
The requirements of the project are as follows:
Create a Python application that will loop between 1 and 100
The numbers are to be printed out alongside their squared value
The app should stop when a squared value of 200 or more is reached
Reconfigure the application to take in a user value to produce squared values up to
Currently I can create the first two points, and have some idea with allowing user input into the app. With the below being the coding.
# The program to find the square of all numbers present in the list
# variable to store the squared numbers
square = 1
x = 200
# List of numbers
numbers = range(1,100)
#iterate over the list
for val in numbers:
square = val*val
# prints the output
print ("The square of ", val, "is", square)

Since your question says program stops when a square value of 200 or more is reached, I'll provide my implementation:
#square = 1 You can comment out this line since this is redundant.
#x = 200 Even this line is redundant.
# List of numbers
numbers = range(1,100)
#iterate over the list
for val in numbers:
square = val*val
if square >= 200:
exit() #I prefer exit() statement over break statement, you can decide what would suit better for you
print ("The square of ", val, "is", square)

You need to provide an upper limit for the square. I assume the user input will be the upper limit for the squares. I would code it like this:
n = int(input())
i = 1
while (i*i<n):
print(i, i*i)
i+=1

Related

Python: Loop to check if an input is valid or not line by line

Given the following inputs that simulate a grid with the respective dimensions:
totLines = int(input("Indicate the number os lines: "))
totColunms = int(input("Indicate the number of columns: "))
I want to check whether the input is valid or not (every digit must be between 0 and 20). The code should check each line of the grid and tell the user if the input is valid and if not ask for another input. The problem is that my code only checks the first digit of line1, the second digit of the line2, and so on. For instance, in a 3x3 grid, if I input the following numbers for line1 (separated by spaces) - 21 10 10 - the code is gonna tell me that the input is not valid, but if I put the incorrect digit in position 2 - 10 21 10 - the code is not gonna find any problem. I know the problem must be related to how I´m doing the loop but I can´t understand how to solve this. This is something easy to do but It´s my first time learning a programming language and I still have a lot to learn. Thanks!
for lin in range (1, totLines+1):
print("Line", str(lin))
while True:
sMoves = input("Movement for this line: ")
listMoves = sMoves.split()
listMovesINT = list(map(int, listMoves))
if listMovesINT[lin-1] > 0 and listMovesINT[lin-1] <= 20:
break
else:
print ("Not a valid integer")
continue
I'd suggest putting the logic to get a valid list of moves in its own function, using all() to test all the values in the list (you don't need the current value of lin or anything else in the main loop to figure this out, and putting this task in its own function makes it easier to focus on it without accidentally mixing in other parts of your program):
def get_movement() -> list[int]:
"""Get a list of movement values between 1 and 20."""
while True:
try:
moves = [int(n) for n in input("Movement for this line:").split()]
if not all(1 <= n <= 20 for n in moves):
raise ValueError("all values must be between 1 and 20")
return moves
except ValueError as e:
print("Not a valid integer:", e)
and then in your main loop you can do:
for lin in range (1, totLines+1):
print("Line", lin)
moves = get_movement()
# do whatever thing with moves
As you noticed, you are "binding" the items in your input to your "board" (sort of the "board"... the totLines variable).
But you really just want to verify one input at a time, right? When the user writes the set of movements for any given line, it doesn't really matter whether it's for the first line of the "board" or for the last. Maybe you want the line index to display a nice prompt message, but that's about it. When it comes to ensuring that the input is valid, you really don't need the line for anything, isn't it?
So it all boils down to verifying that the inputs for any given line are valid, and keep pestering the user until they (all) are. Something like:
valid_input = False
while not valid_input:
sMoves = input("Movement for this line: ")
listMoves = sMoves.split()
listMovesINT = list(map(int, listMoves))
valid_input = all((0 < move <= 20) for move in listMovesINT)
if not valid_input:
print("One of the movements is not valid")
If you wanna use the number of total lines (totLines) to show a little bit more human-friendly prompt and then make the code a bit more like what you have it (with a for loop), you can just wrap the while not valid_input like this:
totLines = int(input("Indicate the number os lines: "))
for lineNum in range(1, totLines + 1):
valid_input = False
while not valid_input:
sMoves = input(f"Movement for line {lineNum}: ")
listMoves = sMoves.split()
listMovesINT = list(map(int, listMoves))
valid_input = all((0 < move <= 20) for move in listMovesINT)
if not valid_input:
print("One of the movements is not valid")
First, your code only check one integer per line.
You have an index but it is a line index (lin-1), not a number index.
Was the "while True" supposed to iterate over numbers. If yes, it should be after the "split()".
Here's a working example:
matrix = []
totlines=3
for i in range( totlines):
line = input( "... ")
numbers = [ int( text) for text in line.split()] # convert list of asciiNumbers to list of 3 integers
for number in numbers:
if (number <= 0) or (number>20):
print( "Invalid number in line", i, ":", numbers)
matrix.append( numbers)
print( matrix)

Writing a pseudocode algorithm for GCSE

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.

python:Write a program that keeps reading positive numbers from the user [duplicate]

This question already has answers here:
Storing multiple inputs in one variable
(5 answers)
Closed 2 months ago.
hi i am very new to programming and was doing my 6th assignment when i started to draw a blank i feel as thou its really simple but i cant figure out how to continue and would appreciate some advice
showing the correct code would be cool and all but i would really appreciate feed back along with it more so then what to do and if so where i went wrong
down below is what im supposed to do.
Write a program that keeps reading positive numbers from the user.
The program should only quit when the user enters a negative value. Once the
user enters a negative value the program should print the average of all the
numbers entered.
what im having trouble with is getting the number to remember okay user entered 55 (store 55) user entered 10 (store 10) user enter 5 (store 5) okay user put -2 end program and calculate. problem is its not remembering all previous entry's its only remembering the last input (which i guess is what my codes telling it to do) so how do i code it so that it remembers all previous entry's
and here is the code i have so far
number = 1
while ( number > 0):
number = int(input("enter a number. put in a negative number to end"))
if number > 0 :
print (number)
else:
print (number) # these are just place holders
If you really want to remember all previous entries, you can add them to a list, like so:
# before the loop
myList = []
# in the loop
myList = int(input("enter a number. put in a negative number to end"))
Then you can easily compute the mean of the numbers by iterating over the list and dividing by the length of the list (I'll let you try it yourself since its an assignment).
Or, if you want to save (a little) memory, you can add them each time to a variable and keep another variable for the count.
You can use a simple list in order to keep track of the numbers that have been inserted by the user. This list may then get processed in order to calculate the average when every number got read in ...
# This is a simple list. In this list we store every entry that
# was inserted by the user.
numbers = []
number = 1
while ( number > 0):
number = int(input("enter a number. put in a negative number to end "))
if number > 0 :
print (number)
# save the number for later usage.
numbers.append(number)
# calculate average
if len(numbers) == 0:
print("You have not inputted anything. I need at least one value in order to calculate the average!")
else:
print("The average of your numbers is: %s" % (sum(numbers) / len(numbers)))
What you need is an list which can store multiple values. It is often use with loops to insert/get value from it.
For instance,
number = 1
numbers = []
while ( number > 0):
number = int(input("enter a number. put in a negative number to end"))
if number > 0 :
numbers.append(number)
print (numbers)
What you get is a list of numbers like [4, 10, 17] in ascending order as append() will add number to the back of the list. To get individual numbers out of the list:
numbers[0]
Note that the index inside the bracket starts from 0, so for instance you have a list with [4, 10, 17]. You should use the below 3 to get each of them:
numbers[0]
numbers[1]
numbers[2]
Or even better, with a loop.
for x in numbers:
print (x)

Issues with while loop

So this code is meant to return the final error and the final logarithm of a number inputted by a user. Now my issue is that it doesn't run the loop, it just keeps going over the same number and it never ends. I am not sure if I have my print statements in the wrong area, or if I am doing the loop wrong but I want the loop to end when the error is less then 1x10^-9. It's possible my iterations are set up wrong too, not really sure what I messed up on here.
import math
import sys
#Computing natural log of x
#x value is input here
x = float(input("Please input a positive number: "))
#If x is not positive then program will not work, so it will exit
if x<=0:
print("Your number is not positive. System Shutdown.")
sys.exit()
#Retrieving ln(x) using the math command
lnx0 = math.log(x)
#Formula for approximate ln
xfrac = (x - 1)/(x + 1)
lnx = 0 #Initializing the approximating
i=0
#This is the code to make it go until it hits the error we want
while True:
ex = 2*i - 1
lnx += 2.0* (xfrac**ex / ex)
#Counter adding 1 to it
i+=1
#This is the error
err = math.fabs(lnx0 - lnx)
if err<0.0000000001:
break
#Priting approximate ln at end of loop
print ("ln(x) at " ,x,"is: " ,lnx)
#Final Error
print ("Final error is:" ,err)
#Number of itterations
#Printing accurate version of ln(x) just to see what it should be
print ("Your accurate value of ln(x) is: " ,lnx0)
I'm assuming you're using the fourth formula on this page to approximate the log function. If so, your i is starting at the wrong value; you've initialized it to 0 here, but it needs to start at 1.
Also, if you only want output after the answer has been found, rather than once per iteration, your print functions should be de-indented so they are outside the loop. Try:
import math
import sys
#Computing natural log of x
#x value is input here
x = float(input("Please input a positive number: "))
#If x is not positive then program will not work, so it will exit
if x<=0:
print("Your number is not positive. System Shutdown.")
sys.exit()
#Retrieving ln(x) using the math command
lnx0 = math.log(x)
#Formula for approximate ln
xfrac = (x - 1)/(x + 1)
lnx = 0 #Initializing the approximating
i=1
#This is the code to make it go until it hits the error we want
while True:
ex = 2*i - 1
lnx += 2.0* (xfrac**ex / ex)
#Counter adding 1 to it
i+=1
#This is the error
err = math.fabs(lnx0 - lnx)
if err<0.0000000001:
break
#Priting approximate ln at end of loop
print ("ln(x) at " ,x,"is: " ,lnx)
#Final Error
print ("Final error is:" ,err)
#Number of itterations
#Printing accurate version of ln(x) just to see what it should be
print ("Your accurate value of ln(x) is: " ,lnx0)
Result:
Please input a positive number: 5
ln(x) at 5.0 is: 1.6094379123624052
Final error is: 7.169509430582366e-11
Your accurate value of ln(x) is: 1.6094379124341003
Thanks to DSM for identifying the formula and possible fix
There are several problems with this. The first is that your computations are incorrect. I tried entering 'e' to 9 places. Your estimate, lnx, quickly degenerates to -3.3279+ and sticks there. This dooms you to an infinite loop, because the estimate will never get near the true value.
Others have already pointed out that you haven't traced your computations with print statements. I'll add another hint from my days in numerical analysis: use a restricted "for" loop until you've debugged the computations. Then trade it in for a "while err > tolerance" loop.
To address your most recent comment, you're not getting the same numbers. The first few terms are significant, but the infinite sequence quickly drops close to 0, so the additions don't show up after about 15-20 iterations.
Also print out ex and lnx values within the loop. Especially check the first one, where your exponent is -1; I believe that you've started the loop in the wrong place.
Finally, you might find this loop form a little easier to read. Get rid of your if...break statement and use this instead:
i = 1
err = 1
tolerance = 1e-10
# This is the code to make it go until it hits the error we want
while err >= tolerance:

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