How would I change this in order to count the number of sevens in a positive integer.
num = int(input("Enter a positive integer: "))
while num >= 1:
digit = num % 10
num = num//10
print(digit)
Using your code as a basis, just declare a variable to count the sevens, and increment it when the current digit is a seven:
sevens = 0
while num >= 1:
digit = num % 10
if digit == 7:
sevens += 1
num = num // 10
print(sevens)
Of course, there are more pythonic ways to do this:
num = input('Enter a positive integer: ')
print(num.count('7'))
You could convert it to a string, then use the count function.
num = int(input("Enter a positive integer: "))
print(str(num).count('7'))
Related
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")
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
In the below code, if the input is even, the number doubles, if not 1 is added. This goes on until the number is greater than 100.
number=int(input("Enter a number: "))
print(number)
while number < 100:
if number % 2 == 0:
number *= 2
else:
number = number+1
print(number)
Once it has reached 100, I want it to repeat the same process for input+1. I can't use number=number+1 because it would use the last version of number rather than the original input.
Thank you for any help!
You can use two loops with to copies of number, for instance:
number=int(input("Enter a number: "))
print(number)
while number < 100:
num = number
while num < 100:
if num % 2 == 0:
num *= 2
else:
num += 1
print(num)
number += 1
I have to write a program that tells the user the factorial of any integer between 1 and 15 while using the while loop. I wrote the code below and the output gives me endless factorials/numbers.. Do you know what I did wrong? Thank you!
Update: I realized that I should use "while" for what num isn't, so I now have this code below, but it still says invalid syntax for the second "while".
# take input from the user
num = int(input("Please enter a number from 1 to 15: "))
factorial = 1
# check if the number is negative, positive or zero
while num < 0:
num = int(input("Negative numbers don't have factorials! Please enter a number between 1 and 15: ")
while num > 15:
num = int(input("Please enter a number between 1 and 15! ")
if num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
I would do this:
from math import factorial as factorial
while True:
num = int(input("Please enter a number from 1 to 15: "))
if 1 <= num <= 15:
fact = factorial(num)
print 'the factorial of {n} is {f}'.format(n=num, f=fact)
else:
num = int(input("Please enter a number from 1 to 15: "))
You missed a closing parenthesis:
while num > 15:
num = int(input("Please enter a number between 1 and 15! "))
^ here
you have missed the braces at the end of int() funtion
# take input from the user
num = int(input("Please enter a number from 1 to 15: "))
factorial = 1
# check if the number is negative, positive or zero
while num < 0:
num = int(input("Negative numbers don't have factorials! Please enter a number between 1 and 15: ")) # brace was missing
while num > 15:
num = int(input("Please enter a number between 1 and 15! ")) # brace was missing
if num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
You might have meant like the below in order to loop until you get correct input:
# take input from the user
num = int(input("Please enter a number from 1 to 15: "))
factorial = 1
while(True):
if num < 0:
num = int(input("Negative numbers don't have factorials! Please enter a number between 1 and 15: ")) # brace was missing
continue
if num > 15:
num = int(input("Please enter a number between 1 and 15! ")) # brace was missing
continue
if num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
break
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()