Multiplication in a variable - python

I am writing a piece of code that needs to multiply numbers by different values, all the code for the entering and validation of the 7 digit number works however the multiplication doesn't work. This is my code.
while True:
try:
num = int(input("enter a 7 digit number: "))
check = len(str(num))
if check == 7:
print("This code is valid")
break
else:
num = int(input("enter a number that is only 7 digits: "))
except ValueError:
print("you must enter an integer")
num = int(num)
def multiplication():
num[0]*3
num[1]*1
num[2]*3
num[3]*1
num[4]*3
num[5]*1
num[6]*3
return total
multiplication()
When I run it, I get the following error:
Traceback (most recent call last):
File "\\hpdl3802\stuhomefolders$\12waj066\Year 10\Computing\A453\Code\Test v2.py", line 29, in <module>
multiplication()
File "\\hpdl3802\stuhomefolders$\12waj066\Year 10\Computing\A453\Code\Test v2.py", line 20, in multiplication
num[0]*3
TypeError: 'int' object is not subscriptable
Any feedback is welcome

Of course, your code might be written in a number of ways, optimized (check #Kasravand answer, it's awesome) or not, but with a minimal effort this is what I get:
while True:
try:
num = input("enter a 7 digit number: ")
check = len(num)
int(num) # will trigger ValueError if not a number
if check == 7:
print("This code is valid")
break
else:
print("bad length, try again")
except ValueError:
print("you must enter an integer")
def multiplication(num):
total = int(num[0])*3
total += int(num[1])*1
total += int(num[2])*3
total += int(num[3])*1
total += int(num[4])*3
total += int(num[5])*1
total += int(num[6])*3
return total
print("Answer: ", multiplication(num))

If you're bound to use an integer instead of a list for the input, you can do one of the following:
You could access the individual digits using a combination of integer division and modulo, for example:
first_digit = num // 1000000 * 3
second_digit = num // 100000 % 10 * 1
# and so on
Or you could get the input as a string and access and convert the individual digits:
# [...]
num = input("enter a number that is only 7 digits: ")
# [...]
first_digit = int(num[0]) * 3
second_digit = int(num[1]) * 3

When you convert the input number to an integer you can not use indexing on that object since integers don't support indexing. If you want to multiply your digits by a specific number you better do this before converting to integer.
So first off replace the following part:
num = int(input("enter a number that is only 7 digits: "))
with:
num = input("enter a number that is only 7 digits: ")
The you can use repeat and chain functions from itertools module in order to create your repeated numbers, then use a list comprehension to calculate the multiplication:
>>> from itertools import repeat, chain
>>> N = 7
>>> li = list(chain.from_iterable(repeat([3, 1], N/2 + 1)))
>>> num = '1290286'
>>> [i * j for i, j in zip(map(int, num), li)]
[3, 2, 27, 0, 6, 8, 18]

This code will works:
while True:
try:
num = int(input("enter a 7 digit number: "))
except ValueError:
print("you must enter an integer")
else:
if len(str(num)) != 7:
print("enter a number that is only 7 digits")
else:
break
num = str(num)
def multiplication():
total = 0
for i,m in enumerate([3,1,3,1,3,1,3]):
total += int(num[i])*m # transform the index of text into a integer
return total
print(multiplication())

This should help
num = ''
check = 0
while True:
try:
num = raw_input("enter a 7 digit number: ")
check = len(num)
if check == 7:
print("This code is valid")
break
else:
print "enter a number that is only 7 digits"
except ValueError:
print("you must enter an integer")
def multiplication():
total = 0
for i in range(check):
if i % 2 == 0:
total += int(num[i]) * 3
else:
total += int(num[i]) * 1
print total
multiplication()

Related

How to loop a function def in python until I write the number 0

I'm trying to do a def function and have it add the digits of any number entered and stop when I type the number "0", for example:
Enter the number: 25
Sum of digits: 7
Enter the number: 38
Sum of digits: 11
Enter the number: 0
loop finished
I have created the code for the sum of digits of the entered number, but when the program finishes adding, the cycle is over, but what I am looking for is to ask again for another number until finally when I enter the number "0" the cycle ends :(
This is my code:
def sum_dig():
s=0
num = int(input("Enter a number: "))
while num != 0 and num>0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
if num>0:
return num
sum_dig()
Use list() to break the input number (as a string) into a list of digits, and sum them using a list comprehension. Use while True to make an infinite loop, and exit it using return. Print the sum of digits using f-strings or formatted string literals:
def sum_dig():
while True:
num = input("Enter a number: ")
if int(num) <= 0:
return
s = sum([int(d) for d in list(num)])
print(f'The sum of the digits is: {s}')
sum_dig()
In order to get continuous input, you can use while True and add your condition of break which is if num == 0 in this case.
def sum_dig():
while True:
s = 0
num = int(input("Enter a number: "))
# Break condition
if num == 0:
print('loop finished')
break
while num > 0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
sum_dig()
A better approach would be to have sum_dig take in the number for which you want to sum the digits as a parameter, and then have a while loop that takes care of getting the user input, converting it to a number, and calling the sum_digit function.
def sum_dig(num): # takes in the number as a parameter (assumed to be non-zero)
s=0
while num > 0: # equivalent to num != 0 and num > 0
r = num % 10
s = s + r
num = num // 10
return s
while True:
num = int(input("Enter a number: "))
if num == 0:
break
print("The sum of the digits is: " + sum_dig(num))
This enables your code to adhere to the Single-Responsibility Principle, wherein each unit of code has a single responsibility. Here, the function is responsible for taking an input number and returning the sum of its digits (as indicated by its name), and the loop is responsible for continuously reading in user input, casting it, checking that it is not the exit value (0), and then calling the processing function on the input and printing its output.
Rustam Garayev's answer surely solves the problem but as an alternative (since I thought that you were also trying to create it in a recursive way), consider this very similar (recursive) version:
def sum_dig():
s=0
num = int(input("Enter a number: "))
if not num: # == 0
return num
while num>0:
r= num %10
s= s+r
num= num//10
print("The sum of the digits is:",s)
sum_dig()

Checksum of seven-digit number input through keyboard

I am trying to get the checksum of a seven-digit number input through the keyboard. The input would be restricted to exactly 7 digits. I already have this code below but can't get to restrict it to only 7 digits.
n = int(input("Enter number"))
total = 0
while n > 0:
newNum = n % 10
total = total + newNum
n = n // 10
print(total)
If I enter 4 digits, the code will still run. I just want to restrict it to only 7 digits.
Instead of instantly converting the input to an integer, keep it as a string, so you can make a condition for the length of the input.
something like:
n = input("Enter number ")
m = int(n)
total = 0
while m > 0 and len(n)==7:
newNum = m%10
total = total + newNum
m = m//10
print(total)
You could keep the input number as a string, so that you have an easy way to count and sum over the digits:
s = ''
while len(s) != 7:
s = input("Enter a 7-digit number")
total = sum(int(char) for char in s)
print(total)
num = str(input("Enter a seven-digit number: "))
if len(num) !=7:
print("Please Enter a seven-digit number!")
else:
sumNum = 0
m = int(num)
while m>0:
newnum = m%10
sumNum = sumNum + newnum
m = m//10
print("The sum of its digits is: ",sumNum)
Check the length of the input before turning it into a int.
Since strings can be iterated over, like list, their length can be checked in the same way as lists with the len() function. as so:
if len(n) != 7:
print("input must be seven digits long")
n = input("Enter number")

How to check if input number is unique [Python]

I want to check if the user's 3-digit number input has no repeat digits (eg. 122, 221, 212, 555).
num = 0
while True:
try:
num = int(input("Enter a 3-Digit number: "))
if (num % 10) == 2:
print("ensure all digits are different")
This somewhat works, tells me that the numbers 122 or 212 are have repeats, but not for 221, or any other 3-digit number
num = input()
if len(set(num)) != len(num):
print("The number has repeat digits!")
else:
print("No repeat digits")
A %b gives the remainder if a is divided by b. Rather than doing this just take the number as string and check if any of the two characters present in the string are same.
num = 0
while True:
try:
num = (input("Enter a 3-Digit number: "))
if (num[0] == num[1] or num[1]==num[2] or num[2]==num[0])
print("ensure all digits are different")
You can also make use of a dictionary to check whether digits are repeated or not.
Take the remainder as you did in your code (taking mod 10)and add that remainder into the dictionary.
Everytime we take the remainder, we check inside the dictionary whether the number is present or not because if the number is present inside the dictionary, then it is not unique.
Code :
num = int(input())
dictionary = {}
while num > 0:
remainder = num % 10
if remainder in dictionary.keys():
print("Not unique")
break
else:
dictionary[remainder] = True
num = num // 10

Automate The Boring Stuff With Python - Collatz Sequence

I'm very new to any sort of coding, currently using python 3.3. I've managed to run the Collatz Sequence accurately in python with the following:
while True: # The main game loop.
number = int(input('Enter number:\n'))
def collatz(number):
while number !=1:
if number % 2==0: #even numbers
number=number//2
print(number)
elif number % 2!=0: #odd numbers
number=number*3+1
print(number)
collatz(number)
However, I'm unsure of how and where to add a ValueError strong, for when the user enters a non-integer, something like the following:
except ValueError:
print('Only integers accepted.')
I'm very new to python, so if any answers could have a little explanation I'd be very appreciative. Thanks
Put it at the very very top. Parameter constraints should always happen as soon as possible, so that you don't waste time running code you're just going to error out of.
def progress(percentage):
if percentage < 0 or percentage > 100:
raise ValueError
# logic
I assumed that you're referring to Exception Handling, Validation part must be done in the beginning.
while True: # The main game loop.
try:
number = int(input('Enter number:\n'))
except ValueError:
print("Only integers accepted! Please try again ...")
else:
collatz(number)
#output:
#
#Enter number:
#abc
#Only integers accepted! Please try again ...
#Enter number:
#5
#16
#8
#4
#2
#1
#Enter number:
But program will continue looping, termination conditions needed.
number = None
while number != int():
try:
number = int(input("Enter number: "))
break
except:
print("Enter a valid Number")
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
else:
number = (3 * number + 1)
print(number)
collatz(number)
def collatz():
try:
number = int(input("Enter number: "))
while True:
if number == 1 or number == 0:
break
elif number % 2 == 0:
number = number // 2
print(number)
elif number % 2 == 1:
number = 3 * number + 1
print(number)
except:
print("Enter in a valid number")
collatz()
Try this:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
else:
print(3 * number + 1)
return 3 * number + 1
while True:
try:
number = int(input("Enter a Number or type 0 to exit: "))
if number == 0:
break
while True:
if number != 1:
number = collatz(number)
else:
break
except ValueError:
print("Enter an integer number")

how to connect user input and lists

in my program, I am taking user input (integers 1-9) and having the user keep typing in numbers until they type 0 to exit. once they type 0 I want to print the sum of the integers and then exit. Im new to python so any help would be appreciated. Im getting an invalid syntax error when using the > and < symbol not sure why.
def createList():
myList=[]
return myList
def fillList(myList):
for number in myList:
if number >=1 and <= 9:
number=int(input(" enter a number 1-9, and 0 to quit"))
myList.append(number)
return myList
def printList(myList):
for number in myList:
print ( " the sum is" ,sum(myList))
print(number)
if number ==0:
exit()
def main():
myList = createList()
fillList(myList)
printList(myList)
main()
You're only missing a word, try this:
if number >=1 and number <= 9:
So close!
_sum = 0
looping = True
while looping:
num = input("Enter a number (1-9) or 0 to exit.")
if num.isdigit() and 0 <= int(num) <= 9:
_sum += num
if num is 0:
looping = False
print("Sum is", _sum)
if number >=1 and number <= 9:
You need to place the variable on both sides of the and since they are two separate conditions.
Also, since you're initially creating an empty list, you will never get to the part where you get user input. To fix this you should use a while loop.
while number != 0:
The full program might look like this:
def createList():
myList=[]
return myList
def fillList(myList):
number = 5
while number != 0:
if number >=1 and number <= 9:
number=eval(input(" enter a number 1-9, and 0 to quit"))
myList.append(number)
return myList
def printList(myList):
for number in myList:
print ( " the sum is" ,sum(myList))
print(number)
if number ==0:
exit()
def main():
myList = createList()
fillList(myList)
printList(myList)
main()

Categories

Resources