Input to list and operate on it - python

I've just started with Python (3.x), and while it is fairly easy to pick up, I'm trying to learn how to work with lists.
I've written a small program which asks for the amount of numbers to input, then asks for the numbers. Where I'm scratching my head a little is here;
t += numList[int(i)]
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
I'm sure it's obvious to someone else. I thought that lists used an integer index? And that referencing that index would return the contents?
(I have a C++ background, so I'm finding that some things don't work how I thought they would).
Full program here;
runLoop = True
numList = []
def avg():
t = 0
i = 0
while i < len(numList):
t += numList[i]
i += 1
print (" total is " + str(t))
while runLoop == True:
maxLen = int(input("Average Calculator : "
"Enter the amount of number "
"to calculate for"))
while len(numList) < maxLen:
numList.append(input("Enter number : "))
avg()
if input("Would you like to run again? (y/n) ") == "n":
quit()

Type casting:
Type casting is missing in following statement
numList.append(input("Enter number : "))
e.g. Use input() method for python 3.x
>>> a = raw_input("Enter number:")
Enter number:2
>>> type(a)
<type 'str'>
>>> b = int(a)
>>> type(b)
<type 'int'>
>>>
Add Integer type variable with Integer type variable: This will raise exception at t += numList[i] statement because we are adding integer variable with string variable, it is not allowed.
e.g.
>>> 1 + "1"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
No need to check length of list in while loop while i < len(numList):. We can iterate directly on list.
e.g.
>> numList = [1,4,10]
>>> total = 0
>>> for i in numList:
... total += i
...
>>> print total
15
>>>
Inbuilt sum() function: We can use inbuilt function sum() to get from list.
e.g.
>>> numList = [1,4,10]
>>> sum(numList)
15
>>>
Exception handling: It is good programming to handle exception on user input. Use exception handling during type casting. If user enters any non integer number and we are type casting that non integer string into integer that time python interpreter raise ValueError.
e.g.
>>> try:
... a = int(raw_input("Enter Number:"))
... except ValueError:
... print "Wrong number. Enters only digit."
...
Enter Number:e
Wrong number. Enters only digit.

Thanks to Vivik for the answer.
I have now adjusted my simple program and solved the issue I had; code as follows.
runLoop = True
numList = []
def avg(workList):
t = sum(workList)
print ("Average is " + str(t/len(workList)) )
print ("Total is " + str(t) )
while runLoop == True:
maxLen = int(input("Average Calculator : "
"Enter the amount of number "
"to calculate for : "))
while len(numList) < maxLen:
numList.append(int(input("Enter number : ")))
avg(numList)
if input("Would you like to run again? (y/n) ") == "n":
quit()
I can see that I could quite easily shorten it down to;
runLoop = True
numList = []
while runLoop == True:
maxLen = int(input("Average Calculator: Enter the amount of number to calculate for : "))
while len(numList) < maxLen:
numList.append(int(input("Enter number : ")))
print ("Average is " + str(sum(numList)/len(numList)) )
print ("Total is " + str(sum(numList)) )
if input("Would you like to run again? (y/n) ") == "n":
quit()
But, the point of my little !/pointless exercise was to explore the relationships of lists, input to lists, and printing lists.
Cheers!

Related

How do I sum numbers from user input in python?(only if they are even numbers)

I am new to programming, and I'm trying to make a code to get six numbers from a user and sum only even numbers but it keeps error like, "unsupported operand type(s) for %: 'list' and 'int' How can I do with it?
Also, I want to make like this,
Enter a value: 1
Is it even number?:no
Enter a value: 2
Is it even number?:yes
Enter a value: 3
Is it even number?:no
Enter a value: 6
Is it even number?:yes
but it keeps like this,
Enter a value: 1
Enter a value: 2
Enter a value: 3
Enter a value: 4
Enter a value: 5
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
How can I fix this?
anyone who can fix this problem please let me know
Python 3.7
numbers = [int(input('Enter a value: ')) for i in range(6)]
question = [input('Is it even number?: ') for i in range(6)]
list1 = [] #evens
list2 = [] #odds
if numbers % 2 ==0:
list1.append
else:
list2.append
sum = sum(list1)
print(sum)
And I'd appreciate it if you could let me know if you knew the better code
This should do it. Note that there is no real need to ask the user if the number is even, but if you do want to ask, you can just add question = input('Is it even number?: ').lower() in the loop and then do if question=='yes'. Moreover, note that you cannot perform % on a list; it has to be on a single number.
evens = []
odds = []
for i in range(6):
number = int(input('Enter a value: '))
if number%2==0:
evens.append(number)
else:
odds.append(number)
print(sum(evens))
you are running the first two input statements in for loops and print at the same time.
You can just take inputs first 6 times and store them in a list. After that you can check each input and store in even and odd lists while printing if its even or odd. and print the sum at last.
Your if condition makes no sense:
if numbers % 2 == 0:
What is the value of [1, 2, 3, 6] % 2? There is no such thing as "a list, modulo 2". Modulus is defined between two scalar numbers.
Instead, you have to consider each integer in turn. This is not an operation you get to vectorize; that is a capability of NumPy, once you get that far.
for i in range(6):
num = int(input('Enter a value: '))
# From here, handle the *one* number before you loop back for the next.
If you want to show running sum. You can do something like :
import sys
sum_so_far = 0
while True:
raw_input = input('Enter an integer: ')
try:
input_int = int(raw_input)
if input_int == 0:
sys.exit(0)
elif input_int % 2 == 0:
sum_so_far = sum_so_far + input_int
print("Sum of Even integers is {}. Enter another integer er or 0 to exit".format(sum_so_far))
else:
print("You entered an Odd integer. Enter another integer or 0 to exit")
except ValueError:
print("You entered wrong value. Enter an integer or 0 to exit!!!")

