checking for decimal points using a while loop - python

I wrote some code to check if two input variables contained decimal points as so:
while "." in n:
print()
print("Please enter only integer numbers")
n = input("Please enter the numerator:")
d = input("Please enter the denominator:")
while "." in d:
print()
print("Please enter only integer numbers")
n = input("Please enter the numerator:")
d = input("Please enter the denominator:")
however, I need a way for these loops to be ignored if the decimal is followed by a 0, e.g. 4.0 or 8.0.
Is there a way to do this, or is there a better way to check if the number entered is a decimal? I don't want to make the input a float from the beginning as it also needs to work if the user enters an integer.
The version of python I'm using is 3.5.4.

this the solution you are looking for
while int(float(d)) != float(d) or int(float(n)) != float(n):
other answers won't work for numbers like 8.05

To piggy-back off of #public static void main 's answer,
you can also consolidate your loop.
while ("." in n and ".0" not in n) or ("." in d and ".0" not in d):
n = input("Enter the numerator: ")
d = input("Enter the denominator: ")

Replace this:
while "." in n:
with this:
while "." in n and ".0" not in n:
This makes the code in the loop execute when "." is found in n, but ".0" is not found in n.

Consider comparing them as the actual value types:
while int(float(d)) != float(d) or int(float(n)) != float(n):

Related

Finding Sum of Variables in Python

I am working on a program that requires the user to enter a number and will continue to loop until a positive number is given. When a positive number is given, it will alert the user and present them with the sum of the digits of their number. However, I thought I had written my code correctly, but it is giving me an incorrect answer. What have I done wrong and how can I fix this?
user_input = float(int(input("Please Enter Your Number:")))
s = 0
while user_input < 0:
float(int(input("Please Enter Another Number: ")))
if user_input > 0:
s += user_input%10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
Four things:
Not sure why you storing the input as float, int should suffice.
If you give a negative input, it will enter the while loop. However, in the while loop, you are not actually assigning the new input to user_input. Fix this by adding user_input =
The while loop guarantees user_input is >= 0, so if user_input > 0: is unnecessary.
Probably the most important, to calculate the sum of digits, you need to repeatedly divide and sum, not just do it once. So, add a while loop.
Final code:
user_input = int(input("Please Enter Your Number: "))
s = 0
while user_input < 0:
user_input = int(input("Please Enter Another Number: "))
while user_input:
s += user_input % 10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
The if statement is generally used to decide if something should be done once.
If you want to keep going until user_input becomes zero, you'll need a while.
Also, I'm not entirely certain why you're storing the number as a float, especially when you make that from an int anyway. It may as well just be an int.
Additionally, you're loop to re-enter the value if it was negative doesn't actually assign the new value to the variable.
And you probably also want to outdent the print statement lest it be done on every iteration of the loop you're about to add.
Of course, some may suggest a more Pythonic way of summing the digits of a positive number is a simple:
sum([int(ch) for ch in str(x)])
That works just as well, without having to worry about explicit loops.
Another way to solve this is using assert and a function:
def sum_num():
# try get user input
try:
user_in = input('Enter Number: ')
assert int(user_in) > 0
except AssertionError:
# we got invalid input
sum_num()
else:
s_d = sum([int(i) for i in user_in])
print('You\'ve entered a positive number! The sum of the digits is: ', s_d)
#run the function
sum_num()
So this will asked user input, if it is not greater than zero it will throw assertion error, which we catch and return the user to inputting the number by calling the function again. If all is well, we split the input into character and add them up. as list('12') gives ['1','2']. We convert to int and add them. :)
The awesome thing about this is you can add more too the asset to capture other issue as floats, character as invalid inputs. E.g.
Assuming literal_eval is important( from ast import literal_eval)
assert isinstance(literal_eval(user_in),int) and int(user_in)>0
Check if user_in is integer and it is greater than 0. So you won’t get issues when user inputs floats or characters.

i have tried many time using for loop but till now i didnt get correct ans so kaindly help to saltout

