Update an integer variable inside the except block - python-3.x

def inputList():
list=[]
length=int(input("Enter the length of the list : "))
print("Enter the elements -->")
for i in range(length):
print(i)
try:
element=int(input(":"))
list.append(element)
except:
print("Invalid element entered! WON'T BE COUNTED!")
i-=1
print("i NOW :",i)
print("Unaltered list :",list)
return list
I am trying to code the except block such that it also decreases the value of i if an error occurs (Eg. Entering a float instead of int). When the except block runs it prints the decreased value but when the for runs again i remains unchanged and therefore the total length is one less than what it should be (because of one incorrect value).

you can view in a different way and use this, this is more simple and avoid the substract in the counter
def inputList():
list =[]
print("Unaltered list :",list)
length =int(input("Enter the length of the list: "))
print("Enter the elements -->")
i=0
while(i<length):
print(i)
try:
element = int(input(":"))
list.append(element)
i++
except:
print("Invalid element entered! WON'T BE COUNTED!")
print("i NOW :",i)
return list

Does it work if you put your call of i in the last except print statement within str()?
print("i NOW : "+ str(i))

Related

What can I do to add a list and sort out all the prime numbers in the list? Python 3

I am creating a program that
accepts an inputted list
finds all the prime numbers and only displays them.
I tried many different methods, many derived from existing prime filters, but they have hardcoded lists rather user-inputted ones.
I just can't seem to get a filter working with inputting a list, then filtering the prime numbers.
my_list = input("Please type a list")
list(my_list)
prime=[]
for i in my_list:
c=0
for j in range(1,i):
if i%j==0:
c+=1
if c==1:
prime.append(i)
return (prime)
When you get input, you're getting a string. You can't cast a string to a list immediately. Maybe you can request the user to use a separator between the numbers then use split method and cast strings to integers like this:
my_list = input("Please enter the list of numbers and use space seperator")
s_list = my_list.split()
cast_list = [int(num) for num in s_list]
Then, you can work on your prime number task based on your preferred algorithm.
Not sure what your c variable is for, current_number? Your loop returns 'str' object cannot be interpreted as an integer for me. I have used len(my_list) to get the length for the loop.
range() defines as range(start, stop, step) - learn more - it accepts integers and parameters are partially optional.
I copied the code from https://www.codegrepper.com/code-examples/python/how+to+find+prime+numbers+in+list+python
my_list = input("Please type a list")
primes = []
for i in range(0, len(my_list)):
for j in range(2, int(i ** 0.5) + 1):
if i%j == 0:
break
else:
primes.append(i)
print(primes)
More helpful resources from SO: Python function for prime number
I hope this helps.

generating a list but only the first index showed