How do I divide a number stored inside a variable? [duplicate]

This question already has answers here:
TypeError: unsupported operand type(s) for /: 'str' and 'str'
(5 answers)
Closed 6 years ago.
The program I am writing allows you to input any number and the program will identify if the number is a prime number or not. However, I am getting an error as shown below.
I have been having trouble with this line of my code:
chosen = input("Input a number")
number = (chosen) / chosen
When I run it, here is the output:
Input a number1
Traceback (most recent call last):
File "C:\Users\engineer2\Desktop\Programs\prime numbers.py", line 3, in <module>
number = (chosen) / chosen
TypeError: unsupported operand type(s) for /: 'str' and 'str'
Here is the full code:
chosen = input("Input a number")
number = (chosen) / chosen
one = 1
if number == (one):
print ("Its a prime number")
else:
print ("Not a prime")
input ("press enter")
You'd have to try and convert the input into a number, float in this case would be explicit.
Keep in mind you should use raw_input instead of input.
try:
chosen = raw_input("Input a number: ")
number = float(chosen) / float(chosen)
except Exception as e:
print 'Error: ' + str(e)
The issue is that input() returns a string rather than a number.
you first need to convert chosen to a number with chosen = float(chosen). Then mathematical operations should work just fine..
You're trying to divide strings, convert to an int using int().
try:
chosen = int(input("Input a number"))
except ValueError:
print('Not number.')
As a side-note, your algorithm for checking primality is flawed, you need to check every number in the range of your number for no remainder division with n not just the input.
a = int(input("Input a number: ")) # Example -> 7
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
print is_prime(a)
>>> True
# One-liner version.
def is_prime(n):
return all(n % i for i in range(2, n))
print is_prime(a)
>>> True
input() function returns a string instead of an int. Try converting it or using raw_input() instead:
Method 1:
chosen = int(input("Input a number"))
number = (chosen) / chosen
Method 2:
chosen = raw_input("Input a number")
number = (chosen) / chosen

What is wrong with this python program? (Traceback error)

my question is why isn't my program working in python 3, It appears to be triggered in the "Speed=dist/time section. Your help would be appreciated.
If you could also correct it would be very helpful.
Illegal=[]
Legal=[]
Count = 0
DIST = 0
TIME = 0
SPEED = 0
def CalSpeed():
global SPEED
SPEED=DIST/TIME
return SPEED
print (" Welcome to the Speed check calculator by Awiar Nasseri")
print ("\n")
Count=int(input("How many registration numbers are there?: "))
LIMIT=int(input ("Speed limit (M/S): "))
VAR=int(input ("How many (M/S) should be allowed over the limit?: "))
LIMIT=LIMIT+VAR
while Count > 0:
Count=Count-1
REG = input ("Enter Registration number: ")
TIME =int (input("Enter the time that the vehicle was in the zone in seconds (e.g. 1min= 60)"))
DIST = input ("Distance inside the zone (M): ")
SPEED=(DIST/TIME)
if SPEED>LIMIT:
Illegal.append(REG)
elif SPEED<LIMIT:
Legal.append(REG)
print ("Press P to print illegal and legal cars or press nothing to exit: ")
if option=="P":
print (Legal[0])
print (Illegal[0])
print("Thank you for using the program, Goodbye")
sys.exit(0)
Here is the error:
Traceback (most recent call last):
File "\\bhs-students\1515787\Desktop\assess.py", line 26, in <module>
SPEED=(DIST/TIME)
TypeError: unsupported operand type(s) for /: 'str' and 'int'
Change line no 26 to
DIST = int(input ("Distance inside the zone (M): "))
SPEED=(DIST/float(TIME))
You are not converting the DIST variable to an Int, meaning that if fails as it can't divide a string by an int.
Just as the error is indicating, you cannot divide a string by an int. You need to convert your input to a numeric type
DIST = float(input("Distance inside the zone (M): "))

