I am trying to create a program that takes in four numbers they can be negative or positive and it should sum all the numbers together and then print the sum.
My problem comes with the append line, I am trying to place it inside the list but it keeps coming up with an error and I am unsure why.
Here is the Code:
def sumList(NumList, list):
sum = 0
for num in list:
sum = sum + num
return sum
NumList = []
while (True):
number = int(input("please enter a number: "))
if (number != 0):
number.append(number, NumList) #Here keeps coming up as an error
else:
sumList()
break
print(NumList)
Thank you for having the time to read this.
Honestly, your code is a mess. This works:
numlist = []
number = int(input("please enter a number: "))
while number != 0:
numlist.append(number)
number = int(input("please enter a number: "))
print(sum(numlist))
To sum the values of an iterable, you can simply use the builtin sum function. And to append something to a list, use list.append(value)
It should be NumList.append(number) or NumList.extend(number)
code snippet:
def sumList(NumList, list):
sum = 0
for num in list:
sum = sum + num
return sum
NumList = []
while (True):
number = int(input("please enter a number: "))
if (number != 0):
NumList.append(number) #correct this
else:
sumList()
break
print(NumList)
Related
n=int(input("Enter a Number: "))
x=0
y=0
z=0
while(n>0):
x=n%10
y=x**3
z=z+y
n=n//10
print (z)
#The z here is the same value which I enter, yet it doesn't work.
#If I enter 407 as n, z becomes (4^3)+(0^3)+(7^3) which is 407
if (z==n):
#But even when 407==407, it just wont print the bottom statement
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
#it prints that it isn't an Armstrong number
After the while loop, n already became 4//10 which is 0, so it'll never equal z which is 407.
You will want to keep a copy of the original input for comparison.
As a general advice, use a debugger or at least print() your objects to see where the assignments went wrong.
Without using any built-in method
Armstrong number is 371 because 3**3 + 7**3 + 1**3 = 371. according this rule 123 is not Armstrong number because 1**3 + 2**3 + 3**3 is not equal to 123
def count_digit(n):
count = 0
while n > 0:
count += 1
n //= 10
return count
def is_armstrong(n):
given = n
result = 0
digit = count_digit(n)
while n > 0:
reminder = n % 10
result += reminder ** digit
n //= 10
return given == result
is_armstrong(371)
>> True
is_armstrong(123)
>> False
You can take in your initial number as a string so we can more easily convert it to a list. We can then map to create that list of ints. After we can use list comprehension to raise all int in that list to the power that is the len of our list. If the sum of this list equals our input, then we have an Armstrong number.
n = input('Enter a number: ')
nums = list(map(int, n))
raised = [i**len(nums) for i in nums]
if sum(raised) == int(n):
print('The number is Armstrong')
else:
print('The number is not Armstrong')
Expanded list comprehension:
raised = []
for i in nums:
i = i**len(nums)
raised.append(i)
print(raised)
Alternate for map:
nums = []
for i in n:
i = int(i)
nums.append(int(i))
I corrected your code:
n = int(input("Enter a Number: "))
x = 0
y = 0
z = 0
num = n
while n > 0:
x = n % 10
y = x**len(str(num))
z = z+y
n = n//10
print(z)
if (z == num):
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
But you can still do it in many ways better. Look at the code of vash_the_stampede and ggorlen.
Or:
def isArmstrong(n):
print(f"{n} is {'' if int(n) == sum(int(i)**len(n) for i in n) else 'not '}an Armstrong number")
isArmstrong(input("Please enter a number: "))
Definition: a number n is an Armstrong number if the sum of each digit in n taken to the power of the total digits in n is equal to n.
It's important to keep track of the original number n, because it'll be needed to compare against the result of z (your variable representing the sum). Since you're mutating n in your while loop, there's no grounds for comparison against your original input, so if (z==n): isn't working like you expect. Save n in another variable, say, original, before reducing it to 0.
Additionally, your code has arbitrarily chosen 3 as the number of digits in the number. For your function to work correctly for any number, you'll need a way to count its digits. One way is to convert the number to a string and take the length.
I strongly recommend using descriptive variable names which reduces the chance of confusing yourself and others. It's only apparent that z represents your sum and x your remainder by virtue of reading through the code. If the code was any longer or more complex, it could be a nightmare to make sense of.
Lastly, Python is not a particularly flexible language from a style standpoint. I recommend adhering to the style guide as best as possible to keep your code readable.
Here's a working example:
def armstrong(n):
total = 0
original = n
digits = len(str(n))
while n > 0:
total += (n % 10) ** digits
n //= 10
return total == original
if __name__ == "__main__":
while 1:
print(armstrong(int(input("Enter a Number: "))))
Output:
Enter a Number: 407
True
Enter a Number: 1234
False
Enter a Number: 23
False
Enter a Number: 8
True
Enter a Number: 371
True
Try it!
total=0
def Armstrong(n):
m=list(n)
global total
for i in m:
total+=pow(int(i),len(n))
if total==int(n):
print ("it is Armstrong number")
else:
print("it is not Armstrong number")
Armstrong(input("enter your number"))
print(total)
def math():
x = str('y')
while x == 'y':
a = float(input("Please enter a number: "))
a = (((4*a)+1)/(a-3))
b = float(input("Please enter a number: "))
b = (((4*b)+1)/(b-3))
c = float(input("Please enter a number: "))
c = (((4*c)+1)/(c-3))
d = float(input("Please enter a number: "))
d = (((4*d)+1)/(d-3))
print(a)
print(b)
print(c)
print(d)
x == str(input("Would you like to continue"))
math()
Hello I'm new to programming and I was just casually doing this to make an easy calculator for my homework assignment and I wanted to know instead of replicating the code for each variable if there was a way to do the math one time and just keep reassigning values to the variable for the math. This might be dumb a question and it's not serious or anything I just was curious if there are better way's to do this.
Comments and suggestions:
def math():
x = str('y')
'y' is a string, so there is no need to convert it to a string using str(). x = 'y' is sufficient.
while x == 'y':
a = float(input("Please enter a number: "))
a = (((4*a)+1)/(a-3))
b = float(input("Please enter a number: "))
b = (((4*b)+1)/(b-3))
c = float(input("Please enter a number: "))
c = (((4*c)+1)/(c-3))
d = float(input("Please enter a number: "))
d = (((4*d)+1)/(d-3))
DRY - don't repeat yourself.
Define a function which takes an input and returns the computed results:
def compute(n_times):
results = [] # initialize results, empty list
for repetition in range(n_times): # repeat n times
inp = float(input("Please enter a number: "))
results.append(((4 * inp) + 1) / (inp - 3)) # append result to list
return results # return filled list
and call this function n times:
result_list = compute(4) # compute() returns a list with results
for result in result_list: # iterate through list
print(result)
ask user if they wish to continue:
x == input("Would you like to continue? ")
run your function:
math()
Conclusion:
def compute(n_times):
results = [] # initialize results, empty list
for repetition in range(n_times): # repeat n times
inp = float(input("Please enter a number: "))
results.append(((4 * inp) + 1) / (inp - 3)) # append result to list
return results # return filled list
def math():
how_often = 4
answer = 'y'
while answer == 'y':
result_list = compute(how_often) # compute() returns a list with results
for result in result_list: # iterate through list
print(result)
answer == input("Would you like to continue? (y/n): ")
math()
Get the Value from user and Print the Odd and Even Number using List in Python
would you like to try this code which simplify the flow and make it more Pythonic:
nums = map(int, input("Input some numbers: ").split()) # get all numbers in one shot
results = [[], []] # declare the results to store evens and odds
for n in nums: # put each number in their own list or bucket. one shot.
results[n % 2].append(n)
print(results)
evens, odds = results # unpacking these 2 lists
print(f' evens list: {evens}' ) # confirm the results is ok
print(f' odds list: {odds} ')
I have written the code below to solve this, but please at least make an effort to answer the question before asking.
# Get the Value from user and Print the Odd and Even Number using List in Python
number = int(input("How many numbers do you want? "))
lst=[]
for i in range(0,number):
add = int(input("Enter Number: "))
lst.append(add)
even = []
odd = []
for num in lst:
if num % 2==0:
even += [num]
else:
odd += [num]
print("even: ", even)
print('odd: ', odd)
number = int(input("Enter How Many Number you want!"))
values=[]
for i in range(0,number):
add = int(input("Enter Next Number:"))
values.append(add)
print("Numbers in the list",values)
def oddEven(valuesList):
OddResult = []
EvenResult = []
for i in valuesList:
if i % 2== 0:
EvenResult.append(i)
else:
OddResult.append(i)
return OddResult,EvenResult
OddResult, EvenResult = oddEven(values)
print("Print Even Number ",EvenResult)
print("Print Odd Number",OddResult)
At the yes/no loop, the program won't call the function to re-perform a calculation. Instead, it asks to compute another gcd repeatedly instead of calling the specified function.
I've tried re-inputting the whole function into the question loop if the user inputs yes, but that did not work either.
def gcd(n,m):
if(m==0):
return n
else:
return gcd(m,n%m)
n = int(input("Enter a positive whole number:"))
while True:
if n <= 0:
print ("The number entered is not a positive number!, please try again")
n = int(input("Enter a positive whole number : "))
if n > 0: break
m = int(input("Enter a second positive whole number:"))
while True:
if m <= 0:
print ("The number entered is not a positive number!, please try again")
m = int(input("Enter a positive whole number : "))
if m > 0: break
GCD = gcd(n,m)
print("The GCD of the two numbers you entered is:" ,GCD)
while True:
a = input("Compute another GCD? Enter y/n:").lower()
if a=="y":
gcd(n,m)
elif a=="n":
break
else:
print("Invalid entry. Please enter either y/n:")
print("Goodbye!")
Expected results is that it calls the function gcd(n,m) and re-performs a calculation. Actual results is that it asks to perform another calculation without having actually completed a second calculation.
The function is called. The problem is that you don't do anything with its return value.
You will also need to ask the user for new input. In order to not repeat the same code again you can have a function that does that.
Then the whole code becomes:
def get_2_numbers():
n = int(input("Enter a positive whole number:"))
while True:
if n <= 0:
print ("The number entered is not a positive number!, please try again")
n = int(input("Enter a positive whole number : "))
if n > 0: break
m = int(input("Enter a second positive whole number:"))
while True:
if m <= 0:
print ("The number entered is not a positive number!, please try again")
m = int(input("Enter a positive whole number : "))
if m > 0: break
return n, m
def gcd(n,m):
if(m==0):
return n
else:
return gcd(m,n%m)
a, b = get_2_numbers()
while True:
answer = input("Compute another GCD? Enter y/n:").lower()
if answer == "y":
print(gcd(a, b))
a, b = get_2_numbers()
elif answer == "n":
break
else:
print("Invalid entry. Please enter either y/n:")
print("Goodbye!")
A small downside is that the user will have to answer y even before the first calculation, but I'll leave that as an exercise to the reader.
I am trying to separate the -odd, -even, even, and odds into separate arrays. I have done this in matlab but confused with how this would work in python. All I got so far is how to generate a user inputted array
print('Enter 10 numbers: ')
num=10
l1=[0]*num
for l in range (0,num):
numbers = float(input('Enter value #'+str(l+1)+' : '))
l1[l]=numbers
print('Your numbers are: ',l1 )
Here's a working example that does what you need and starts with your code to populate the "l1" list.
negative_odds = []
negative_evens = []
evens = []
odds = []
for num in l1:
if num % 2 == 0:
if num < 0:
negative_evens.append(num)
else:
evens.append(num)
else:
if num < 0:
negative_odds.append(num)
else:
odds.append(num)
print('-odd: ', negative_odds)
print('-even: ', negative_evens)
print('even: ', evens)
print('odd: ', odds)