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

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

Related

How do I get the user to input an int rather than a float?

I'm writing a program that takes in a value from the user, in the console, and I'm casting it to an int like so:
num = int(input("Enter a number: "))
I need my program to work with ints only. This works to convert an actual int entered into the console to an int I can use in the program, but if the user enters a float, like 3.1, then it doesn't cast to an int by truncating or rounding up for example.
How do I get the user to input an int rather than a float? Or how do I convert a floating point input to an int?
You can use a try catch block to ensure they only give you an int:
while True:
try:
num = int(input("Enter a number: "))
#do something with num and then break out of the while loop with break
except ValueError:
print("That was not a number, please do not use decimals!")
When ValueError (when it fails to convert to int) is excepted it goes back to asking for a number which once you get your number you can do things with said number or break out of the loop then and use num elsewhere.
You can use a try except to test if a user input is a whole number. Example code:
while True:
try:
value=int(input("Type a number:"))
break
except ValueError:
print("This is not a whole number.")
This code will loop back to the start if a user inputs something that is not an int.
So int() of a string like "3.1" doesnt work of course. But you can cast the input to a float and then to int:
num = int(float(input("Enter a number: ")))
It will always round down. If you want it to round up if >= .5:
num = float(input("Enter a number: "))
num = round(num, 0)
num = int(num)
You can simply use eval python built-in function. num = int(eval(input("Enter a number: "))).
For converting string into python code and evaluating mathimatical expressions, eval function is mostly used. For example, eval("2 + 3") will give you 5. However, if you write "2 + 3", then u will get only '2 + 3' as string value.
Try:
num = int(float(input("Enter number: ")))
and the float will be rounded to int.
You can also add a try...except method to give error to user if the number cannot be converted for any reason:
while True:
try:
num = int(float(input("Enter number: ")))
print(num)
break
except ValueError:
print("This is not a whole number")
use abs() it returns the absolute value of the given number

How do I make it detect exactly how many digits are in a number?

I am trying to get my code to show each digit individually on its own line, and it does do that. However, I am getting an error at the end of it, so I want to detect exactly how many digits are in the number. I am having trouble finding a solution for this that isn't len(), because for this specific program I am not supposed to use it.
Here's my code:
number = int(input("Enter a positive integer: "))
number = str(number)
digits = 0
while True:
print(number[digits])
digits += 1
You can create a counter and with a while loop should look like:
num = int(input("enter num"
result = 0
while num > 10:
num = num // 10
result += 1
result += 1
print(result)
It throws an error because you are running an infinite while loop. Use for instead.
number = int(input("Enter a positive integer: "))
number = str(number)
digits = 0
for i in number:
print(i)
digits+=1
You can also use the log10 (logarithm with base 10) function:
import math
number = int(input("Enter a positive integer: "))
print(1 + int(math.log10(number)))
You can solve your problem just by printing elements of string concatenated with new-line delimiter without attempts to find how many elements in string:
number = input("Enter a positive integer: ")
print('\n'.join(number))
The reason you’re getting the error is because when the digits acquires the value of the length of the number say l, then number[l] doesn't exist (The indices start from 0)
number = input("Enter a positive integer: "))
# type(number) is <class 'str'> you don't have to convert to int and reconvert to string
# since <class 'str'> implements iterable you could go like this ..
digits = 0
for digit in number:
print(digit) # digit is still a str here
digits += 1

Python Function returing 12 instances of 1 number rather timesing my input my 12

So I'm trying to create a function that allows me to times a users input by 12. However, for example instead of doing 12 x 4 = 64 its gives me 4 12s' e.g. 444444444444
Ive already tried using the return function on its own and Ive tried creating a variable.
Options Ive tried are:
def cube(num):
print("answer =")
return num*12
num1 = input("Enter a number to times by 12: ")
print(cube(num1))
and:
def cube(num):
print("answer =")
answer = num*12
return answer
num1 = input("Enter a number to times by 12: ")
print(cube(num1))
I would expect if input number is 4 i would get 64 but the output is shown as 444444444444
It is because the input is read as a string. If you create string s = 'foo' and do something like this s2 = s*4 then s2 will be equal to foofoofoofoo. To fix your problem convert input to int. So answer = int(num)*12)
When you take in input, you get it as a string first. When you multiply a string, you’ll get repetitions of that string, which is why you’re getting twelve 4s.
You need to convert that input into a number before multiplying it.
Try:
cube(int(num1))
instead.
The function input returns a string, not a number. Multiplying a string by a number repeats the string that many times.
You'll want to convert that string to a number early:
num1 = int(input("Enter a number to times by 12: "))
print(cube(num1))
input("Enter a number to times by 12: ") gets input as string. Python strings allows you to multiply them to a number. The result is a number times repeated string (as you see, 444444444444). If you want to treat input as number, you should convert it to an integer:
num1 = int(input("Enter a number to times by 12: "))
You need to cast the input value to a float or int. input always returns a string.
num1 = float(input('Enter a number to multiply by 12: '))
This will cause a ValueError if you enter something that can’t be converted to a number.
If you need to keep asking for a valid input, I always tend to create a function that does this for me:
def float_input(prompt=''):
while True:
try:
return float(input(prompt))
except ValueError:
print('Invalid Input')
Now replace the input in your code with float_input

How to validate an input with a 4-digit number? [duplicate]

This question already has an answer here:
Python Checking 4 digits
(1 answer)
Closed 1 year ago.
I want to write a program that only accepts a 4-digit input from the user.
The problem is that I want the program to accept a number like 0007 but not a number like 7 (because it´s not a 4 digit number).
How can I solve this? This is the code that I´ve wrote so far:
while True:
try:
number = int(input("type in a number with four digits: "))
except ValueError:
print("sorry, i did not understand that! ")
if number > 9999:
print("The number is to big")
elif number < 0:
print("No negative numbers please!")
else:
break
print("Good! The number you wrote was", number)
But if I input 7 to it it will just say Good! The number you wrote was 7
Before casting the user's input into an integer, you can check to see if their input has 4 digits in it by using the len function:
len("1234") # returns 4
However, when using the int function, Python turns "0007" into simple 7. To fix this, you could store their number in a list where each list element is a digit.
If it's just a matter of formatting for print purposes, modify your print statement:
print("Good! The number you wrote was {:04d}", number)
If you actually want to store the leading zeros, treat the number like a string. This is probably not the most elegant solution but it should point you in the right direction:
while True:
try:
number = int(input("Type in a number with four digits: "))
except ValueError:
print("sorry, i did not understand that! ")
if number > 9999:
print("The number is to big")
elif number < 0:
print("No negative numbers please!")
else:
break
# determine number of leading zeros
length = len(str(number))
zeros = 0
if length == 1:
zeros = 3
elif length == 2:
zeros = 2
elif length == 3:
zeros = 1
# add leading zeros to final number
final_number = ""
for i in range(zeros):
final_number += '0'
# add user-provided number to end of string
final_number += str(number)
print("Good! The number you wrote was", final_number)
pin = input("Please enter a 4 digit code!")
if pin.isdigit() and len(pin) == 4:
print("You successfully logged in!")
else:
print("Access denied! Please enter a 4 digit number!")

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

Categories