Errors when converting input() function into an integer [duplicate] - python

This question already has an answer here:
Python - How to break while loop after empty value in a int turning input? [duplicate]
(1 answer)
Closed 2 years ago.
I have been trying to simply turn an input() function into an integer as the title of this question suggests. I am essentially trying to run a program that takes in as many inputs as the user inputs, but when an empty string is inputted, it breaks out of a loop and returns the average of all inputted numbers. Currently, my code looks like this:
count = 0
sum = 0.0
number = 1.0
while number != 0:
number = int(input(""))
sum = sum + number
count += 1
if number == 0:
continue
if number == "":
break
else:
print("Average is {}".format(sum / (count-1)))
The issue i face is the error:
ValueError: invalid literal for int() with base 10: ''
Does anyone have a simple solution for this? I feel like i'm overlooking something rather simple?

if number == "":
break
In the case where you want this to happen, number got its value as int(input()). That is, the attempt to convert to int happens first. Since an empty string cannot be converted to int, this test is not reached before the exception is thrown.
You should test for the exception anyway, using try:/except:. But if you want to compare a string to a string, you need to do it at the point where you still have the strings you want to do the comparison with.

Related

How can I fix this code so that inputs that start and end with 0 will show the zeros

My code runs fine, for example, if i input 123, i will get 321. However there is a problem when I try the input 01230, it would output 321. I can't seem to figure it out.
edit: it has to be done using integers as data type.
while True:
reverse=0
num=str(input("Enter an integer of at least 2 digits or -1 to quit: "))
if num == str(-1):
break
elif len(num)< 2 or len(num)>11:
print("error")
else:
num=int(num)
while(num>0):
lastDigit=num%10
reverse=(reverse*10)+lastDigit
num=num//10
print(reverse)
I have tried using if statements to check for the zeros but i felt like that was too inefficient and couldn't figure out a better way.
You could just keep your variables as strings. Following is a snippet of code that tweaks your current program.
while True:
reverse=0
num=str(input("Enter an integer of at least 2 digits or -1 to quit: "))
if num == str(-1):
break
elif len(num)< 2 or len(num)>11:
print("error")
else:
reverse = num[::-1]
print(reverse)
Testing this results in the following terminal output.
#Dev:~/Python_Programs/Palindrome$ python3 Reverse.py
Enter an integer of at least 2 digits or -1 to quit: 01230
03210
Enter an integer of at least 2 digits or -1 to quit: -1
Give that a try and see if it meets the spirit of your project.
First of all, you don't need to use str() function to convert the value you get from user, because input() function always returns string as return type. See https://docs.python.org/3/library/functions.html#input for more information.
This part will try to convert string num into integer but it will ignore the leading zeros because 0123 does not make any sense as an integer if you think about it.
num=int(num)
This part also won't work for the numbers that are multiplies of 10, you can either use a condition to check if that is the case and use that information at the end or you can use some other method like adding 1 to number at the beginnig and deal with it at the end (ie. 5670 -> 5671 -> 1765 -> 0765 but again leading zeros does not make any sense if you don't work with strings)
lastDigit=num%10
reverse=(reverse*10)+lastDigit
num=num//10
What you can do is, you can count the 0s at the beginning and at the end, use the same logic you already did while ignoring them and simply add when you finish reversing the number. For counting the 0s at the beginning, you should either use string format or input user again until he/she inputs a number that has no leading zeros and for the 0s at the end, use modulo operator.
You can take a look at Display number with leading zeros, this might help. You may also want to add some error handling since you directly convert user input into integer.

