Why am I getting a value error from my while loop? - python

I don't understand why I'm getting a Value Error. I specifically exclude the "*" character.....yet it still gets included and causes an error. I understand I have to figure out how to reverse the output too but I'll worry about that later.
Write a program that reads a list of integers, one per line, until an
"*" is read, then outputs those integers in reverse. For simplicity in coding output, follow each integer, including the last one, by a
comma.
Note: Use a while loop to output the integers. DO NOT use reverse() or
reversed().
Ex: If the input is:
2
4
6
8
10
*
the output is:
10,8,6,4,2,
my code:
''' Type your code here. '''
while True:
try:
if input().strip() != "*":
num = input().strip()
lst = []
lst.append(num)
print("{},".format(int(num),end=""))
else:
break
except EOFError:
break
Enter program input (optional)
2
4
6
8
10
*
Program errors displayed here
Traceback (most recent call last):
File "main.py", line 8, in <module>
print("{},".format(int(num),end=""))
ValueError: invalid literal for int() with base 10: '*'
Program output displayed here
4,
8,

It's because you're using input 2 times:
First input read 10 and it passes the if.
Second input read "*" inside the "action" section of your code and fails.
Also:
You're resetting the list on every loop. The initialization should be outside of the loop.
Using a more pythonic way to check if the "*" is in the data should avoid any further issues, for example, using "**" or having an incorrect input "1*".
An updated version of the code will be:
''' Type your code here. '''
lst = []
while True:
try:
data = input().strip()
if "*" not in data:
lst.append(num)
print("{},".format(int(num),end=""))
else:
break
except EOFError:
break

Use append to add numbers to the list lst, and pop to remove them from the end of the list. Use f-strings or formatted string literals to print the list elements.
num = input().strip()
lst = []
while num != '*':
num = int(num)
lst.append(num)
num = input().strip()
while lst:
num = lst.pop()
print(f"{num},", end='')
print('')
Comments on your code:
while True:
try: # No need for the try block.
if input().strip() != "*": # This input gets lost: not assigned to any variable.
num = input().strip() # This input is not tested whether it is '*'.
lst = [] # This list gets assigned anew ands becomes empty with every iteration.
lst.append(num)
print("{},".format(int(num),end="")) # Use f-strings instead (easier).
else:
break
except EOFError:
break

Related

print all the list elements with an even index number, error statement

for my task, which I think I have already right, but on Snakify it shows me this error statement: Traceback (most recent call last): ValueError: invalid literal for int() with base 10: '1 2 3 4 5'
On google colab this error doesn't show up, on snakify it does, but I need this error to go so I can check my solutions. Any suggestions?
Task is: a list of numbers, find and print all the list elements with an even index number.
a = []
b = []
numbers = input()
for n in numbers.split():
a.append(int(n))
if int(n) % 2 == 0:
b.append(a[int(n)])
print(b)
int() can convert only numbers and raise error if argument contain a non-digit char, for example space ' '. You can use:
nums = input().split() # split() method splited string by spaces
a = []
for i in range(len(nums)): # len() function return count of list elements
if (i % 2) == 0:
a.append(nums[i])
print(a)
Also you can get
IndexError: list index out of range
Please comment if interesting why
int(input()) will only work on a single number. If you want to enter many numbers at once, you'll have to call input() first, split it into separate numbers, and call int() on each one:
numbers = input()
for n in numbers.split():
a.append(int(n))
Or using a list comprehension:
numbers = input()
a = [int(n) for n in numbers.split()]

Python challenge TypeError: 'int' object is not iterable

