can any one offer any assistance, as to why the following code always returns the same check digit number?
def ISBN():
numlist = []
request = raw_input("Please enter the 10 digit number: ")
if len(request) == 10:
listofnums = [int(digit) for digit in '1234567890']
multipliers = reversed(range(2,12))
multipliednums = [a*b for a,b in zip(listofnums, multipliers)]
print multipliednums
added_result = sum(multipliednums)
print added_result
remainder = added_result % 11
print remainder
check_digit = 11 - remainder
print check_digit
ISBN()
if len(request) != 10:
print "Invalid Input"
ISBN()
ISBN()
any information or tips on how i could imptove the code, or just why it constantly eturns the same digit(9) no matter what the input.
Thank you
I think for digit in '1234567890' should be for digit in request.
Looking at your code, you can see that you accept the value of request from the user, but after checking its length, you don't do anything else with it again. There's no way the output of this program could change.
You do not seem to be calculating anything on the variable that you ask from the user.
Variable request is not used in the subsequent code...
Related
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 need to create a program that will convert Base 10 numbers in Base 2.
Next is the code, it can not run as expected even if it has no error:
E = input('Please enter a number')
Eint= int(E)
for N in range(100,0):
while 2**N > Eint:
N = N-1
print(0)
if B**N <= Eint:
Eint = Eint - 2**N
print(1)
Print('finished')
When I'm running it it will ask me the number but that's all, thank you for your help guys.
From a quick inspection, range(100,0), B, and Print() are three culprits here! If you want to pass through numbers from 0 to 99, then range(100) is what you need. Now, what is B? Print should be written in lower case: print.
After we fix these syntax errors, let us try to revisit the program and understand what it is supposed to do. Have fun :-)
EDIT to fix the code in the question:
E = input('Please enter a number: ')
Eint = int(E)
for N in range(8,-1,-1):
if 2**N > Eint:
print(0, end='')
else:
Eint = Eint - 2**N
print(1, end='')
print()
print('finished')
Please note that Python is a language that uses indentations to denote code blocks. This code will convert a decimal to binary. Now, note that the range start of 8 gives you a hint about the upper bound of the number that the code can translate. Therefore, an if condition must be added after the second statement to ensure we are not attempting to convert a number that is too large. Enjoy!
If it helps check my solution too. Because I guess you don't want to see the result on separate lines, so I create a list for you to see the result in one line.
E = int(input('Please enter a number\n'))
Eint = E
base_two=[]
while E > 0:
a = int(float(E%2))
base_two.append(a)
E = (E-a)/2
base_two.append(0)
string = ""
for j in base_two[::-1]:
string = string+str(j)
print("Binary for", Eint, "is", string)
print('finished')
I was late a little bit :)
So I basically wanna compare "Number" and "Guess" in the if statement, but no matter what it says they don't match (I get the else response, not included here). Even if I copy the random number they don't match.
Thanks in advance!
import time
def the_start():
points = 0
attempt = 1
print("Attempt:",attempt)
print("Your goal is to guess a number between 1 and 10 - Points:",points)
time.sleep(2)
attempt = attempt + 1
number = random.randint(0,10)
print(number)
guess = input("What is your guess? :")
time.sleep(2)
if guess == number:
points = points + 1
print("OMG YOU WERE RIGHT! Here, have some fake cheers! *cheer*")
time.sleep(5)
guess is a string. You need to do conversion of the string and handle error conditions. int() will convert a string to an integer, but it will throw an exception if the string is not purely numbers.
import random
print "Welcome to the number guesser program. We will pick a number between 1 and 100 and then ask you to pick a number between 1 and 100. If your number is 10 integers away from the number, you win!"
rand_num = random.randint(1, 100)
user_input = raw_input('Put in your guess:').isdigit()
number = int(user_input)
print number
if abs(rand_num - number) <= 10:
print "Winner"
else:
print "Loser"
Whenever I try to run this code, the computer always generates the number 1. And if I put in a number that is 10 (or less) integers away from one it will still display the else statement. I will have my gratitude to whoever can solve my predicament. I am new to python try to keep your answers simple please.
raw_input returns a string you entered as input. isdigit() checks whether a string is a digit or not and returns True or False.
In your code you're assigning the return value of isdigit to user_input So, you get either True or False. Then you convert it to a number, thus getting either one or zero. This is not what you want.
Let user_input be just a result of raw_input. Then check whether it is a valid number with user_input.isdigit(). If it's not a number, print an error message and exit (or re-ask for input), else convert user_input to an integer and go on.
The problem is product by this sentenc:
user_input = raw_input('Put in your guess:').isdigit().
The return value of isdigit() is True or False. When you enter 1 or any digit number, it will return True(True=1,False=0), so you will always get 1, if you enter digit. You can change like this:
import random
print "Welcome to the number guesser program.
We will pick a number between
1 and 100 and then ask you to pick a number
between 1 and 100. If your number is 10 integers
away from the number, you win!"
rand_num = random.randint(1, 100)
user_input= raw_input('Put in your guess:')
is_digit = user_input.isdigit()
if is_digit==True:
number = int(user_input)
print number
if abs(rand_num - number) <= 10:
print "Winner"
else:
print "Loser"
else:
print 'Your input is not a digit.'
Look at this line:
user_input = raw_input('Put in your guess:').isdigit()
The function raw_input gives you user input, but then you call isdigit and as consequence in your variable user_input you get result of isdigit. So, it has boolean value.
Then in
number = int(user_input) you cast it to integer type. In python true is 1 and false is 0. That's why you always get 1.
I'm trying to calculate the check digit for an ISBN input on python. so far I have...
def ISBN():
numlist = []
request = raw_input("Please enter the 10 digit number: ")
if len(request) == 10:
**numlist == request
print numlist**
if len(request) != 10:
print "Invalid Input"
ISBN()
ISBN()
The bold bit is where im having trouble, I cant seem to split the 10 digit input into individual numbers in the list (numlist) and then multiply the seperated individual numbers by 11 then the next by 10 then the next by 9 etc...
For the next part of the program, I will need to add these new multiplied numbers in the list together, then i will use the mod(%) function to get the remainder then subtract the number from 11, any assistance with any of my coding or incorrect statements on how to calculate the ISBN would be greatly appreciated.
Thank you.
This code should get you on your way:
listofnums = [int(digit) for digit in '1234567890']
multipliers = reversed(range(2,12))
multipliednums = [a*b for a,b in zip(listofnums, multipliers)]
Strings are iterable, so if you iterate them, each element is returned as a single-character string.
int builds an int from a (valid) string.
The notation [a*b for a,b in zip(listofnums, multipliers)] is a list comprehension, a convenient syntax for mapping sequences to new lists.
As to the rest, explore them in your repl. Note that reversed returns a generator: if you want to see what is "in" it, you will need to use tuple or list to force its evaluation. This can be dangerous for infinite generators, for obvious reasons.
I believe list() is what you are looking for.
numlist=list(request)
Here is how I would write the code. I hope I'm interpreting the code correctly.
def ISBN():
request = raw_input("Please enter the 10 digit number: ")
if len(request) == 10:
numlist = list(request)
print numlist
else:
print "Invalid Input"
ISBN()
import itertools
if sum(x * int(d) for x, d in zip(nums, itertools.count(10, -1))) % 11 != 0:
print "no good"