As I run my code, the program always returns:
'str' object is not callable in the ninth line and I don't know why.
sum = 0
count = 0
binNum = input('Input your number: \n')
while count != len(binNum):
if binNum(count) == 1:
sum = sum + 2**count
count = count + 1
else:
count = count + 1
if count == len(binNum):
print(sum)
Thank you for your help.
Looks like you're trying to access the countth character of the string binNum, and see if it is the character '1'. In which case, you should use square brackets. And compare it to the character '1', not the digit 1.
if binNum[count] == '1':
By the way, if you're trying to convert a string of ones and zeroes into its equivalent decimal number, you're scanning over the digits backwards. In your algorithm, the leftmost digits contribute the least to the sum, and the rightmost digits contribute the most. You may want to reverse the input string before scanning it.
binNum = input('Input your number: \n')
binNum = binNum[::-1]
You have to change
if binNum(count) == 1:
to
if count == 1:
Also, you could convert input line as:
binNum = str(input('Input your number: \n'))
Related
num = [int(d) for d in str(input("Enter the number:"))]
even,odd = 0,0
for i in range(0,len(num)):
if i % 2 ==0:
even = even + num[i]
else:
odd = odd + num[i]
print(abs(odd-even))
What does the first line mean for taking strings as input?
The line:
num = [int(d) for d in str(input("Enter the number:"))]
will error out if anything but digits are entered. If only digits are entered, then they end up being individual integer entries in num. For example, for the input 124, the resulting value of num will be [1, 2, 4]. The code will then go on to process each of those single digit numeric values.
BTW, the call to str() is redundant, as input already returns a string value.
I'm trying to solve this problem but I'm just stuck at the very end.
I need to make a function that cycles the 5 digit number around. So for example, the input is 12345 and then it should be 51234, 45123 etc. Then when it cycles it out, until it's at the beginning again which is 12345, it should print out the biggest number of all of the cycled ones.
def number_cycle(number):
if number >= 99999 or number < 9999:#this is for limiting the number to 5 digits
print('Error,number isnt in 5 digit format')
else:
e = number%10 #5th digit
d = int(((number-e)/10)%10)#4th digit
c = int(((((number - e)/10)-d)/10)%10)#3rd digit
b = int(((((((number - e)/10)-d)/10)-c)/10)%10)#2nd digit
a = int(((((((((number - e)/10)-d)/10)-c)/10)-b)/10)%10)#1st digit
print(e,a,b,c,d)
print(d,e,a,b,c)
print(c,d,e,a,b)
print(b,c,d,e,a)
print(a,b,c,d,e)
number = eval(input('Input number:'))
I can't figure out how to get the biggest number out of all these.
Can you help?
You can try this solution:
def get_largest(number):
num_str = str(number)
num_len = len(num_str)
if num_len != 5:
print(f"Error: {number} is not a 5 digit number")
return
largest = 0
for i in range(num_len):
cycled_number = int(num_str[i:] + num_str[:i])
print(cycled_number)
if cycled_number > largest:
largest = cycled_number
print("Largest: ", largest)
number = int(input("Input number: "))
get_largest(number)
It will basically convert your 5 digit number to a string using a for loop, and then rotate the string, compare the rotated numbers and print the largest one.
Note:
In your original code snippet I'd suggest not to use the built-in eval method as it can be quite dangerous if you don't know what you are doing so avoid it as much as you can except you really have no other way to deal with a problem. More here:
https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
https://medium.com/swlh/hacking-python-applications-5d4cd541b3f1
Hey guys I'm fairly new to the programming world. For a school practice question I was given the following text and I'm suppose to convert this into code. I've spent hours on it and still can't seem to figure it out but I'm determine to learn this. I'm currently getting the error
line 7, in <module> if i % 2 == 0: TypeError: not all arguments converted during string formatting
What does this mean? I'm still learning loops and I'm not sure if it's in the correct format or not. Thanks for your time.
# GET user's credit card number
# SET total to 0
# LOOP backwards from the last digit to the first one at a time
# IF the position of the current digit is even THEN
# DOUBLE the value of the current digit
# IF the doubled value is more than 9 THEN
# SUM the digits of the doubled value
# ENDIF
# SUM the calculated value and the total
# ELSE
# SUM the current digit and the total
# ENDIF
# END loop
# IF total % 10 == 0 THEN
# SHOW Number is valid
# ELSE
# SHOW number is invalid
# ENDIF
creditCard = input("What is your creditcard?")
total = 0
for i in creditCard[-1]:
if i % 2 == 0:
i = i * 2
if i > 9:
i += i
total = total + i
else:
total = total + i
if total % 10 == 0:
print("Valid")
else:
print("Invalid")
well, i can see 2 problems:
1)when you do:
for i in creditCard[-1]
you dont iterate on the creditCard you simply take the last digit.
you probably meant to do
for i in creditCard[::-1]
this will iterate the digits from the last one to the first one
2)
the pseudocode said to double the number if its POSITION is even, not if the digit itself is even
so you can do this:
digit_count = len(creditCard)
for i in range(digit_count -1, -1, -1):
digit = creditCard[i]
or have a look at the enumerate built-in function
edit:
complete sample:
creditCard = input("What is your creditcard?")
total = 0
digit_count = len(creditCard)
for i in range(0, digit_count, -1):
digit = creditCard[i]
if i % 2 == 0:
digit = digit * 2
if digit > 9:
digit = digit / 10 + digit % 10 # also noticed you didnt sum the digits of the number
total = total + digit
if total % 10 == 0:
print("Valid")
else:
print("Invalid")
How do I display the number of one's in any given integer number?
I am very new to python so keep this in mind.
I need the user to input a whole number.
Then I want it to spit out how many one's are in the number they input.
i am using python 3.3.4
How would I be able to do this with this following code?
num = int(input ("Input a number containing more than 2 digits"))
count = 0
for i in range (0):
if num(i) == "1":
count = count + 1
print (count)
I don't know what i'm doing wrong
it gives me 'int' object is not callable error
Something like this:
Int is not iterable so you may need to convert into string:
>>> num = 1231112
>>> str(num).count('1')
4
>>>
str(num).count('1') works just fine, but if you're just learning python and want to code your own program to do it, I'd use something like this, but you're on the right track with the code you supplied:
count = 0
for i in str(num):
if i == "1":
count = count + 1 # or count += 1
print(count)
Just to help you, here is a function that will print out each digit right to left.
def count_ones(num):
while num:
print(num % 10) # last digit
num //= 10 # get rid of last digit
num = 1112111
answer = str(num).count("1")
num = int(input (" Input a number to have the number of ones be counted "))
count = 0
for i in str(num):
if i == "1":
count = count + 1 # or count += 1
print (' The number of ones you have is ' + str(count))
So i took the user input and added it to the correct answer since when i tried the answer from crclayton it didn't work. So this works for me.
I must create two functions. One that can tell whether one number is odd or even by returning t/f, and the other will call the first function then return how many even numbers there are.
This is my code so far:
Even = [0,2,4,6,8]
IsEvenInput = int(input("Please enter a number: "))
def IsEvenDigit(a):
if a in Even:
return True
else:
return False
y = IsEvenDigit(IsEvenInput)
print(y)
def CountEven(b):
count = 0
for a in b:
if IsEvenDigit(a):
count+=1
return count
d = input("Please enter more than one number: ")
y = CountEven(d)
print(y)
This keeps outputting 0 and doesn't actually count. What am I doing wrong now?
d = input("Please enter more than one number: ")
This is going to return a string of numbers, perhaps separated by spaces. You'll need to split() the string into the sequence of text digits and then turn those into integers.
There's a general approach to determining whether a number is odd or even using the modulus / remainder operator, %: if the remainder after division by 2 is 0 then the number is even.
Here is another approach:
def is_even(number):
return number % 2 == 0
def even_count(numbers_list):
count = 0
for number in numbers_list:
if is_even(number): count += 1
return count
raw_numbers = input("Please enter more than one number: ")
numbers_list = [int(i) for i in raw_numbers.split()]
count = even_count(numbers_list)
print(count)
This will take care of all other numbers too.
So by calling CountEvent(d) outside the scope of the function CountEven, you aren't using recursion, you're simple calling the function after it's been defined.
Try reducing the amount of code outside of your functions.
#Start by declaring your functions:
def isEven(n):
return n % 2 == 0
def countEven():
count = 0
string_of_numbers = input("Please enter numbers separated by spaces: ")
list_of_number_characters = string_of_numbers.split(' ')
for number in list_of_number_characters:
number_as_int = int(number)
if isEven(number_as_int) == True:
count = count + 1
print("There were " + str(count) + " even numbers found.")
countEven() #Call the function that runs your program
You are counting whether the integers - [0, 2, 4, 6, 8] etc. - are characters in a string - "0", "2", "4", "6", "8" etc. Currently, IsEvenDigit(a) will never be true, because a character in a string will not be in the list of even integers, so the code beneath the if statement will never be executed. You need IsEvenDigit(int(a)) in the CountEven function.
On another topic, a commenter to your post suggested reading PEP 8. Your code is actually formatted pretty well, its just in Python, CamelCase is used just for classes, and words_seperated_by_underscores is used for variables and function names.
Or if you want brevity and unreadability, some code:
main = lambda: sum(map(lambda x: int(x) % 2 == 0, (i for i in input("Enter a number: "))))
main()
It does define 2 (anonymous) functions!
A possible solution:
def is_even(n):
return not n % 2
def count_even(numbers)
return sum(map(is_even, numbers))
nums = input("Enter numbers separated by spaces: ")
nums = map(int, nums.split())
print(count_even(nums))