I am currently using Python to create a program that accepts user input for a two digit number and will output the numbers on a single line.
For Example:
My program will get a number from the user, lets just use 27
I want my program to be able to print "The first digit is 2" and "The second digit is 7"
I know I will have to use modules (%) but I am new to this and a little confused!
Try this:
val = raw_input("Type your number please: ")
for i, x in enumerate(val, 1):
print "#{0} digit is {1}".format(i, x)
It was not clear from your question whether you are looking to use % for string substitution, or % for remainder.
For completeness, the mathsy way using modulus operator on ints would look like this:
>>> val = None
>>> while val is None:
... try:
... val = int(raw_input("Type your number please: "))
... except ValueError:
... pass
...
Type your number please: potato
Type your number please: 27
>>> print 'The first digit is {}'.format(val // 10)
The first digit is 2
>>> print 'The second digit is {}'.format(val % 10)
The second digit is 7
Think about the two digit number as though it were a string. It is easier to grab each digit this way. Using str() will change the integer to a string. Modulos allow you to place these strings into your text.
Assuming the user inputs 27 into the variable called num, the code is:
print 'The first digit is %s and the second digit is %s' % (str(num)[0], str(num)[1])
Another way of coding Python:
val = raw_input("Type your number please: ")
for i in list(val):
print i
Note: val is read as string. For integer manipulation, use list(str(integer-value)) instead
two_digit_number = input("Type a two digit number: ")
print("The first digit is " + two_digit_number[0] + " The second digit is " +
two_digit_number[1])
You don't need modules to solve this question.
Related
i am asking the user to input a number as well as if they think their number plus a random integer will be odd or even in the same line but cant get it to work.
I wrote
user, num = input('Enter a number 1-10: ' and '\n odd or even?').split()
Only the 2nd string is asked (odd or even?) when i run the program.
i want it to be formatted as
Enter a number 1-10: \n
odd or even?
How do I take two different types of inputs using one line of code. i want the input from
'Enter a number: '
to be an int and i want the input from
'odd or even' to be a str
Well, you can simply use two lines of input. something like this:
num = int(input('Enter your number: '))
state = input('Odd or Even?')
Remove and it will work
>>> user, num = input('Enter a number 1-10: odd or even? ').split()
Enter a number 1-10: odd or even?10 3
>>> user
'10'
>>> num
'3'
>>>
input() outputs strings. You may have to convert it to int using int(num).
try this line:
user, num = input('Enter a number 1-10:' + '\nodd or even?\n').split()
how would i allow a user to input a 3-digit number, and then output the individual digits in the number in python
e.g. If the user enters 465, the output should be “The digits are 4 6 5”
sorry if this sounds basic
You use for your number num:
num % 10 to extract the last digit.
num = num // 10 to remove the final digit (this exploits floored division).
Finally, you want to get out the leading digit first. Therefore you adopt a recursive function to perform the above (which calls itself prior to printing the digit).
The solution using str.isdigit and re.sub functions:
import re
num = input('Enter number:')
if num.isdigit():
num_sequense = re.sub(r'(\d)(?=\d)', r'\1 ', num)
print("The digits are:", num_sequense)
else:
print("There should be only digits", num)
The output for the input 123:
The digits are: 1 2 3
The output for the input a1s2d3:
There should be only digits a1s2d3
Hard to make in one line, anyway this should do exactly what you want:
inp = list(input())
print("The digits are ", end ='')
for i in inp:
print(i, end=' ')
If you don't care for formatting, one-liner is possible:
print("The digits are ",list(input()))
Ok, so I've got a couple issues with a program (for school again) that I'm using to add up all the digits of a number. I've got some of the program down, except 2 things. First, how to use a variable (thelength below) in replacement of a number to call a specific digit of the input (I'm not sure if this is even possible, but it would be helpful). And second, how to add up different numbers in a string. Any ideas?
Here's what I have so far:
number = str(int(input("Please type a number to add up: ")))
length = len(number)
thelength = 0
total = 0
thenumbers = []
while thelength < length:
#The issue is me trying to use thelength in the next two lines, and the fact that number is now a string
total += number[thelength]
thenumbers.append(number[thelength])
thelength += 1
for num in thenumbers:
print(num[0])
print("+")
print("___")
print(total)
Thanks for any help I can get!
I don't know what "call a specific digit of the input" means, but the error in your code is here:
total += number[thelength]
total is an int, and you're trying to add a string to it, convert the digit to an integer first.
total += int(number[thelength])
Result:
1
2
3
+
___
6
import re
import sys
INPUT_VALIDATOR = re.compile("^[0-9]+$")
input_str = input("Please type a natural number to add up: ")
if INPUT_VALIDATOR.match(input_str) is None:
print ("Your input was not a natural number (a positive whole number greater or equal to zero)!")
print ("This displeases me, goodbye puny human.")
sys.exit(1)
total = 0
for digit_str in input_str:
print(digit_str)
total += int(digit_str)
print("+")
print("___")
print(total)
If you don't need to print the digits as you go, it's even easier:
# (Add the same code as above to get and validate the input string)
print(sum(int(digit_str) for digit_str in input_str))
number = int(input("Please type a number to add up: "))
total = 0
while number > 0:
total += number % 10
total /= 10
print(total)
num % 10 pretty much gets the last digit of a number
then we divide it by 10 to truncate the number by its last digit
we can loop through the number as long as it's above 0 and take the digital sum by using the method outlined above
Every thing that you need is convert the digits to int and sum them :
>>> s='1247'
>>> sum(map(int,s))
14
But as you get the number from input it could cause a ValueErorr , for refuse that you can use a try-except :
try :
print sum(map(int,s))
except ValueErorr :
print 'please write a valin number :'
Also if you are using python 2 use raw_input for get the number or if you are using python 3 just use input because the result of both is string !
So I am writting a program that inputs a 3 # digit and breaks it apart. I am having trouble figuring out how to then add the separate digits altogether?
For example: The user inputs 345
My program will break the #'s apart to 3,4,5 but how do I then add those numbers together?
this is my code thus far,
#set variable
val = raw_input("Type your three digit number please: ")
print 'The first digit is {}'.format(val[0])
print 'The second digit is {}'.format(val[1])
print 'The third digit is {}'.format(val[2])
#set variable
total = [val[0] +val [1] + val[2]]
total_value = total
print 'The sum of the three digits is' total_value
A short way to add all of the number's digits together is:
In [3]: sum(map(int, val))
Out[3]: 12
Here, map(int, val) iterates over the characters of val and converts each of them into an int, and sum(...) adds together all those ints.
The nice thing about this approach is that it works for any number of digits.
The reason your original code doesn't work is that val[0] etc are strings, so using + simply concatenates those strings back together. To add the numeric values, you would have to convert the characters to int first:
In [5]: int(val[0]) + int(val[1]) + int(val[2])
Out[5]: 12
You have to convert the individual components to numbers to be able to add them:
total = int(val[0]) + int(val[1]) + int(val[2])
Or, more concise:
total = sum(int(x) for x in val)
An elegant solution is to use python's builtin functions map and sum:
val = raw_input("Type your three digit number please: ")
total = sum(map(int, val))
print 'The sum of the three digits is', total
You just have to do this :
total = int(val[0]) + int(val[1]) + int(val[2])
Since the digits in val are characters, they have to be converted to integers first.
Note that there are no [ ] around the value affected to total as in your code (you don't want a list, you want a single value).
Try this:
res = raw_input("Enter value: ")
print sum(map(int, res))
i think the answer you looking for is something like this:
a = int(input("3 digit number:"))
x = a // 100
y = a // 10 % 10
z = a % 10
print (x + y + z)
i'm a total noob and its an ez question for noobs learning but when looking for an ez answer i couldn't find it anywhere (here) The question is Adding the sum of "THREE" digits...
I got hung up on if the digits were 5 or 6 long dunno what the code would look like if digits weren't defined.
answer:
a = int(input("enter a few numbers:"))
conversion = str(a)
number =[]
for i in conversion:
a = int(i)
number.append(a)
print (sum(number))
or as shown before me:
number = map(int, str(input('Enter a number: ')))
print(sum(number))
but i still have a ways to goes till i understand this properly
Sorry...I'm kind of a programming noob. I was looking at some problem sets online and I found THIS ONE. I wrote this much:
import random
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
(f,g,h,i,j)=x=input("Your 5 Chosen Numbers:")
My problem is that I don't know how to make the program print something like "Please enter 5 numbers separated by only a comma" if more or less than five are entered. Also how would I do that if I wanted it to display a different message every other time they made that mistake?
Try this approach:
input_is_valid = False
while not input_is_valid:
comma_separated_numbers = raw_input("Please enter a list of 5 numbers,separated by commas: ")
numbers = [int(x.strip()) for x in comma_separated_numbers.split(",")]
if len(numbers) != 5:
print "Please enter exactly 5 numbers"
else:
input_is_valid = True
Looking at your link I'd say:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
other_numbers = sorted(ri(1,53) for i in range(5))
print 'your numbers:','\t',other_numbers,'\t','powerball:','\t',powerball
It seems that's more or less what he asks from you.
If I'm correct, you want the user to submit his series so to see if its one of the sets extracted (amirite?)
then it could be fine to do:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
while True:
myset = raw_input('your 5 numbers:').split()
if len(myset) != 5:
print "just five numbers separated ny a space character!"
else:
myset = sorted(int(i) for i in myset)
break
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
numbers = sorted(ri(1,53) for i in range(5))
print 'numbers:','\t',numbers,'\t','powerball:','\t',powerball
if numbers == myset:
print "you won!" ##or whatever the game is about
else:
print "ahah you loser"
EDIT: beware this doesn't check on random generated numbers. So it happens one number can appear more than once in the same sequence. To practice you may try avoiding this behavior, doing so with a slow pace learning some python in the way it could be:
make a set out of a copy of the list "numbers" -- use set()
if its length is less than 5, generate another number
check if the new number is in the list
if it is, then append it to the list. if its not unique yet, GOTO point 1 :-)
sort the whole thing again
there you go
happy reading the docs!
My proposition:
import random
import sys
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
bla = ["\nPlease enter 5 numbers separated by only a comma : ",
"\nPlease, I need 5 numbers separated by only a comma : ",
"\nPLEASE, 5 numbers exactly : ",
"\nOh gasp ! I said 5 numbers, no more nor less : ",
"\n! By jove, do you know what 5 is ? : ",
"\n==> I warn you, I am on the point to go off : "]
i = 0
while i<len(bla):
x = raw_input(warn + bla[i])
try:
x = map(int, x.split(','))
if len(x)==5:
break
i += 1
except:
print "\nTake care to type nothing else than numbers separated by only one comma.",
else:
sys.exit("You wanted it; I go out to drink a beer : ")
(f,g,h,i,j)=x
print f,g,h,j,i
.
Some explanation:
.
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item.
http://docs.python.org/reference/compound_stmts.html#index-801
.
.
x = map(int, x.split(','))
means that the function int() is applied to each element of the iterable which is the second argument.
Here the iterable is the list x.split(',')
Hence, x is a list of 5 integers
In Python 3, there is no more raw_input() , it has been replaced by input() that receives characters, as raw_input() in Python 2.
.
.