This is one of the challenge question:
Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. The numbers obtained should be printed in a comma-separated sequence on a single line. Hints: In case of input data being supplied to the question, it should be assumed to be a console input.
Here is what I'm trying to do: if there's an input, then check if all the digits are even numbers and display a message. If there's no input, then it will append the number from 1000 to 3000 that contains all even digits to a list. I heard nested loop is bad practice, so better solution is welcomed. Encountered Error: TypeError: 'int' object is not iterable.
num = input("Enter a number to check for even digit. Skip if you want to see 1000-3000: ")
if num:
list = [int(x) for x in num]
for i in list:
if i % 2 != 0:
x = False
break
else:
x = True
if x:
print("It has all even digits!")
else:
print("It contains odd digits.")
else:
t = True
printl = []
for i in range(1000,3001):
l = [str(x) for x in i] # the error line
for q in l:
if int(q) % 2 != 0:
t = False
break
else:
printl.append(q)
print(printl)
You are trying to iterate over the integer i in the for loop below:
for i in range(1000,3001):
l = [str(x) for x in i] # the error line
If you want to iterate over the string representation of that integer, use this instead:
for i in range(1000,3001):
l = [x for x in str(i)] # the error line
So your main issue (question) is about that integers are not iterable on this line:
for i in range(1000,3001):
l = [str(x) for x in i] # the error line
so you are trying to iterate over i which is of type int which cannot be iterated, you need to convert it to a string first so this:
for i in range(1000,3001):
l = [x for x in str(i)]
That however is quite redundant because you can immediately do this:
l = [int(x) for x in str(i)]
and avoid conversion to int later.
However your logic is flawed, in this loop it matters only if the last digit is even or not:
for i in list:
if i % 2 != 0:
x = False
break
else:
x = True
Other flaw is in the second loop where you append all even numbers to that list so it will basically create a list of 0, 2, 4, 6, 8 because you append single digits. Over all your code can be reduced to this (at least):
# create a list to append to
all_even = []
# ask for user input
num = input('Enter a number to check for even digit. Skip if you want to see 1000-3000: ')
# loop over either user input if they did input anything or over the range
# if they didn't input anything
for i in (num and [num]) or range(1000, 3000 + 1):
# check if all digits in the number are even and
# if they are append to the list
if all(int(x) % 2 == 0 for x in str(i)):
all_even.append(i)
# now check if user did input anything and if they did return the boolean
# of the list `all_even` which if the number had all even digits
# will contain one item so the bool will return True and or returns first True
# value or last one if none are True. So in case user did not input anything go to the
# next logical operator `or` and if there is anything in `all_even` print it out
# lastly print False if there were no values found at all
print(num and bool(all_even) or all_even or False)
Sources:
"short-circuiting" of logical operators

Error in a loop which prints string from last index to first index

I have written this loop to print any input string from its last index to its first index on each separate line. But when I run it, technically, it does work correctly only if the string is all lowercase. It does not work correctly for uppercase strings. In both cases, either the input string is uppercase or lowercase, the following output displays with a traceback which I do not know what for:
OUTPUT :
C:\Users\CM-Ajk\PycharmProjects\Pract\venv\Scripts\python.exe C:/Users/CM-Ajk/PycharmProjects/Pract/main.py
Enter: emadd
d
d
a
m
e
Traceback (most recent call last):
File "C:\Users\CM-Ajk\PycharmProjects\Pract\main.py", line 166, in <module>
print(name[i-1])
IndexError: string index out of range
Process finished with exit code 1
CODE:
i = 0
name = input("Enter: ")
while True:
print(name[i-1])
i = i-1
for i in name[::-1]: print(i)
Try above instead, [::-1] returns reversed string.
i think is better to define a condition for the name length
and start -1 on i
name = input("Enter: ")
i = len(name) - 1
while i > 0 :
print(name[i])
i = i - 1
You can refactor your code as below:
name = 'emadd'
j = len(name)-1
while j>= 0:
print(name[j])
j-= 1
Or optionally handle int with for loop like this:
for i in range(len(enter)-1,-1,-1):
print(enter[i])

How do I add up total numbers in a text file for python?

