how to make a string an integer in python - string

Distance = input("How far are you from the spacecraft in meters? (full positive numbers) \n")
number = Distance.isdigit()
while number == False:
print ("Please enter a number or full number")
Distance = input("How far are you from the spacecraft in meters? (full positive numbers) \n")
number = Distance.isdigit()
while Distance < 600:
print ("Please move back further from the space craft! \n")
Distance = input("How far are you from the spacecraft in meters? (full positive numbers) \n")
So I am trying to compare a string to a integer but I'm not sure how to fix that with out breaking this part
number = Distance.isdigit()
while number == False:

I think you can use this.
def is_digit(Distance):
try:
if int(Distance) & int(Distance) >0:
return True
return False
except ValueError:
return False

Related

How to fix issue where python won't call a function from within a loop

At the yes/no loop, the program won't call the function to re-perform a calculation. Instead, it asks to compute another gcd repeatedly instead of calling the specified function.
I've tried re-inputting the whole function into the question loop if the user inputs yes, but that did not work either.
def gcd(n,m):
if(m==0):
return n
else:
return gcd(m,n%m)
n = int(input("Enter a positive whole number:"))
while True:
if n <= 0:
print ("The number entered is not a positive number!, please try again")
n = int(input("Enter a positive whole number : "))
if n > 0: break
m = int(input("Enter a second positive whole number:"))
while True:
if m <= 0:
print ("The number entered is not a positive number!, please try again")
m = int(input("Enter a positive whole number : "))
if m > 0: break
GCD = gcd(n,m)
print("The GCD of the two numbers you entered is:" ,GCD)
while True:
a = input("Compute another GCD? Enter y/n:").lower()
if a=="y":
gcd(n,m)
elif a=="n":
break
else:
print("Invalid entry. Please enter either y/n:")
print("Goodbye!")
Expected results is that it calls the function gcd(n,m) and re-performs a calculation. Actual results is that it asks to perform another calculation without having actually completed a second calculation.
The function is called. The problem is that you don't do anything with its return value.
You will also need to ask the user for new input. In order to not repeat the same code again you can have a function that does that.
Then the whole code becomes:
def get_2_numbers():
n = int(input("Enter a positive whole number:"))
while True:
if n <= 0:
print ("The number entered is not a positive number!, please try again")
n = int(input("Enter a positive whole number : "))
if n > 0: break
m = int(input("Enter a second positive whole number:"))
while True:
if m <= 0:
print ("The number entered is not a positive number!, please try again")
m = int(input("Enter a positive whole number : "))
if m > 0: break
return n, m
def gcd(n,m):
if(m==0):
return n
else:
return gcd(m,n%m)
a, b = get_2_numbers()
while True:
answer = input("Compute another GCD? Enter y/n:").lower()
if answer == "y":
print(gcd(a, b))
a, b = get_2_numbers()
elif answer == "n":
break
else:
print("Invalid entry. Please enter either y/n:")
print("Goodbye!")
A small downside is that the user will have to answer y even before the first calculation, but I'll leave that as an exercise to the reader.

Excluding 0's from calculations

Hi I have been asked to write a program that will keep asking the user for numbers. The average should be given to 2 decimal places and if a 0 is entered it shouldnt be included in the calculation of the average.
so far I have this:
data = input()
numbers = []
while True:
data = input()
if data == "":
break
numbers.append(float(data))
count = len(numbers)
if count > 0:
newsum = sum(numbers)
average = newsum / float(count)
print("The average is {}".format(average))
Dumb question but how do you ensure the 0's arent considered in the calculation?
Correction: you are not appending the first input to the list
Modification: added an if statement to check whether the input is '0'
data = input()
numbers = []
numbers.append(float(data))
while True:
data = input()
if data == "":
break
if data == '0':
continue
numbers.append(float(data))
count = len(numbers)
if count > 0:
newsum = sum(numbers)
average = newsum / float(count)
print("The average is {}".format(average))

Python 3 Count and While Loop

