t = int(input())
while t:
qu , pt = input().split(' ')
qu = int(qu)
pt = int(pt)
sd = []
for i in range(0,qu):
x = int(input()) # I think I am getting problem in this part of
sd.append(x)
hd , cw = 0 , 0
diff = pt / 10
cwk = pt / 2
for i in range(0,qu):
if sd[i] <= diff:
hd += 1
else:
if sd[i] >= cwk:
cw += 1
if hd == 2 and cw == 1:
print ('yes')
else:
print('no')
t -= 1
When I try to give input like '1 2 3' I get an an error like this
Traceback (most recent call last):
File "C:/Users/Matrix/Desktop/test.py", line 8, in <module>
x = int(input())
ValueError: invalid literal for int() with base 10: '1 2 3'
Why am I seeing this problem ? How do I rectify this ?
The issue is that you're passing it a string rather than an integer. When you typed "1 2 3," you left spaces, which are considered characters. Spaces cannot be cast as integers. If your set on having the input as number space number space number space, then I suggest you split the sentence at the whitespace into a list.
def setence_splitter(user_input):
# splits the input
words = text.split()
Now you have the list, words, which will have each individual number. You can call each individual number using its index in words. The first number will be words[0] and so on.
Related
I am new to learning programming and I tried to make a simple prg to display input digits into English upto 999, it works correctly till 99 but when it comes to 100's than i get following error:
please help me to understand what I am doing wrong?
print('Print digits into english upto 999')
words_upto_ninteen=['','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Eleven','Tweleve','Thirteen','Fourteen','Fifteen', 'Sixteen','Seventeen','Eighteen','Nineteen']
words_tens=['','','Twenty','Thirty','Fourty','Fifty','Sixty','Seventy','Eighty','Ninty']
words_hundreds=[' ','One Hundred','Two Hundred','Three Hundred','Four Hundred','Five Hundred','Six Hundred','Seven Hundred','Eight Hundred','Nine Hundred']
n=int(input("Please enter digits 0 to 999:"))
output=''
if n==0:
output='zero'
elif n<=19:
output=words_upto_ninteen[n]
elif n<=99:
output=words_tens[n//10]+" "+ words_upto_ninteen[n%10]
elif n<=999:
output=words_hundreds[n//100]+" "+ words_tens[n//10]+" "+ words_upto_ninteen[n%10]
else:
output=print('Please enter value upto 999')
print(output)
print('###########################################################################################')
Sample Output:
Please enter digits 0 to 999:433
Traceback (most recent call last):
File "D:/python learning/projects/4flow control/rough2.py", line 21, in <module>
output=words_hundreds[n//100]+" "+ words_tens[n//10]+" "+ words_upto_ninteen[n%10]
IndexError: list index out of range
This solution would work:
print('Print digits into english upto 999')
words_upto_ninteen=['','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Eleven','Tweleve','Thirteen','Fourteen','Fifteen', 'Sixteen','Seventeen','Eighteen','Nineteen']
words_tens=['','','Twenty','Thirty','Fourty','Fifty','Sixty','Seventy','Eighty','Ninty']
words_hundreds=[' ','One Hundred','Two Hundred','Three Hundred','Four Hundred','Five Hundred','Six Hundred','Seven Hundred','Eight Hundred','Nine Hundred']
n=int(input("Please enter digits 0 to 999:"))
output=''
if n==0:
output='zero'
elif n<=19:
output=words_upto_ninteen[n]
elif n<=99:
output=words_tens[n//10]+" "+ words_upto_ninteen[n%10]
elif n<=999:
output=words_hundreds[n//100]+" "+ words_tens[(n//10)%10]+" "+ words_upto_ninteen[n%10]
else:
output=print('Please enter value upto 999')
print(output)
print('###########################################################################################')
You made a mistake in words_ten[n//10] in fourth condition. Hope it helps :)
When the error IndexOutOfRange is encountered, an array field is accessed which does not exist. If the number 100 is reached, the case elif n <= 999: is reached for the first time. We have n = 100, we also have
output = words_hundreds [100 // 100] + "" + words_tens [100 // 10] + "" + words_upto_ninteen [100% 10]
and thus
output = words_hundreds [1] + "" + words_tens [10] + "" + words_upto_ninteen [0]. However, the words_tens array will count to the words_tens [9] field, since 0 starts counting.
So I'm making a calculator that takes in a string and checks to see if it has certain words like add or subtract and then finding integers. However, in my current code, I run it and get this error message:
Traceback (most recent call last):
File "python", line 1, in <module>
File "python", line 7, in calculator
IndexError: string index out of range
The code is typed out below.
def calculator(string):
if "add" in string or "Add" in string:
total = 0
for i in range(len(string)): #loop for length of string
try:
if type(int(string[i])) == int: #checks to see if there is a number in the string
try:
if type(int(string[i+1])): #checks to see if the number is 2 digits
number_1 = int(string[i])*10
except ValueError:
number_1 = int(string[i])
total = total + number_1 #adds all the numbers to a total variable
except ValueError:
pass
print (total)
If someone could help me out that would be great! Thanks so much!
I believe your problem is with type(int(string[i+1]))
as you have a for loop, i can already be pointing to the last index of string. When you add 1 to that, you get an IndexError
Example:
s = 'blabla'
for i in range(len(s)):
print(s[i])
Output:
b
l
a
b
l
a
Example:
s = 'blabla'
for i in range(len(s)):
print(s[i+1])
Output:
l
a
b
l
a
File "C:\Users\python\scratch\untitled-1.py", line 3, in <module>
print(s[i+1])
builtins.IndexError: string index out of range
Sat down with my friend(#Kay Ace Elits) and realised a bunch of things were amiss but we pieced this together
def calculator(string):
if "add" in string:
total = 0
first_string = "" # before a in add
second_string = "" # after d in add
value_list = string.split('add')
for number in value_list:
total += int(number)
print(total)
elif "Add" in string:
total = 0
first_string = ""
second_string = ""
value_list = string.split('Add')
for number in value_list:
total += int(number)
print(total)
### our test your can modify for other factors
### like spellings and different operations
string = "22add43"
calculator(string)
I have tried to write a function that takes sequence of integers as input from the user and returns cumulative totals. For example, if the input is 1 7 2 9, the function should print 1 8 10 19. My program isn't working. Here is the code:
x=input("ENTER NUMBERS: ")
total = 0
for v in x:
total = total + v
print(total)
and here is the output:
ENTER NUMBERS: 1 2 3 4
Traceback (most recent call last):
File "C:\Users\MANI\Desktop\cumulative total.py", line 4, in <module>
total = total + v
TypeError: unsupported operand type(s) for +: 'int' and 'str'
I don't know what this error means. Please help me to debug my code.
This code will work. Remember: read the code and learn how it works.
x = input("Enter numbers: ") #Take input from the user
list = x.split(" ") #Split it into a list, where
#a space is the separator
total = 0 #Set total to 0
for v in list: #For each list item
total += int(v) #See below for explanation
print(total) #Print the total so far
There are two new things in this code:
x.split(y) splits x up into a list of smaller strings, using y as the separator. For example, "1 7 2 9".split(" ") returns ["1", "7", "2", "9"].
total += int(v) is more complicated. I'll break it down more:
The split() function gave us an array of strings, but we want numbers. The int() function (among other things) converts a string to a number. That way, we can add it.
The += operator means "increment by". Writing x += y is the same as writing x = x + y but takes less time to type.
There is another problem with the code: You say you need a function, but this is not a function. A function might look like this:
function cumulative(list):
total = 0
outlist = []
for v in list:
total += int(v)
outlist.append(total)
return outlist
and to use it:
x = input("Enter numbers: ").split(" ")
output = cumulative(x)
print(output)
but the program will work just fine.
Cumulative totals
input_set = []
input_num = 0
while (input_num >= 0):
input_num = int(input("Please enter a number or -1 to finish"))
if (input_num < 0):
break
input_set.append(input_num)
print(input_set)
sum = 0
new_list=[]
for i in range(len(input_set)):
sum = sum + input_set[i]
new_list.append(sum)
print(new_list)
I'm trying to obtain the following: i want to print a range of integers, but if the integer contains more than 10 digits, the '1' in '10' needs to be printed on top.
e.g.:
6 - > 123456
13 - >...................1111
..........1234567890123
Remark, that if it contains less then 10 digits, there's no 'upper line' printed. And the '.' should be replaced just by spaces, but the editor won't let me do that
I've tried the following:
line10 = ''
line1 = ''
if length > 10:
for i in range(length):
if (i + 1) // 10 == 0:
line10 += ' '
else:
line10 += str((i + 1) // 10)
for i in range(length):
line1 += str((i + 1) % 10)
if length > 10:
print(line10)
print(line1)
And: this works, but how can you make it work for let's say 100 or 1000, without having to copy the lines of code?
Thanks in advance.
There may be a more elegant solution to your problem, but I believe this does what you require:
def number_printer(n):
lines = [[] for m in range(len(str(n)))]
for i in range(1, n+1):
diff = len(str(n))-len(str(i))
if diff > 0:
for z in range(diff):
lines[z].append(" ")
for x, y in enumerate(str(i)):
lines[x+diff].append(y)
else:
for x, y in enumerate(str(i)):
lines[x].append(y)
for line in lines:
print "".join(line)
if __name__ == "__main__":
number_printer(132)
Essentially, it is checking the length of each number it counts through against the lenght of the number you wish to print (in this example 132). Wherever it finds a difference (where diff > 0), it appends the appropriate number of blank spaces so all the numbers align (e.g. for the number 12 it would append 1 blank space, as the difference in length between 12 and 132 is 1).
Hopefully this is what you were after!
This program is a bit of a pain. It has to find the average tempearatures. If it is below 60, it must count how many numbers (that were averaged out) were below 60. It must do the same for any number above 80 if the average temperature is above 80. EDIT: instead of asking the user for the # of values, the program will keep accepting until given a blank value. This is my program:
def main():
sums = 0.0
count = 0
heating = 0
cooling = 0
temp = (input("enter a number, <enter> to quit: "))
while temp != " ":
x = float(temp)
sums = sums + x
count = count + 1
temp = eval(input("enter a number, <enter> to quit: "))
avg = sums/count
if avg < 60:
if temp < 60:
heating = heating + 1
if avg > 80:
if temp > 80:
cooling = cooling + 1
print(avg, heating, cooling)
main()
This is the error I keep getting. I have tried variations of asking for the input with and without the eval, and also with switching the temp between float and int. I keep getting errors, more commonly, this one.
Traceback (most recent call last):
File "C:/Python33/heatingcooling.py", line 24, in <module>
main()
File "C:/Python33/heatingcooling.py", line 13, in main
temp = eval(input("enter a number, <enter> to quit: "))
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
Any ideas on how to get this program to run would be much appreciated. As a side note, we are not allowed to use raw inputs, which seemed to be the most common solution for this
Your current loop confuses temp with x a few places. You need to be consistent about them because they're different types (temp is a string and x is a float). Here's a fixed version of the code, with a few other fixes, like testing for an empty string and providing an initial value for avg:
sums = 0.0
count = 0
heating = 0
cooling = 0
avg = 0 # need an initial value for this, in case the first input is empty!
temp = input("enter a number, <enter> to quit: ") # temp is always a string
while temp: # equivalent to testing temp != ""
x = float(temp)
sums = sums + x
count = count + 1
avg = sums/count
if avg < 60:
if x < 60: # compare to x here, not temp
heating = heating + 1
if avg > 80:
if x > 80: # here too
cooling = cooling + 1
temp = input("enter a number, <enter> to quit: ") # moved this to the end of the loop
print(avg, heating, cooling)
Assuming you're in Python 3.x, removing the eval() should work with the input(...)
temp = input("enter a number, <enter> to quit: ")
The Python 3 documentation for input can be found here
Edit It sounds like you need to convert your temp variable into an int after you get it from the input() method, which is a str by default.
temp = float(input("enter a number, <enter> to quit: "))
Also, when you get your first temp variable, remove the outside parentheses:
temp = (input("enter a number, <enter> to quit: "))
to
temp = input("enter a number, <enter> to quit: ")
Assuming your enter a numeric value, you should then be able to cast this value to a float once inside the while loop.
Edit2
In your while loop change it to this:
while temp: # or while temp != ""
# etc.
This will resolve the ValueError: could not convert string to float error. You were terminating the while loop upon entering a space " ", but when the user hits enter, the input is really an empty string "". Thus, you were still entering the while loop and then trying to cast the empty string "" input into a float, which then raised the ValueError.