Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So, the part of this project I cannot get to work is the sum() function.
It works during:
a = [1, 2, 3, 4, 5]
b = sum(a)
print b
But in my program, I have a user created list and the sum() keeps getting an error. len() works, but I also need the sum to obtain an average.
namelist = []
agelist = []
while True:
name = raw_input("Enter a name or type Exit to end data entry: ")
namelist.append(name)
if name == "Exit": #creates an exit point from data entry
break
age = raw_input("How old is " + name + "? ")
agelist.append(age)
lenage = len(agelist)
sumage = sum(agelist) #here is the problem -<<
avgage = sumage / lenage
print avgage
How can I get the sumage to work?
Is it not working because I did not define how long the list is?
The variable age has type string, so you need to convert it to an integer:
agelist.append(int(age))
The reason for the error is that agelist is a list of strings (inputs from the user) and before you can "add" those inputs you need to convert them either to an integer number or (probably) to a floating number (depending on what kind of average you want: an integer or floating point in Python 2):
sumage = sum(map(int, agelist)) # OR, replace int with float
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Q. Write a function called shift_string that takes a string and an integer n as parameters and returns a new string with every letter of the string shifted by the n alphabets. It should also work for negative alphabets in reverse order.
So far, I have come up with this:
usr_input=input('Please enter string: ')
n=input('enter shifts: ')
encryption= ""
def shift_string(usr_input,n):
for i in usr_input:
if i.isupper():
i_unicode=ord(i) #find position
i_index=i_unicode-ord('A')
new_index= (i_index + n)
new_unicode= new_index +ord('A') #to perform shift
new_character=chr(new_unicode)
encryption= encryption+new_character #to append string
else:
encryption=encryption+i #for non-uppercase
print('Encrypted text is',encryption)
At encryption= encryption+new_character I am getting the error:
"Local variable 'encryption' defined in enclosing scope on line 23 referenced before assignment...(pyflakes E)"
n=input(eval('enter shifts: '))
The argument to eval() has to be a string containing a Python expression. enter shifts is not a valid expression, you can't evaluate it. I suspect you meant eval(input('enter shifts: ')).
But you shouldn't use eval() to process user input. If you want to convert the input to a number, use int() or float().
n = int(input('enter shifts: '))
The second error is because encryption is a local variable in the function, and you're trying to add to it before you've initialized it. You need to move encryption = "" inside the function. Then you can return the value.
def shift_string(usr_input,n):
encryption = ""
for i in usr_input:
if i.isupper():
i_unicode=ord(i) #find position
i_index=i_unicode-ord('A')
new_index= (i_index + n)
new_unicode= new_index +ord('A') #to perform shift
new_character=chr(new_unicode)
encryption= encryption+new_character #to append string
else:
encryption=encryption+i #for non-uppercase
return encryption
encrypted = shift_string(usr_input, n)
print('Encrypted text is',encrypted)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I can't find a way to sum the ASCII numerical values, I keep getting errors.
This is my code:
str = input("Enter your name: ")
for c in str:
print("The ASCII value for ", c, "is", ord(c))
I deleted the part that was summing it because it was wrong.
You can try with the following using built-in sum and list comprehensions. As a good practice, remember not to define variables with built-in types or functions names (str).
name = input("Enter your name: ")
for c in name:
print("The ASCII value for ", c, "is", ord(c))
print("The total sum is: ",sum([ord(c) for c in name]))
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
A number that equals to the sum of its own digits, where each digit raised to the power of number of digits. For example, 153 is an armstrong number
because 1^3+3^3+5^3=153
at here user enters a number
number=int(input("please enter a number: "))
Here in a while loop it puts the digits of the given number in numbers class
numbers=[]
while number>0:
rem=number%10
numbers.append(rem)
number=int(number/10)
and then we want to put their qubes in qubes class
qubes=[]
for i in range(0,len(numbers)):
c=(int(numbers[i]))**len(numbers)
qubes.append(c)
and now we calculate the sum of the qubes class members
result = sum(i for i in qubes)
I dont know why the if_code below doesnt work it just gives me false output I dont know why??
even when i enter 153 it prints false
if result==number:
print("true")
else:print("false")
To sum-up all suggestions from the comments:
Your main problem is:
When you create the numbers list you use number = int(number/10). This changes the number variable itself until it is equal to zero. This means that, as you experienced, result == number will always be False.
Some redundant parts of your code:
See Splitting integer in Python? to get a list of a number's digits. Most commonly you can just do numbers = [int(i) for i in str(number)]. This will actually solve the problem above as you don't change number this way.
The digits are already integers so no need for an int conversion. It is also more readable to use direct loop in Python rather than looping over indices:
qubes = []
for num in numbers:
qubes.append(num**len(numbers))
sum(i for i in qubes) is just an overly explicit way of saying sum(qubes).
You are printing either "true" or "false" according to a boolean result. There is no need for a condition and you can simply print(result == number).
Putting together all the above, you can achieve this with a single line of code:
print(number == sum(int(digit)**len(str(number)) for digit in str(number)))
This is where you are wrong. you should iterate over the integer not the iterator given by range function
Use this
qubes=[]
for i in numbers:
c=(int(i)**len(numbers))
qubes.append(c)
instead of
qubes=[]
for i in range(0,len(numbers)):
c=(int(numbers[i]))**len(numbers)
qubes.append(c)
Also you are referencing the number to itself number=(int(number/10)) so your result value will be 153 but number value will be 0 at the end because you have reduced the value of number. So copy the value of number to another variable (num1 in below code).
Full code:
number=int(input("please enter a number: "))
num1 = number
numbers=[]
while number>0:
rem=number%10
numbers.append(rem)
number=int(number/10)
qubes=[]
for i in numbers:
c=(int(i)**len(numbers))
qubes.append(c)
result = sum(i for i in qubes)
print(result == int(num1))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm writing a function to return the mean of the user's comma-separated input.
def get_average () :
grades = input()
grades = grades.split(",")
grades = [int(x) for x in grades]
average = (sum(grades))/(len(grades))
return round(average, 2)
Is this a good way to do so? What about the fact that I redefined the grades variable twice? Is there a more practical way to do it?
Reusing grades just makes the program harder to read, as grades now means three different, semantically incompatible things. Try using more descriptive names, then combining intermediate steps. For instance:
input_line = input("Please enter the grades, separated by commas")
grades = [int(x) for x in input_line.split(',')]
Other than the superfluous outer parentheses in the mean computation, you're doing fine so far.
You could write it a bit more elegant, but nothing is wrong with redefining grades in these three consecutive lines. It works, and as it is so close together it won't create confusion.
Here would be my go for a more elegant solution using python's statistics module from the standard lib:
import statistics
def get_average():
user_input = input('Please enter integer numbers separated by commas: ')
average = statistics.mean(map(int, user_input.split(',')))
return round(average, 2)
This is fine, to be more pythonic you can chain calls like:
grades = [int(x) for x in grades.split(',')]
without having to use a temporary assignment of .split()
You can do the same with the round() call:
return round(sum(grades) / len(grades), 2)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
alphabet = 'abcdefghijklmnopqrstuvwxyz'
message = input('Please insert the message you want to encrypt')
key = input('whay key value do you want in your encyption?')
for m in message:
if m in alphabet:
key += alphabet [(alphabet.index(m)+key)%(len(alphabet))]
Keeping to your original idea, you were fairly close. Note, Python already keeps a handy list of lower case letters:
import string
alphabet = string.ascii_lowercase
message = input('Please insert the message you want to encrypt: ')
key = int(input('What key value do you want in your encryption? '))
output = []
for m in message:
if m in alphabet:
output.append(alphabet[(alphabet.index(m) + key) % (len(alphabet))])
print(''.join(output))
You need to create a new output list of characters as it is not possible to directly change the characters in the original string. This list can then be joined back together to display your output.
So for example, this would give you the following:
Please insert the message you want to encrypt: hello
What key value do you want in your encryption? 3
khoorzruog
Please also note, there are more efficient ways to tackle this, for example the use of maketrans.