input which number in row and output the number [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 10 months ago.
n=[0]*365
s=0
s1=1
s2=2
s3=3
s4=4
s5=5
s6=6
for i in range(len(n)):
n[i]=4+1
s=s+7
s1=s1+7
s2=s2+7
s3=s3+7
s4=s4+7
s5=s5+7
s6=s6+7
if n[i]==s:
n[i]=0
elif n[i]==s1:
n[i]=1
elif n[i]==s2:
n[i]=2
elif n[i]==s3:
n[i]=3
elif n[i]==s4:
n[i]=4
elif n[i]==s5:
n[i]=5
elif n[i]==s6:
n[i]=6
Hey everyone here is my code i need to imput which number in row in array it is and it needs print out the number like if i input 300 it needs to output the 300th number in the list
I have tried using print(n[input()] but that obvioslly didnt work can you please help me
It is because input returns a string. The following should work:
print(n[int(input())])
However, note that this will fail if you input something else than a number as python will fail in the int conversion.

Function to detect integers instead string in Python [duplicate]

This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
How can I check if string input is a number?
(30 answers)
Closed 1 year ago.
I'm trying to make a function that count the numbers of characters in a string and detect when an integer is typed, the condition is use "if" function. I'd expect that if I type any integer like"4464468" instead a string, the program displayed: "Sorry, you typed an integer". But, instead, counts the total number and displayed "The word you type has 7 characters".
My code is next:
def string_lenght(mystring):
return len(mystring)`
#Main Program
mystring = (input("Type a word: "))
if type(mystring) == int or type(mystring) == float:
print("Sorry, you typed an integer")
else:
print("The word you typed has",string_lenght(mystring), "characters")
I'm Newbie at Python. I really appreciate your help and patience.
Best regards.
input() always returns a string so you can try to convert it into int/float, if the operation is successful then it's a number, else it is a string:
try:
float(mystring)
print("Sorry you typed an integer")
except ValueError:
# Rest of the code ...

python gives me unexpected variable [duplicate]

This question already has answers here:
How to check if input is float or int?
(4 answers)
Determine the type of an object? [duplicate]
(15 answers)
Closed 2 years ago.
def check(checked):
checked = {}
if checked == float:
return format(checked, '.2f')
else:
checked = "not a float"
return checked
# convert to float and check
a = input('Enter price for item 1 : ')
a = check(a)
b = input('Enter price for item 2 : ')
c = input('Enter price for item 3 : ')
d = input('Enter price for item 4 : ')
e = input('Enter price for item 5 : ')
print(a)
whenever I use input for a and expect it to change it returns as not a float even when it has a decimal point. I am trying to get a number to a 2 decimal point limit and if it's not a float value to ignore it. I put the else statement to see what's been going wrong I tried using is instead of == but I still get the same result.
You’re reassigning the checked variable. Don’t do that.
def check(checked):
if isinstance(checked, float):
return format(checked, '.2f')
else:
return "not a float"
Not sure what you were trying to achieve with checked = {} but all it seemed to be doing was ensuring that checked was always a dictionary, never a float, and never the actual bout value.
To test if something is a float you use isinstance, not == or is
And then reassigning checked to a message which was returned “not a float” is just bad practice.
See the above for a cleaner and (hopefully) working implementation
In python whatever input you take integer,float or any other ,The Input will be of String data type.
Here is the solution of your problem , It will only work if the input is positive value and the input is either float or integer.
Code:
def check(checked):
if checked.isdigit():
return checked
else:
return format(float(checked), '.2f')
a = input('Enter price for item 1 : ')
print(check(a))
This code will return float value upto 2 decimal places if float value is entered and will leave the number as it is if its not a float value

collatz sequence name not defined [duplicate]

This question already has answers here:
Collatz Sequence. (Python 3)
(3 answers)
Closed 4 years ago.
calculation = 0
def collatz(number):
global calculation
if number % 2 == 0:
calculation = number // 2
print(calculation)
return calculation
#odd number
elif number % 2 == 1:
calculation = 3 * number + 1
print(calculation)
return calculation
try:
number = collatz(input('Type a number:')))
except:
while type(number) != int:
print('Please type a numerical value')
number = collatz(int(input('Type a number:')))
while calculation > 1:
collatz(calculation)
Question:
while doing a project from the python book i'm reading i was instructed to create a program that utilizes the collatz conjecrture. I had no problems doing everything up to the point where it wanted me to do exception handling in case the user types a none integer value in. i used the type function to loop through everything in the except statements block of code until the user types an integer value but for some reason it throws an error when it reaches the while loop under the except statement stating that "Name 'number' is not defined' and i'm not sure why its throwing this error
In the except block of your code, where will number have been defined? It could not be in the try block, because if you're executing the except block then by definition the operation of the try block had failed.
As a separate comment, consider what type of data you would get back from input and what can collatz return if neither of the if or else conditions is satisfied?

Categories

Resources