im new at this and i was trying to calculate the total of the given numbers, if one of those numbers were a odd number, it wouldn't add up to the total amount, that is b
what i was doing is, if a / 2 has no split rest it would be evens, then it would add to b, but im getting a ZeroDivisionError, what am i doing wrong?
sorry if i misspelled any word
for c in range(1, 7):
a = int(input("type a number {}: ".format(c)))
if a / 2 % 0:
b += a
print("the sum of the numbers is equivalent to:", b)
if you are checking for even number than it should be :
if a % 2 == 0:
I think you want to sum the even numbers entered by the user. In that case, a % 2 returns 0 for even and 1 for odd positive whole numbers.
Please consider using meaningful variable names, like 'even_sum' instead of 'b'.
Consider commenting your code with what you expect a line or code block to do.
The corrected code is as follows.
# initialize b, which will hold the sum of the even numbers
# entered by the user.
b = 0
# prompt the user for a number 6 times.
for c in range(1, 7):
# request a number
a = int(input("type a number {}: ".format(c)))
# if the number is even
if a % 2 == 0:
# the number is even, so add it to the running total, b
b += a
print("The sum of the EVEN numbers is equivalent to:", b)
Related
The output shows a different result. Yes, the factorials of those numbers are right but the numbers outputted aren't right.
Here's the code:
input:
n = int(input("Enter a number: "))
s = 0
fact = 1
a = 1
for i in range(len(str(n))):
r = n % 10
s += r
n //= 10
while a <= s:
fact *= a
a += 1
print('The factorial of', s, 'is', fact)
Output:
Enter a number: 123
The factorial of 3 is 6
The factorial of 5 is 120
The factorial of 6 is 720
You're confusing yourself by doing it all in one logic block. The logic for finding a factorial is easy, as is the logic for parsing through strings character by character. However, it is easy to get lost in trying to keep the program "simple," as you have.
Programming is taking your problem, designing a solution, breaking that solution down into as many simple, repeatable individual logic steps as possible, and then telling the computer how to do every simple step you need, and what order they need to be done in to accomplish your goal.
Your program has 3 functions.
The first is taking in input data.
input("Give number. Now.")
The second is finding individual numbers in that input.
for character in input("Give number. Now."):
try:
int(character)
except:
pass
The third is calculating factorials for the number from step 2. I won't give an example of this.
Here is a working program, that is, in my opinion, much more readable and easier to look at than yours and others here. Edit: it also prevents a non numerical character from halting execution, as well as using only basic Python logic.
def factorialize(int_in):
int_out = int_in
int_multiplier = int_in - 1
while int_multiplier >= 1:
int_out = int_out * int_multiplier
int_multiplier -= 1
return int_out
def factorialize_multinumber_string(str_in):
for value in str_in:
print(value)
try:
print("The factorial of {} is {}".format(value, factorialize(int(value))))
except:
pass
factorialize_multinumber_string(input("Please enter a series of single digits."))
You can use map function to get every single digit from number:
n = int(input("Enter a number: "))
digits = map(int, str(n))
for i in digits:
fact = 1
a = 1
while a <= i:
fact *= a
a += 1
print('The factorial of', i, 'is', fact)
Ok, apart from the fact that you print the wrong variable, there's a bigger error. You are assuming that your digits are ever increasing, like in 123. Try your code with 321... (this is true of Karol's answer as well). And you need to handle digit zero, too
What you need is to restart the calculation of the factorial from scratch for every digit. For example:
n = '2063'
for ch in reversed(n):
x = int(ch)
if x == 0:
print(f'fact of {x} is 1')
else:
fact = 1
for k in range(2,x+1):
fact *= k
print(f'fact of {x} is {fact}')
Hey so im pretty new to programming in general and I was having a crack at a question I found for the collatz function,
The code I wrote after some trial and error is as follows:
def collatz(number):
if number % 2 == 0:
number = number//2
print(number)
return number
elif number%2 != 0:
number = 3*number + 1
print(number)
return number
n = int(input("plz enter the number:"))
while n != 1:
n = collatz(n)
Output:
plz enter the number:3
10
5
16
8
4
2
1
This code works but im not sure how the variable values are being alloted, cuz after running this program I can see that in the shell "number = 3" but "n = 1", why is this the case? Shouldnt "number" also equal to 1? Because I am returning the value of number within the function?
Also just to clear my concepts, at the initial moment when I input n = 3, at that moment n = number = 3, then does this returned value of "number" automatically become the new value of n, when i call it in the while loop?
Just wanted to check cuz im a little weak when it comes to doing stuff that needs to pass parameters.
edit:
Why is this case diff then what was just answered?
def testfile(number):
number = number -1
print(number)
return number
n = int(input("enter:"))
while n != 2:
n = testfile(n)
Output:
enter:5
4
3
2
When the input is given as n = 5, then why does number = 3 instead of 5 as was just explained below?
Here's how your program works.
You ask for a number and store it in variable n.
You open a loop which continues until n is 1
Every time the loop repeats, you're calling your function and passing a COPY of n. If you add one to the copy inside the function, your original n will not change.
The COPY is called number. You perform your little tricks with number, output it to the screen, and here's the confusing part: you return a copy of number right back to your loop. And where does it go? It goes right back to n. This overwrites whatever was in n previously.
I am not getting any output from interpreter after I input a value.
Here's my code:
number = int(input("Enter the number to test:"))
count = 0
if number % 2 == 0:
while number > 1:
number /= 2
count += 1
else:
while number > 1:
number = (3 * number) + 1
count += 1
print("Iteration count: " + count)
Expected output is 15 for input = 11
Edit: The Collatz Conjecture (above) use the following algorithm: If n is even, divide it by 2, else multiply by 3 and add 1. Start over until you get 1.
You have created an infinite loop in your while statements. A good way you can check this yourself is to print number inside the while loop, and you will quickly see where you are going wrong.
I don't want to give away the solution as this sounds too much like homework - but you must ensure your while loop condition is met, or it will never exit.
I'm very much new to programming.
I implemented Credit card validation program according to following instructions.
Let the input be input.
Reverse input.
Multiply all odd positions (i.e. indexes 1, 3, 5, etc.) of input by 2.
If any of these multiplied entries is greater than 9, subtract 9.
Sum all of the entries of input, store as sum.
If sum (mod 10) is equal to 0, the credit card number is valid.
code
# credit card validation - Luhn Formula
card_number = list(reversed(input("enter card number: ")))
status = False
temp1 = []
temp2 = []
sum = 0
for i in card_number:
if card_number.index(i) % 2 != 0:
temp1.append(int(i) * 2)
else:
temp1.append(int(i))
for e in temp1:
if e > 9:
temp2.append(e - 9)
else:
temp2.append(e)
for f in temp2:
sum += f
if sum % 10 == 0:
status = True
print("card is VALID")
else:
print("card is INVALID")
code sometimes works and sometimes not. is there a problem with my code.
valid number 49927398716 - works
valid number 4916092180934319 - not working
please don't link to this - Implementation of Luhn Formula
I don't need another implementation. If possible please tell me what's wrong with my code. So I can correct it.
Thank you
Your problem is here:
if card_number.index(i) % 2 != 0:
This looks for a specific digit in the number, but if the digit is repeated, you will get the position of the first occurrence. If both (or all, or no) occurrences are in odd positions, your code will work. But if one is in an even position and another not, then your odd/even test will produce the wrong answer. Do the odd/even position check this way:
for n,i in enumerate(card_number):
if n % 2 != 0:
temp1.append(int(i) * 2)
else:
temp1.append(int(i))
I'm working on a problem that involves putting in an input, integer n, that when doing so will print off the following 4 "multiples" of the integer. I need to do this for 3 integers, n = 5, n = 0, n = 3.
Original Question:
Implement a program that requests a positive
integer n from the user and prints the first four multiples of n: Test
your module for n = 5; n = 0 and n = 3.
The output of the code should look like:
>>>
Enter n: 5
5
10
15
20
So, what I've come up with so far is this
n = (input("Enter n:"))
This allows me to input an integer value.
Next using print(n), this will print the value I input (Ex. number 5), but I'm not sure how to print off multiples of it after. I realize it's a loop question, most likely involving if or in, but I'm not sure where to go after this.
You've pretty much figured out the question on your own. The correct code is:
n = int(input("Enter n:"))
for i in range(4):
print(n*(i+1))
So, what this for loop does for you is repeat your print statement 4 times, where you give i the values of the expression range(4).
If you just print(range(4)), you'll see that it evaluates to [0,1,2,3]. That's why I had to add 1 to it each time.
The int() function call is needed because input() returns a string, not a number. So if we want the mathematical operators to do what we expect, we need to first convert it to a number (in this case, an integer).
This is the general logic:
n = (input("enter n:"))
for(int i = 1; i <= 4; i++){
print(int(float((n))*i);
}
if you want the list to start with 0 you can do this, it has an error but it can be fixed...
number = int(input("Give a number:"))
for multiples in range(10):
getal1 = number * multiples
print("\t The", str(multiples + 1) + "e multiple of," + number, "is", str(getal1) + ".")