Ask the user to enter a number x. Use the sep optional argument to print out x, 2x, 3x, 4x, and 5x, each separated by three dashes, like below.
Enter a number: 7
7---14---21---28---35
You're probably running into issues because input() returns a string, not an integer.
Try this:
num = int(input("Choose a number" + "\n"))
output = num
max = 6
for i in range(2, max):
output = str(output) + "---" + str(num * i)
print(output)
def func(param=0):
print(str(param )+ '---'+str(2*param)+'---'+str(3*param)+'---'+str(4*param)+'---'+str(5*param))
n = int(input("Enter a number"))
func(n)
Try this list comprehension
a=int(input())
print("---".join([str((e+1)*a) for e in range(5)]))
def fun():
# Defining default separator
sep = "---"
# Asking user to enter number
x = input("Enter the number: ")
# Asking user for
new_sep = raw_input('Would you like to provide a separator? If yes, please specify. If not, leave blank and press "return key":')
if new_sep:
sep = new_sep
return sep.join(map(str, [x*n for n in range(1,6)]))
Using default separator
fun()
Enter the number: 7
Would you like to provide a separator? If yes, please specify. If not, leave blank and press "return key":
'7---14---21---28---35'
User specifying separator
fun()
Enter the number: 7
Would you like to provide a separator? If yes, please specify. If not, leave blank and press "return key": ***
'7***14***21***28***35'
You could simply use the sep parameter of print
x=eval(input("Enter a number: "))
print(x,2*x,3*x,4*x,5*x, sep='---')
Output:
Enter a number:7
7---14----21---28---35

Not Getting Desired Output From For Loop

