Whenever i run my program is print the number 10 randomly and i don't know where its coming from. Anyone help me out?
def main():
phoneNumber=int(input("Enter a 10 digit unformatted telephone number in the format ##########: "))
tempNumber = []
phoneNumber = str(phoneNumber)
length = len(phoneNumber)
index=0
print(length)
if (length ==10):
print("The unformatted number is: ",phoneNumber)
else:
print("The telephone number was NOT entered in unformatted format ##########.")
for num in phoneNumber:
tempNumber.append(num)
tempNumber.insert(0,"(")
tempNumber.insert(4,")")
tempNumber.insert(8,"-")
phoneNumber = ''.join(tempNumber)
print("The formatted number is: ",phoneNumber)
main()
You are printing the length of the input given by user, so that's why 10 is printed out (see statement no. 6 inside main() function).
phoneNumber = str(phoneNumber)
length = len(phoneNumber)
index = 0
print(length) # <--- this statement is printing the length of the input
Related
I'm new to python and I really need some help, the question is a program asks the user to enter a name and number of choices. If the number of choices is less than 10, then display their name as much as that number. If not, display the message “Number entered more than 10” five times.
How to display the else condition "Number entered more than 10” five times?
name = input('What is your name: ')
number = int(input('Enter a number: '))
for i in range(number):
if (number > 0) and (number <= 10):
print(name)
else:
print("Number entered more than 10")
Just use separate for loops in different conditions:
name = input('What is your name: ')
number = int(input('Enter a number: '))
if number > 0 and number <= 10:
for i in range(number):
print(name)
else:
for i in range(5):
print("Number entered more than 10")
You can use the for loop:
for i in range(10):
print("Message")
This one prints "Message" 10 times. I leave the rest as an exercise :)
I have just added what is needed to your attempt. See below
# read your inputs
name = input('What is your name: ')
number = int(input('Enter a number: '))
if 0<number<=10:
# if in range, print it that many times
print("\n".join([name]*number))
else:
# if not print 5 times
print("\n".join(["Number entered more than 10"]*5))
You could try:
else:
print("Number entered more than 10" * 5)
or, if you'd like to have prints in separate lines:
else:
print("Number entered more than 10\n" * 5)
the \n stands for new line to be added after every line.
I'm trying to work out the average of numbers that the user will input. If the user inputs nothing (as in, no value at all) I want to then calculate the average of all numbers that have been input by the user upto that point. Summing those inputs and finding the average is working well, but I'm getting value errors when trying to break the loop when the user inputs nothing. For the if statement I've tried
if number == ''
First attempt that didn't work, also tried if number == int("")
if len(number) == 0
This only works for strings
if Value Error throws up same error
Full code below
sum = 0
while True :
number = int(input('Please enter the number: '))
sum += number
if number == '' :
break
print(sum//number)
Error I'm getting is
number = int(input('Please enter the number: '))
ValueError: invalid literal for int() with base 10:>
Any help much appreciated!
EDIT: Now getting closer thanks to the suggestions in that I can get past the problems of no value input but my calculation of average isn't working out.
Trying this code calculates fine but I'm adding the first input twice before I move to the next input
total = 0
amount = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
total = number + number
amount += 1
except:
break
total += number
print(total/amount)
Now I just want to figure out how I can start the addition from the second input instead of the first.
sum = 0
while True :
number = input('Please enter the number: '))
if number == '' :
break
sum += int(number)
print(sum//number)
try like this
the issue is using int() python try to convert input value to int. So, when its not integer value, python cant convert it. so it raise error. Also you can use Try catch with error and do the break.
You will always get input as a string, and if the input is not a int then you cant convert it to an int. Try:
sum = 0
while True :
number = input('Please enter the number: ')
if number == '' :
break
sum += int(number)
print(sum//number)
All of the answers dont work since the print statement referse to a string.
sum = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
except:
break
sum += number
print(sum//number)
including a user_input will use the last int as devisor.
My answer also makes sure the script does not crash when a string is entered.
The user has to always input something (enter is a character too) for it to end or you will have to give him a time limit.
You can convert character into int after you see it isn't a character or
use try & except.
sum = 0
i = 0
while True :
try:
number = int(input('Please enter the number: '))
except ValueError:
break
i += 1
sum += number
try:
print(sum/number)
except NameError:
print("User didn't input any number")
If you try to convert a character into int it will show ValueError.
So if this Error occurs you can break from the loop.
Also, you are trying to get the average value.
So if a user inputs nothing you get NameError so you can print an Error message.
I wish to create a Function in Python to calculate the sum of the individual digits of a given number
passed to it as a parameter.
My code is as follows:
number = int(input("Enter a number: "))
sum = 0
while(number > 0):
remainder = number % 10
sum = sum + remainder
number = number //10
print("The sum of the digits of the number ",number," is: ", sum)
This code works up until the last print command where I need to print the original number + the statement + the sum. The problem is that the original number changes to 0 every time (the sum is correct).
How do I calculate this but also show the original number in the print command?
Keep another variable to store the original number.
number = int(input("Enter a number: "))
original = number
# rest of the code here
Another approach to solve it:
You don't have to parse the number into int, treat it as a str as returned from input() function. Then iterate each character (digit) and add them.
number = input("Enter a number: ")
total = sum(int(d) for d in number)
print(total)
You can do it completely without a conversion to int:
ORD0 = ord('0')
number = input("Enter a number: ")
nsum = sum(ord(ch) - ORD0 for ch in number)
It will compute garbage, it someone enters not a number
number = input("Enter a number: ")
total = sum((int(x) for x in list(number)))
print("The sum of the digits of the number ", number," is: ", total)
As someone else pointed out, the conversion to int isn't even required since we only operate a character at a time.
I'm doing a small program that has the job of a school's subjects and marks management.
HOW IT WORKS
I've created 4 variables: a dictionary, an initialized empty string(for subjects) and two initialized empty integers(one for the marks, the other one for the subjects number). The program asks the user to input the numbers of subjects to work with. After that, it enters in a for loop that repeats itself in the range of the subjects number. And it works fine. Now the problem comes when the user inputs a mark over the range specified. Let's suppose we have a school and the marks we can input are between 1 and 10. The user can't write 11,12 and so on..
CODE
pagella = {}
materia = ""
voti = 0
length = 0
print("Insert the number of subjects, the subjects and the marks-")
num = int(input("Number of subjects: "))
length = len(pagella)
length = num
for i in range(length):
materia = input("Subject: ")
voto = eval(input("Mark: "))
if(voto > 10):
print("Number between 1 and 10")
else:
pagella[materia] = voto
print(pagella)
As you can see, there's the for loop that asks the user to input the subjects and the marks in the range of num(the number of subjects). If I try to input 12 on a mark, the program tells me to input a mark between 1 and 10 so it repeat again the cycle from the beginning. But the problem is that in this case, if I want to have 3 subjects with 3 marks (that means 3 iterations), one is lost because of the wrong mark, so I will not have 3 subjects and marks to input correctly, but only 2.
I hope I've explained correctly everything and someone can help me!
Thanks in advice
I suggest you the following solution that handles also the cases of non-numeric values as input for marks:
pagella = {}
materia = ""
length = 0
print("Insert the number of subjects, the subjects and the marks-")
num = int(input("Number of subjects: "))
length = num
for i in range(num):
# Ask for subject
materia = input("Subject: ")
# Ask for mark until the input is correct
voto = None
while (voto is None):
try:
voto = int(input("Mark: "))
if (voto > 10):
print("Number between 1 and 10")
voto = None
except:
print("Pleaser enter an integer")
# Store in dictionary pagella (if mark is correct)
pagella[materia] = voto
print(pagella)
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 !