TypeError: unsupported operand type(s) for +: 'int' and 'str' python

there are many people who have asked this question but i am a noob at computer programming and cant understand the complicated stuff so i need the answer somewhat dumb down i keep getting the same error and cant correct it
def main():
#A Basic For loop
print('I will display the numbers 1 through 5.')
for num in (1, 2, 3, 4, 5):
print (num)
#The Second Counter code
print('I will display the seconds 1 through 61.')
for seconds in range (1, 61):
print (seconds)
#The Accumulator code
total = 0
for counter in range (5):
number = input (' Enter a number: ')
total = total + number
print (number)
print (total)
here is the full error code :
Traceback (most recent call last):
File "C:/Python34/Lab6-3.py", line 23, in <module>
total = total + number
TypeError: unsupported operand type(s) for +: 'int' and 'str'
First of all, you wrote this:
for counter in range (5):
number = input (' Enter a number: ')
total = total + number
You probably meant this:
for counter in range (5):
number = input (' Enter a number: ')
total = total + number
To answer your question, input() returns a string (like "52"), so you need to convert it to an int (like 52). Fortunately, that's easy in Python:
for counter in range (5):
number = input (' Enter a number: ')
total = total + int(number)
Also, as PEP 8 says, you shouldn't put spaces before function parentheses. You should write this instead:
for counter in range(5):
number = input(' Enter a number: ')
total = total + int(number)
You are trying to add an integer(total) and string(number) at total = total + number. You need to convert var number to integer using int() first. Because input (' Enter a number: ') returns a string.
number = int(input (' Enter a number: '))
Also, your loop should looks like this:
for counter in range (5):
number = int(input (' Enter a number: '))
total = total + number
Total total = total + number needs to be inside your loop.
Be careful if the user try to input a string that can be cast to integer, like "ss" for example. I recommend to add a try/catch
for counter in range (5):
try:
number = int(input (' Enter a number: '))
total = total + number
except,ValueError:
print "You entered a non intenger input"
# you can break loop or continue

What is wrong in the code?

I am very newbie to programming and stack overflow. I choose python as my first language. Today as I was writing some code to refresh and to improve my skills I wrote a little program. But with complete errors.
Here is the Program
a = [1 , 2, 3]
def list_append():
numbers = int(raw_input("Enter the number please"))
a.append(numbers)
print a
def average(list):
for marks in list:
print marks
total = float(sum(list))
total = total / len(list)
print ("Your total average is : %d" %total )
def loop():
add_numbers = raw_input("Do you want to add another number")
if add_numbers == ("y"):
return list_append()
else:
return average()
while True:
loop()
print average(a)
Basically the function of this program is to ask user for the input of the number. Then append to the list and then show the average which is an easy one.
But I want the program to stop after the first input and ask user if they want to give another input ?
Can't understand where is the problem. ** I am not asking for the direct solution. I would rather want an explanation than the solution itself.**
Following is missing in your code:
Need to break any loop, your while loop in going into infinite loop.
while True:
loop()
2. Handle exception during type casting.
numbers = int(raw_input("Enter the number please"))
Create user enter number list in loop function and pass to list_append function to add numbers.
Also return from the loop function to pass argument into average function.
code:
def list_append(numbers):
while 1:
try:
no = int(raw_input("Enter the number please:"))
numbers.append(no)
break
except ValueError:
print "Enter only number."
return list(numbers)
def average(number_list):
avg = float(sum(number_list))/ len(number_list)
return avg
def loop():
numbers = []
while 1:
add_numbers = raw_input("you want to add number in list(Y):")
if add_numbers.lower()== ("y"):
numbers = list_append(numbers)
else:
return list(numbers)
numbers = loop()
avg = average(numbers)
print "User enter numbers:", numbers
print "average value of all enter numbers:", avg
output:
vivek#vivek:~/Desktop/stackoverflow$ python 17.py
you want to add number in list(Y):y
Enter the number please:10
you want to add number in list(Y):y
Enter the number please:e
Enter only number.
Enter the number please:20
you want to add number in list(Y):Y
Enter the number please:30
you want to add number in list(Y):n
User enter numbers: [10, 20, 30]
average value of all enters numbers: 20.0
vivek#vivek:~/Desktop/stackoverflow$
do not use variable names which are already define by python
e.g. list
>>> list
<type 'list'>
>>> list([1,2,3])
[1, 2, 3]
>>> list = [2]
>>> list([1,2,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>>
a = []
def average(list):
total = float(sum(list))
total = total / len(list)
print ("Your total average is : %d" %total )
while True:
numbers = raw_input("Enter the number please or 'q' to quit : ")
if numbers == "q":
average(a)
break
else:
a.append(int(numbers))
Hope this helps

Categories

Resources