i want to generate a list, in which only odd number get factorial application. However only the first number will be execute, can you help me? Thanks.
def factorial(x):
if x<=0:
return 1
else:
return x*factorial(x-1)
def odd(x):
if x%2 ==0:
return x
else:
return factorial(x)
def apply_if(factorial,odd,xs):
#xs is a list
i=0
mlst=[]
for x in xs:
if i<len(xs):
return odd(xs[i])
i+=1
mlst=mlst.append(odd(x))
return mlst
You should change apply_if function.
def apply_if(factorial,odd,xs):
mlst=[]
for x in xs:
mlst.append(odd(x))
return mlst
Because at first iteration of loop i will always be smaller than lenght of ws list (if it's not empty). Also append method doesn't return anything so you shouldn't use a = a.append() as it just appends element to given list.

python TypeError: '>; not suppported between instances of 'str' and NoneType

This is the output I need
Invalid input
Maximum is 10
Minimum is 2
The example they start you off with is wrong you must use try/except and while true for the grader to accept. I am having trouble with finding the min and max this is the code I have wrote it is similar to the code they start you off with. They say to have a continue in there but I have no idea where to put it.
I've tried a bunch of combinations as well as tried to go off the answers on this site.
largest_so_far = None
smallest_so_far = None
while True:
num = int(input('Enter a number: '))
if num == 'done' :
break
try:
int(num)
except:
print('Invalid input')
for the_num in [num]:
if num > largest_so_far:
largest_so_far = the_num
for the_num2 in [num]:
if num > smallest_so_far:
smallest_so_far = the_num2
#continue
print('Maximum', the_num)
print('Minimum', the_num2)
I want the output of
Invalid input
Maximum is 10
Minimum is 2
However I get the error
TypeError: '>; not suppported between instances of 'str' and NoneType
Both of your so_far variables are initialized to None, and are compared to some number before assigning new values to them; as the error says, you can't use > to compare a number and None.
A few things.
You aren't populating any list with the numbers entered from the user. Initialize an empty list, and add the valid inputs to the list as the user enters them. If you want the user to be able to type 'done', don't immediately turn it into an integer. You perform that check a few lines later in your try/except block.
user_inputs = [] # Store numbers in here
while True:
num = input('Enter a number: ')
if num == 'done' :
break
try:
user_inputs.append(int(num)) # Add it to the list if it is an int.
except:
print('Invalid input')
Move the initialization of your largest and smallest to after the while loop and instead of setting it to None, set it to the first element in the list (but make sure there are elements in the list first). Since you originally initialized them to None, the first comparison you perform will try to check if an integer is greater than or less than None which doesn't make sense. In this case, it's valid to initialize them to the first element of your input list.
if len(user_inputs) != 0:
largest_so_far = user_inputs[0]
smallest_so_far = user_inputs[0]
else:
print("You didn't enter any numbers!")
largest_so_far = None
smallest_so_far = None
There is no need to loop over the same list twice. You can do both checks in one loop. Perform a for-each loop over each element in user_inputs. Fix the comparison in where you check for the smallest element. You should use the < operator instead of the > operator.
for element in user_inputs:
if element > largest_so_far:
largest_so_far = element
if element < smallest_so_far:
smallest_so_far = element
In your code, the_num and the_num2 will be the last element of your list and not the smallest/largest values, which is what your objective was. Instead, print out the smallest and largest values.
print("Maximum:", largest_so_far)
print("Minimum:", smallest_so_far)
Output:
Enter a number: 12
Enter a number: 51
Enter a number: -2
Enter a number: 3.4
Invalid input
Enter a number: test
Invalid input
Enter a number: 5
Enter a number: 2
Enter a number: done
Maximum: 51
Minimum: -2

Value-Returning Function Not Returning Any Value

Am I doing something wrong? There was no errors running the program. This should output a boolean value, but when I run it there is no return value. The program lets the user to enter a number, but then the program doesn't return anything.
def main():
num = int(input("Enter a number:"))
isPrime(num)
def isPrime(num):
if num < 2:
return False
elif num == 2:
return True
else:
for counter in range(2, num):
if num % counter == 0:
return True
return False
main()
Do you mean to print isPrime (num)?
No, the return statement itself will not print to the console. The print statement does that.
"return" only returns that value from the function, it does not display anything to the screen. You could assign the value that is being returned to a variable, but if it is not assigned or used, it is lost. If you wanted it to actually be displayed, you could do
print(isPrime(num))
which will then print out the resulting boolean to the console, or assign the returned value to a variable for later use.
You may do like this
result = isPrime(num)
print(result)

int object is not iterable?

I was attempting to create a program that would take a user input which would be a string of numbers and print out how many times each number occurred. However, I receive a TypeError stating that the int object is not iterable? How would I fix this and why is it happening? Thank you.
def main():
count = {}
user_input = input("Enter numbers separated by spaces: ")
for number in user_input.split():
if number in count:
count[number] = count[number] + 1
else:
count[number] = 1
print(count)
for k,v in count.values():
if v == 1:
print(k,"occurs one time")
else:
print(k,"occurs",v,"times")
main()
Replace:
for k,v in count.values():
With:
for k,v in count.items():
For your loop, you need both the key, k, and the value, v. count.values() will return only the values. count.items(), by contrast, will return both.
For every key check its value like this:
for key in count:
if count[key] == 1:
print(key,"occurs one time")
else:
print(key,"occurs",count[key],"times")
count.values() method returns only values in dictionary not keys. count.items() will return you key value pairs.

Resources