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): "))
Related
When writing up a program in python version 3.3.0 (because of non-admin privileges i can't update) it worked completely fine, however now that i am using python version 3.3.2 it no longer works, the program goes as follows:
num = input("please enter a value and press enter: ")
(assuming 1 is chosen)
conv = input("what unit is the measurement in? cm, m, or km: ")
(assuming cm is chosen)
if conv == "cm":
print("chosen value is cm, converting to m and km")
m = num/100
print(m , "meters")
km = num/100000
print(km , "kilometers")
the desired output is (found in 3.3.0):
please enter value and press enter: 1
your chosen value is: 1
what unit is the measurement in? cm, m, or km: cm
you have chosen cm, converting to m and km
0.01 meters
1e-05 kilometers
but instead i get (in 3.3.2):
please enter value and press enter: 1
your chosen value is: 1
what unit is the measurement in? cm, m, or km: cm
you have chosen cm, converting to m and km
Traceback (most recent call last):
File "C:/Users/USER/Desktop/QUESTION.py", line 10, in <module>
m = num/100
TypeError: unsupported operand type(s) for /: 'str' and 'int'
I am surprised that it works somewhere anyway. When using the input() function, Python returns a string (str) from what has been entered.
So basically, you just need to convert the text to an integer, using num = int(num) after having initialized your num variable. To be clean, you'd also need to implement a basic error handling system, in case the input entered by the user is not implicitely convertable to an integer.
For example:
num = ""
while not isinstance(num, int):
num = input("Please, enter a number\n>>> ")
try:
num = int(num)
except ValueError:
pass
# proceed with your code...
I'm very new to programming, just started working my way through a Python course. I've been looking through the course material and online to see if there's something I missed but can't really find anything.
My assignment is to make a chatbot that takes input and summarizes the input but also calculates the average. It should take all the input until the user writes "Done" and then terminate and print the results.
When I try to run this:
total = 0
amount = 0
average = 0
inp = input("Enter your number and press enter for each number. When you are finished write, Done:")
while inp:
inp = input("Enter your numbers and press enter for each number. When you are finished write, Done:")
amount += 1
numbers = inp
total + int(numbers)
average = total / amount
if inp == "Done":
print("the sum is {0} and the average is {1}.". format(total, average))
I get this error:
Traceback (most recent call last):
File "ex.py", line 46, in <module>
total + int(numbers)
ValueError: invalid literal for int() with base 10: 'Done'
From searching around the forums I've gathered that I need to convert str to int or something along those lines? If there are other stuff that need to be fixed, please let me know!
It seems that the problem is that when the user types "Done" then the line
int(numbers) is trying to convert "Done" into an integer which just won't work. A solution for this is to move your conditional
if inp == "Done":
print("the sum is {0} and the average is {1}.". format(total, average))
higher up, right below the "inp = " assignment. This will avoid that ValueError. Also add a break statement so it breaks out of that while loop as soon as someone types "Done"
And finally I think you are missing an = sign when adding to total variable.
I think this is what you want:
while inp:
inp = input("Enter your numbers and press enter for each number. When you are finished write, Done:")
if inp == "Done":
print("the sum is {0} and the average is {1}.". format(total, average))
break
amount += 1
numbers = inp
total += int(numbers)
average = total / amount
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
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!
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