I am trying to figure out an error in the code below. I need the following conditions to be met:
1) If equal to zero or lower, I need python to state "Invalid Input"
2) If greater than zero, ask whether there is another input
3) As long as there is another input, I need the program to keep asking
4) If "done", then I need Python to compute the lowest of inputs. I have not gotten to this part yet, as I am getting an error in the "done" portion.
print ("Lowest Score for the Racer.")
number = float(input("Please enter score: "))
if number < 0 or number == 0:
print ("Input should be greater than zero.")
while True:
number = float(input('Do you have another input? If "Yes" type another score, if "No" type "Done": '))
if number < 0 or number == 0:
print ("Input should be greater than zero. Please enter score: ")
if number == "Done":
print ("NEED TO COUNT")
break
I tried to modify your code according to your desired output. I think this should give you an idea. However there is still small things to deal in code. I suppose you can manage rest of it.
empthy_list = []
print ("Lowest Score for the Racer.")
while True:
number = float(input("Please enter score: "))
if number < 0 or number == 0:
print ("Input should be greater than zero.")
if number > 0:
empthy_list.append(number)
reply = input('Do you have another input? If "Yes" type another score, if "No" type "Done": ')
if reply == "Yes" :
number = float(input("Please enter score: "))
empthy_list.append(number)
if reply == "Done":
print("NEED TO COUNT")
print("Lowest input is: ",min(empthy_list))
break
I wrote an alternative solution which is more robust regarding input errors. It might include some ideas for improving your code but probably isn't the best solution, either.
print ("Lowest score for the racer.")
valid_input = False
num_arr = []
while not valid_input:
foo = input('Please enter score: ')
try:
number = float(foo)
if number > 0:
num_arr.append(number)
valid_input = True
else:
raise ValueError
while foo != 'Done' and valid_input:
try:
number = float(foo)
if number > 0:
num_arr.append(number)
else:
raise ValueError
except ValueError:
print('Invalid input! Input should be number greater than zero or
"Done".')
finally:
foo = input('Do you have another input? If yes type another score,
if no type "Done": ')
except ValueError:
print('Invalid input! Input should be number greater than zero.')
print("Input done! Calculating lowest score...")
print("Lowest score is ", min(num_arr))

Python 3.4.2 IDLE: Error when defining 'denaryInput'

I am just new really to programming and for homework we had to make a denary to binary converter for homework, using a number inputed by the user. When I run this code I get the following error:
if denaryInput < 0:
NameError: name 'denaryInput' is not defined
I am unsure what I am doing wrong and any answers greatly appreciated.
Code used:
"""We are asking the user for a number"""
def getNumber():
denaryInput = int(input("Please enter a number between 0 and 255: "))
"""We are validating the number"""
def validateNumber():
if denaryInput < 0:
print("Error: Number is too small, try again!" + " \n")
return False
elif denaryInput > 255:
print("Error: Number is too big, please try again!" + " \n")
return False
else:
return True
def binaryNumber():
result = []
for number in range(8):
bit = denaryInput % 2
result.append(bit)
denaryInput = denaryInput // 2
result.reverse()
str1 = "".join(str(x)for x in result)
print (str1 + " \n")
"""Now telling the computer to run the code above and in what order of operations"""
def mainProgram():
answer = getNumber()
validNum = validateNumber()
Binary = binaryNumber()
print("The binary equlivent for that number is " + Binary + " \n")
mainProgram()
You need to pass the denaryInput from the getnumber function as part of a call. The validatenumber function needs a value passed into it to actually be validated. These should be different names in each function.
E.g.:
def validateNumber(numIn):
if numIn < 0
Also, you should validate the number from the getnumber function
denaryInput = int(input("Please enter a number between 0 and 255: "))
if validateNumber(denaryInput): #returns true if number valid
Return denaryInput
Finally, binary is a keyword and should NOT appear in your main function.

Python: only two decimal places after user entered number

How do you make sure that the user only entered a float that has two decimal places. The number cannot be 4 or 4.999 it has to be 4.00 or 4.99 otherwise an error should appear.
while looping:
try:
number = float(input("Number: "))
string_number = (str(number)).split(".")
check_length = len(string_number)
if check_length != 2:
print ("ERROR!")
looping = True
else:
looping = False
except ValueError:
looping = True
You are currently only checking that there is currently just one decimal point.
number.split(".") will return a list. If number is 4.323, it will return ['4', '323'].
What you really want to check in your if clause is that the length of the second element is 2.
if len(string_number[1]) != 2:
Check the second part of the number.
while True:
try:
number = input('Number:')
integral, fractional = number.split('.')
number = float(number)
if len(fractional) == 2:
break
except ValueError:
pass
print('ERROR!')
looping = True
while looping:
number = input("Number: ")
string_number = number.split(".")
if len(string_number) != 2:
print ("ERROR: Needs exactly one decimal point!")
looping = True
elif len(string_number[1]) != 2:
print ("ERROR: Two numbers are required after decimal point!")
looping = True
else:
try:
number = float(number)
looping = False
except ValueError:
print("ERROR: Number is not valid!")
looping = True
Making some minor changes eliminates the need for the variable looping. Since our goal is to get a valid number, we can just test for that:
number = None
while not number:
s = input("Number: ")
string_number = s.split(".")
if len(string_number) != 2:
print ("ERROR: Needs exactly one decimal point!")
continue
elif len(string_number[1]) != 2:
print ("ERROR: Two numbers are required after decimal point!")
continue
try:
number = float(s)
except ValueError:
print("ERROR: Number is not valid!")
I would write this way:
while True:
try:
str_num=input("Number: ")
num=float(str_num) # ValueError if cannot be converted
i, f=str_num.split('.') # also ValueError if not two parts
if len(f)==2:
break # we are done!!!
except ValueError:
pass
print('ERROR! ') # either cannot be converted or not 2 decimal places
print(num)

Resources