I've been getting stuck in the total_num() function as it gives the error
"ValueError: invalid literal for int() with base 10: ''"
I know how to do it if its a defined list but if its set by the user I get confused.
def total_num():
total = 0
num_file = open("num_list.txt", "r")
line = num_file.read()
while line != "":
num1 = int(num_file.readline())
total = total + num1
print total
def read_num():
num_file = open("num_list.txt", "r")
for line in num_file:
print line.rstrip("\n")
def write_num():
num = input("Enter a number: ")
num_file = open("num_list.txt", "w")
num_consec = 0
for x in range(num):
num_consec = num_consec + 1
num_file.write(str(num_consec)+ "\n")
num_file.close()
def main():
write_num()
read_num()
total_num()
main()
The error is because you are getting an empty string from your text file. Look at this bit of code; you are reading the whole file into memory.
line = num_file.read()
while line != "":
Over here, unless you opened an empty file line != "" you are comparing the whole file with an empty string. So you will keep on looping until your num1 = int(num_file.readline()) reads an empty line from the file.
You can find the solution if you look at your read_num method.
for line in num_file:
try:
total += int(line)
except ValueError:
print "Invalid data in ", line
By using try except you are able to handle the situation where the file might contain other invalid texts.
You are reading the file in an odd way - namely, twice. read() puts the entire file contents into a string. If you repeatedly check whether there are characters in it, and then never change it, it will either not execute or loop infinitely.
Using input() to get a number will work, but it's better to use raw_input() and cast with int() for safety. Also, xrange() is a better practice than range() in Python 2. You don't need to keep a manual counter if you're already iterating over range(), either.
Overall, your code could be condensed to this:
def write_num():
num = int(raw_input("Enter a number: "))
with open("num_list.txt", "w") as output:
for x in xrange(1, num+1):
output.write(str(x) + "\n")
def read_num():
with open("num_list.txt") as f:
numbers = map(int, f)
for number in numbers:
print number
return numbers
def main():
write_num()
print sum(read_num())
main()

number/numbers to list by using input() [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 6 years ago.
Maybe this is a very basic question but i am a beginner in python and couldnt find any solution. i was writing a python script and got stuck because i cant use python lists effective. i want user to input (number or numbers) and store them in a python list as integers. for example user can input single number 1 or multiple numbers seperated by comma 1,2,3 and i want to save them to a list in integers.
i tried this ;
def inputnumber():
number =[]
num = input();
number.append(num)
number = map(int,number)
return (number)
def main():
x = inputnumber()
print x
for a single number there is no problem but if the the input is like 1,2,3 it gives an error:
Traceback (most recent call last):
File "test.py", line 26, in <module>
main()
File "test.py", line 21, in main
x = inputnumber()
File "test.py", line 16, in inputnumber
number = map(int,number)
TypeError: int() argument must be a string or a number, not 'tuple'
Also i have to take into account that user may input characters instead of numbers too. i have to filter this. if the user input a word a single char. i know that i must use try: except. but couldn't handle. i searched the stackoverflow and the internet but in the examples that i found the input wanted from user was like;
>>>[1,2,3]
i found something this Mark Byers's answer in stackoverflow but couldn't make it work
i use python 2.5 in windows.
Sorry for my English. Thank you so much for your helps.
In your function, you can directly convert num into a list by calling split(','), which will split on a comma - in the case a comma doesn't exist, you just get a single-element list. For example:
In [1]: num = '1'
In [2]: num.split(',')
Out[2]: ['1']
In [3]: num = '1,2,3,4'
In [4]: num.split(',')
Out[4]: ['1', '2', '3', '4']
You can then use your function as you have it:
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
number = map(int,num)
return number
x = inputnumber()
print x
However you can take it a step further if you want - map here can be replaced by a list comprehension, and you can also get rid of the intermediate variable number and return the result of the comprehension (same would work for map as well, if you want to keep that):
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
return [int(n) for n in num]
x = inputnumber()
print x
If you want to handle other types of input without error, you can use a try/except block (and handle the ValueError exception), or use one of the fun methods on strings to check if the number is a digit:
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
return [int(n) for n in num if n.isdigit()]
x = inputnumber()
print x
This shows some of the power of a list comprehension - here we say 'cast this value as an integer, but only if it is a digit (that is the if n.isdigit() part).
And as you may have guessed, you can collapse it even more by getting rid of the function entirely and just making it a one-liner (this is an awesome/tricky feature of Python - condensing to one-liners is surprisingly easy, but can lead to less readable code in some case, so I vote for your approach above :) ):
print [int(n) for n in raw_input('Number(s): ').split(',') if n.isdigit()]
input is not the way to go here - it evaluates the input as python code. Use raw_input instead, which returns a string. So what you want is this:
def inputnumber():
num = raw_input()
for i, j in enumerate(num):
if j not in ', ':
try:
int(num[i])
except ValueError:
#error handling goes here
return num
def main():
x = inputnumber()
print x
I guess all it is is a long-winded version of RocketDonkey's answer.

Categories