I am trying to make a program that will ask the user to input 25 integers.
This is where I'm at now:
while True:
numbers = list(map(int, input("Enter 25 numbers (seperate it with space): ").split()))
This should do the trick. It will prompt you with the question again if you do not enter the right amount of characters. Plus, it does not count spaces as characters.
gettingInput = True
while gettingInput:
numbers = list(map(int, input("Enter 25 numbers (seperate it with space): ").split()))
if len(numbers) - numbers.count(" ") > 25:
gettingInput = True
else:
gettingInput = False
# (- numbers.count(" ") will not count spaces as characters.)
Related
This question already has answers here:
Sum the digits of a number
(11 answers)
Closed last year.
Consider the following input prompt. I want to output the sum of digits that are inputted.
Example:
two_digit_number = input("Type a two digit number: ") 39
# program should print 12 (3 + 9) on the next line
If I input 39, I want to output 12 (3 + 9). How do I do this?
You can use sum(), transforming each digit to an integer:
num = input("Enter a two digit number: ")
print(sum(int(digit) for digit in num))
maybe like this:
numbers = list(input("Enter number: "))
print(sum(list(map(int, numbers))))
Read digits with input as a whole number of string type
split them with list() in characters in a list
use map() to convert type to int in a list
with sum() you're done.. just print()
Beware of invalid entries! "hundred" or "1 234 567"
you can achieve that like this:
a = input("Type a two digit number: ")
b = list(a)
print(int(b[0])+int(b[1]))
n = (int(input("Enter the two digit number\n")))
n = str(n)
p = int(n[0])+int(n[1])
print(p)
This is one of the many ways for it.
value = 39 # it is your input
value_string = str(value)
total = 0
for digit in value_string:
total += int(digit)
print(total)
new version according to need mentioned in comment:
value = 39
value_string = str(value)
total = 0
digit_list = []
for digit in value_string:
total += int(digit)
digit_list.append(digit)
print(" + ".join(digit_list))
print(total)
You can do that as follows:
two_digit_number = input("Type a two digit number: ")
digits = two_digit_number.split("+")
print("sum = ", int(digits[0])+int(digits[1]))
Explanation:
first read the input (ex: 1+1)
then use split() to separate the input statement into the strings of the input digits only
then use int() to cast the digit from string to int
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 have an assignment where we have to convert alphanumeric phone numbers into just numbers. For example "555-PLS-HELP" should convert into "555-757-4357". I wrote some of it but it keeps giving me incorrect output.
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
phone_number = str(input("Please enter a phone number: "))
counter = len(phone_number[:4])
total = phone_number[:4]
while counter > 0:
alpha = phone_number[-counter]
if alpha.isalpha():
total += num[alph.index(alpha)]
else:
total += alpha
counter -= 1
print(total)
I keep getting weird output.
For example:
Please enter a phone number: '555-PLS-HELP'
Gives:
555-4357
There are a few things to consider in your code:
Changing your first slice to counter = len(phone_number[4:]) produces a working solution: you'd like to iterate for the length of the rest of the number rather than the length of the area code prefix.
A simple for n in phone_number is preferable to taking len() and iterating using a counter variable and indexing from the rear with -counter, which is non-intuitive.
input() returns a str; there's no need for a superfluous cast.
This is a perfect situation for a dictionary data structure, which maps keys to values and is an explicit version of what you're already doing. Use zip to combine your strings into a dictionary.
In the list comprehension, each character is looked up in the keypad dictionary and its corresponding entry is returned. Using the dict.get(key, default) method, any items not present in the dictionary will be default.
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
keypad = dict(zip(alph, num))
phone_number = input("Please enter a phone number: ")
print("".join([keypad.get(x, x) for x in phone_number]))
Try it!
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
phone_number = str(input("Please enter a phone number: "))
counter = len(phone_number)
total = ''
while counter > 0:
alpha = phone_number[-counter]
if alpha.isalpha():
total += num[alph.index(alpha)]
else:
total += alpha
counter -= 1
print(total)
Test:
Please enter a phone number: '555-PLS-HELP'
Output:
555-757-4357
Try the following:
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
# converts the above lists into a dict
lookup = dict(zip(alph, num))
phone_number = input("Please enter a phone number: ")
result = ''
for c in phone_number:
# if needs changing
if c.isalpha():
result += lookup[c.upper()]
# simply append otherwise
else:
result += c
print(result)
Result:
Please enter a phone number: 555-PLS-HELP
Output:
555-757-4357
You could just iterate through the inputted number, check if it's alphabet and get the corresponding number if so, all in one-line:
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
phone_number = input("Please enter a phone number: ")
print(''.join([num[alph.index(x.upper())] if x.isalpha() else x for x in phone_number]))
Sample run:
Please enter a phone number: 555-PLS-HELP
555-757-4357
If it's an alphabet, this gets the index of the alphabet from alph and use that to look up in the num to get corresponding number. In the else case, just copies the number.
Why you are considering only last 4 characters of an a-priori unknown string? You could search first if phone_number has some alphabetic characters, and if it does, then starting from the first occurrence of such an alphabetic character you can replace it with the correct digit. This works for capital letters:
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
num = '22233344455566677778889999'
phone_number = raw_input("Please enter a phone number: ")
def fstAlpha(string):
for i in range(0,len(string)):
if string[i].isalpha():
return i
return -1
index = fstAlpha(phone_number);
if index != -1:
for i in range(index,len(phone_number)):
if(phone_number[i].isalpha()):
to_replace = phone_number[i]
replace_with = num[alph.index(to_replace)]
phone_number = phone_number.replace(to_replace,replace_with)
print phone_number
I'm trying to create a program that gets each digit of an inputted number into a list using a while loop. However, it only appends the last digit of the number to the list.
Code -
num = int(input("Enter a number: "))
numstr = str(num)
numlen = len(numstr)
x = 0
while x < numlen:
digits = []
a = numstr[x]
digits.append(a)
x = x + 1
print(digits)
So if I were to put in 372 as the number, the list would just simply be ['2'] with a length of 1.
Try this code:
digits = [i for i in str(num)]
You cannot do better than digits = list(str(num)). In fact, since input returns a string, even the conversion to a number is not necessary:
num = input("Enter a number: ")
digits = list(num)
(You still may want to ensure that what's typed is indeed a number, not a random string.)
For a python assignment I need to ask users to input numbers until they enter a negative number. So far I have:
print("Enter a negative number to end.")
number = input("Enter a number: ")
number = int(number)
import math
while number >= 0:
numberagain = input("Enter a number: ")
numberagain = int(numberagain)
while numberagain < 0:
break
how do I add up the number of times the user entered a value
i = 0
while True:
i += 1
n = input('Enter a number: ')
if n[1:].isdigit() and n[0] == '-':
break
print(i)
The str.isdigit() function is very useful for checking if an input is a number. This can prevent errors occurring from attempting to convert, say 'foo' into an int.
import itertools
print('Enter a negative number to end.')
for i in itertools.count():
text = input('Enter a number: ')
try:
n = int(text)
except ValueError:
continue
if n < 0:
print('Negative number {} entered after {} previous attempts'.format(n, i))
break
The solution above should be robust to weird inputs such as trailing whitespace and non-numeric stuff.
Here's a quick demo:
wim#wim-desktop:~$ python /tmp/spam.py
Enter a negative number to end.
Enter a number: 1
Enter a number: 2
Enter a number: foo123
Enter a number: i am a potato
Enter a number: -7
Negative number -7 entered after 4 previous attempts
wim#wim-desktop:~$