I have this code for a program that should manipulate certain inputs the user enters.
I'm not sure how to only get x number of ouputs (x is specified by the user at the start of the program).
numOfFloats = int(input("Enter the number of floating point inputs: "))
numOfInts = int(input("Enter the number of integer inputs: "))
numOfStrings = int(input("Enter the number of string inputs: "))
for num in range(numOfStrings,0,-1):
print()
ffloats = float(input("Enter a real number: "))
iints = int(input("Enter an integer: "))
string = input("Enter a string: ")
print()
print("float: ", ffloats**(1/10))
print("int: ", iints**10)
print("string: ", (string + string))
I get all three requests each time, even though I have specified in the beginning that I only want 1 float, 2 ints, and 3 strings. I get asked for 3 floats, 3 ints, and 3 strings. I do realize what my code does, but I'm not sure how to get it to where I want it. I have a feeling something is wrong in the for loop conditions.
Any help is appreciated!
ffloats = []
for num in range(numOfFloats):
ffloats.append(float(input("\nEnter a real number: "))
iints = []
for num in range(numOfFloats):
iints.append(int(input("\nEnter an integer: "))
sstrings = []
for num in range(numOfFloats):
sstrings.append(input("\nEnter a real number: ")
print("Floats:", [f**(1/10) for f in ffloats])
print("Ints:", [i**10 for i in iints])
print("Strings:", [s + s for s in sstrings])
If you want them in order, then you'll have to:
for v in range(max([numOfFloats, numOfInts, numOfStrings])):
if v < numOfFloats:
ffloats.append(float(input("\nEnter a real number: "))
if v < numOfInts:
iints.append(int(input("\nEnter an integer: "))
if v < numOfStrings:
sstrings.append(input("\nEnter a string: ")
The program did exactly what you told it to do: given the number of strings -- 3 -- get that many int-float-string sets. You never used the other two quantities to control their loops. You need three separate loops; here's the one for strings, with all the int and float stuff removed.
numOfStrings = int(input("Enter the number of string inputs: "))
for num in range(numOfStrings,0,-1):
print()
string = input("Enter a string: ")
print()
print("string: ", (string + string))
Now just do likewise for ints and floats, and I think you'll have what you want.
Yes, you can do it in one loop, but it's inelegant. You have to find the max of all three numbers and use that as the loop's upper limit. Within the loop, check "num" against the int, float, and string limits, each in turn.
This code would be less readable, harder to maintain, and slower. Do you have some personal vendetta against loops? :-)
If your really want just a single loop, then I would suggest you use a while loop rather than a for loop, as you need to keep looping until all values have been entered.
numOfFloats = int(input("Enter the number of floating point inputs: "))
numOfInts = int(input("Enter the number of integer inputs: "))
numOfStrings = int(input("Enter the number of string inputs: "))
while numOfFloats + numOfInts + numOfStrings:
print()
if numOfFloats:
ffloats = float(input("Enter a real number: "))
if numOfInts:
iints = int(input("Enter an integer: "))
if numOfStrings:
string = input("Enter a string: ")
print()
if numOfFloats:
print("float: ", ffloats**(1/10))
numOfFloats -= 1
if numOfInts:
print("int: ", iints**10)
numOfInts -= 1
if numOfStrings:
print("string: ", (string + string))
numOfStrings -= 1
So for example:
Enter the number of floating point inputs: 1
Enter the number of integer inputs: 2
Enter the number of string inputs: 3
Enter a real number: 1.5
Enter an integer: 2
Enter a string: three
float: 1.0413797439924106
int: 1024
string: threethree
Enter an integer: 2
Enter a string: hello
int: 1024
string: hellohello
Enter a string: world
string: worldworld

Python: the len() function doesn't recognize 0 at the start

I want to test whether a 10 digit number is of 10 length, but whenever the number begins with 0, len() only counts 9.
How can I fix this?
At the moment:
something is a variable made up of numbers, I converted the variable into a string, then made this statement.
if len(something) != 10:
(do something)
My current code:
number = int(input("Enter number: "))
number = str(number)
if len(number) != 10:
print ("Not 10 digits long")
else:
print ("Good")
If I inputted a number with 10 digits it's fine, BUT, when I input a number with 10 digits and starting with zero, the len() function recognizes the number as 9 long. Help plz
Providing yout code, it's because you are casting your input to int, then casting it down to string (input automatic type is str in Python3, if you're using Python2, don't forget to cast as str or using raw_input like hackaholic).
Replace
number = int(input("Enter number: "))
number = str(number)
By
number = input("Enter number: ")
So number will directly be a string. And you can use len() on it. It even works with 0000000000
you forcing it to integer, input take values as string
number = input("Enter number: ")
if len(number) != 10:
print ("Not 10 digits long")
else:
print ("Good")
len function works on string
if you using python 2.x better to use raw_input("Enter Number: ")
Numbers starting with 0 are represented in base 8 (octal numbers) in python. You need to convert them to string to count their digits :
# Not converted
number1 = 0373451234
print "number: "+str(number1)+" digits:"+str(len(str(number1)))
> number: 65950364 digits:8
# Converted
number2 = "0373451234"
print "number: "+str(number2)+" digits:"+str(len(str(number2)))
> number: 0373451234 digits:10

How to add up a variable?

I was wondering how I would sum up the numbers they input for n even though it's an input and not int. I am trying to average out all the numbers they input.
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Start now ")
a+=1
In Python 2.x input() evaluates the input as python code, so in one sense it will return something that you can accept as an integer to start with, but may also cause an error if the user entered something invalid. raw_input() will take the input and return it as a string -> evaluate this as an int and add them together.
http://en.wikibooks.org/wiki/Python_Programming/Input_and_Output
You would be better off using a list to store the numbers. The below code is intended for Python v3.x so if you want to use it in Python v2.x, just replace input with raw_input.
print("Enter as many numbers you want, one at the time, enter stop to quit. ")
num = input("Enter number ").lower()
all_nums = list()
while num != "stop":
try:
all_nums.append(int(num))
except:
if num != "stop":
print("Please enter stop to quit")
num = input("Enter number ").lower()
print("Sum of all entered numbers is", sum(all_nums))
print("Avg of all entered numbers is", sum(all_nums)/len(all_nums))
sum & len are built-in methods on lists & do exactly as their name says. The str.lower() method converts a string to lower-case completely.
Here is one possibility. The point of the try-except block is to make this less breakable. The point of if n != "stop" is to not display the error message if the user entered "stop" (which cannot be cast as an int)
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Enter a number: ")
try:
a+=int(n)
except:
if n != "stop":
print("I can't make that an integer!")
print("Your sum is", a)

Categories