I was wondering how I would sum up the numbers they input for n even though it's an input and not int. I am trying to average out all the numbers they input.
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Start now ")
a+=1
In Python 2.x input() evaluates the input as python code, so in one sense it will return something that you can accept as an integer to start with, but may also cause an error if the user entered something invalid. raw_input() will take the input and return it as a string -> evaluate this as an int and add them together.
http://en.wikibooks.org/wiki/Python_Programming/Input_and_Output
You would be better off using a list to store the numbers. The below code is intended for Python v3.x so if you want to use it in Python v2.x, just replace input with raw_input.
print("Enter as many numbers you want, one at the time, enter stop to quit. ")
num = input("Enter number ").lower()
all_nums = list()
while num != "stop":
try:
all_nums.append(int(num))
except:
if num != "stop":
print("Please enter stop to quit")
num = input("Enter number ").lower()
print("Sum of all entered numbers is", sum(all_nums))
print("Avg of all entered numbers is", sum(all_nums)/len(all_nums))
sum & len are built-in methods on lists & do exactly as their name says. The str.lower() method converts a string to lower-case completely.
Here is one possibility. The point of the try-except block is to make this less breakable. The point of if n != "stop" is to not display the error message if the user entered "stop" (which cannot be cast as an int)
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Enter a number: ")
try:
a+=int(n)
except:
if n != "stop":
print("I can't make that an integer!")
print("Your sum is", a)
Related
I am working on a program that requires the user to enter a number and will continue to loop until a positive number is given. When a positive number is given, it will alert the user and present them with the sum of the digits of their number. However, I thought I had written my code correctly, but it is giving me an incorrect answer. What have I done wrong and how can I fix this?
user_input = float(int(input("Please Enter Your Number:")))
s = 0
while user_input < 0:
float(int(input("Please Enter Another Number: ")))
if user_input > 0:
s += user_input%10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
Four things:
Not sure why you storing the input as float, int should suffice.
If you give a negative input, it will enter the while loop. However, in the while loop, you are not actually assigning the new input to user_input. Fix this by adding user_input =
The while loop guarantees user_input is >= 0, so if user_input > 0: is unnecessary.
Probably the most important, to calculate the sum of digits, you need to repeatedly divide and sum, not just do it once. So, add a while loop.
Final code:
user_input = int(input("Please Enter Your Number: "))
s = 0
while user_input < 0:
user_input = int(input("Please Enter Another Number: "))
while user_input:
s += user_input % 10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
The if statement is generally used to decide if something should be done once.
If you want to keep going until user_input becomes zero, you'll need a while.
Also, I'm not entirely certain why you're storing the number as a float, especially when you make that from an int anyway. It may as well just be an int.
Additionally, you're loop to re-enter the value if it was negative doesn't actually assign the new value to the variable.
And you probably also want to outdent the print statement lest it be done on every iteration of the loop you're about to add.
Of course, some may suggest a more Pythonic way of summing the digits of a positive number is a simple:
sum([int(ch) for ch in str(x)])
That works just as well, without having to worry about explicit loops.
Another way to solve this is using assert and a function:
def sum_num():
# try get user input
try:
user_in = input('Enter Number: ')
assert int(user_in) > 0
except AssertionError:
# we got invalid input
sum_num()
else:
s_d = sum([int(i) for i in user_in])
print('You\'ve entered a positive number! The sum of the digits is: ', s_d)
#run the function
sum_num()
So this will asked user input, if it is not greater than zero it will throw assertion error, which we catch and return the user to inputting the number by calling the function again. If all is well, we split the input into character and add them up. as list('12') gives ['1','2']. We convert to int and add them. :)
The awesome thing about this is you can add more too the asset to capture other issue as floats, character as invalid inputs. E.g.
Assuming literal_eval is important( from ast import literal_eval)
assert isinstance(literal_eval(user_in),int) and int(user_in)>0
Check if user_in is integer and it is greater than 0. So you won’t get issues when user inputs floats or characters.
So this is a prompt for user input, and it works just fine. I was printing some names and associated (1 based) numbers to the console for the user to choose one. I am also giving the option to quit by entering q.
The condition for the number to be valid is a) it is a number and b) it is smaller or equal than the number of names and greater than 0.
while True:
number = str(input("Enter number, or q to quit. \n"))
if number == "q":
sys.exit()
try:
number = int(number)
except:
continue
if number <= len(list_of_names) and number > 0:
name = list_of_names[number-1]
break
There is no problem with this code, except I find it hard to read, and not very beautiful. Since I am new to python I would like to ask you guys, how would you code this prompt more cleanly? To be more specific: How do I ask the user for input that can be either a string, or an integer?
A bit simpler:
while True:
choice = str(input("Enter number, or q to quit. \n"))
if choice.lower() == "q":
sys.exit()
elif choice.isdigit() and (0 < int(choice) <= len(list_of_names)):
name = list_of_names[int(choice)-1]
break
Just downcase it.
number = str(input("Enter number, or q to quit. \n"))
number = number.lower()
That will make the q lower case so it doesn't matter if they press it with shift if they press something else just make a if statement that sets a while loop true.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
I'm a beginner in the Python language. Is there a "try and except" function in python to check if the input is a LETTER or multiple LETTERS. If it isn't, ask for an input again? (I made one in which you have to enter an integer number)
def validation(i):
try:
result = int(i)
return(result)
except ValueError:
print("Please enter a number")
def start():
x = input("Enter Number: ")
z = validation(x)
if z != None:
#Rest of function code
print("Success")
else:
start()
start()
When the above code is executed, and an integer number is entered, you get this:
Enter Number: 1
Success
If and invalid value however, such as a letter or floating point number is entered, you get this:
Enter Number: Hello
Please enter a number
Enter Number: 4.6
Please enter a number
Enter Number:
As you can see it will keep looping until a valid NUMBER value is entered. So is it possible to use the "try and except" function to keep looping until a letter is entered? To make it clearer, I'll explain in vague structured English, not pseudo code, but just to help make it clearer:
print ("Hello this will calculate your lucky number")
# Note this isn't the whole program, its just the validation section.
input (lucky number)
# English on what I want the code to do:
x = input (luckynumber)
So what I want is that if the variable "x" IS NOT a letter, or multiple letters, it should repeat this input (x) until the user enters a valid letter or multiple letters. In other words, if a letter(s) isn't entered, the program will not continue until the input is a letter(s). I hope this makes it clearer.
You can just call the same function again, in the try/except clause - to do that, you'll have to adjust your logic a bit:
def validate_integer():
x = input('Please enter a number: ')
try:
int(x)
except ValueError:
print('Sorry, {} is not a valid number'.format(x))
return validate_integer()
return x
def start():
x = validate_integer()
if x:
print('Success!')
Don't use recursion in Python when simple iteration will do.
def validate(i):
try:
result = int(i)
return result
except ValueError:
pass
def start():
z = None
while z is None:
x = input("Please enter a number: ")
z = validate(x)
print("Success")
start()
If I'm asking for a user input of numbers which continues as long as an empty string is not entered, if an empty string is entered then the program ends.
My current code is:
n=0
while n != "":
n = int(input("Enter a number: "))
But obviously this isn't exactly what I want. I could remove the int input and leave it as a regular input, but this will allow all types of inputs and i just want numbers.
Do i ago about this a different way?
calling int() on an empty string will cause a ValueError so you can encapsulate everything in a try block:
>>> while True:
try:
n = int(input('NUMBER: '))
except ValueError:
print('Not an integer.')
break
NUMBER: 5
NUMBER: 12
NUMBER: 64
NUMBER:
not a number.
this also has the added benefit of catching anything ELSE that isn't an int.
I would suggest using a try/except here instead.
Also, with using a try/except, you can instead change your loop to using a while True. Then you can use break once an invalid input is found.
Also, your solution is not outputting anything either, so you might want to set up a print statement after you get the input.
Here is an example of how you can put all that together and test that an integer is entered only:
while True:
try:
n = int(input("Enter a number: "))
print(n)
except ValueError:
print("You did not enter a number")
break
If you want to go a step further, and handle numbers with decimals as well, you can try to cast to float instead:
while True:
try:
n = float(input("Enter a number: "))
print(n)
except ValueError:
print("You did not enter a number")
break
# Math Quizzes
import random
import math
import operator
def questions():
# Gets the name of the user
name= ("Alz")## input("What is your name")
for i in range(10):
#Generates the questions
number1 = random.randint(0,100)
number2 = random.randint(1,10)
#Creates a Dictionary containg the Opernads
Operands ={'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'/':operator.truediv}
#Creast a list containing a dictionary with the Operands
Ops= random.choice(list(Operands.keys()))
# Makes the Answer variable avialabe to the whole program
global answer
# Gets the answer
answer= Operands.get(Ops)(number1,number2)
# Makes the Sum variable avialbe to the whole program
global Sum
# Ask the user the question
Sum = ('What is {} {} {} {}?'.format(number1,Ops,number2,name))
print (Sum)
global UserAnswer
UserAnswer= input()
if UserAnswer == input():
UserAnswer= float(input())
elif UserAnswer != float() :
print("Please enter a correct input")
def score(Sum,answer):
score = 0
for i in range(10):
correct= answer
if UserAnswer == correct:
score +=1
print("You got it right")
else:
return("You got it wrong")
print ("You got",score,"out of 10")
questions()
score(Sum,answer)
When I enter a float number into the console the console prints out this:
What is 95 * 10 Alz?
950
Please enter a correct input
I'm just curious on how I would make the console not print out the message and the proper number.
this is a way to make sure you get something that can be interpreted as a float from the user:
while True:
try:
user_input = float(input('number? '))
break
except ValueError:
print('that was not a float; try again...')
print(user_input)
the idea is to try to cast the string entered by the user to a float and ask again as long as that fails. if it checks out, break from the (infinite) loop.
You could structure the conditional if statement such that it cause number types more than just float
if UserAnswer == input():
UserAnswer= float(input())
elif UserAnswer != float() :
print("Please enter a correct input")
Trace through your code to understand why it doesn't work:
UserAnswer= input()
This line offers no prompt to the user. Then it will read characters from standard input until it reaches the end of a line. The characters read are assigned to the variable UserAnswer (as type str).
if UserAnswer == input():
Again offer no prompt to the user before reading input. The new input is compared to the value in UserAnswer (which was just entered on the previous line). If this new input is equal to the previous input then execute the next block.
UserAnswer= float(input())
For a third time in a row, read input without presenting a prompt. Try to parse this third input as a floating point number. An exception will be raised if this new input can not be parsed. If it is parsed it is assigned to UserAnswer.
elif UserAnswer != float() :
This expression is evaluated only when the second input does not equal the first. If this is confusing, then that is because the code is equally confusing (and probably not what you want). The first input (which is a string) is compared to a newly created float object with the default value returned by the float() function.
Since a string is never equal to a float this not-equals test will always be true.
print("Please enter a correct input")
and thus this message is printed.
Change this entire section of code to something like this (but this is only a representative example, you may, in fact, want some different behavior):
while True:
try:
raw_UserAnswer = input("Please enter an answer:")
UserAnswer = float(raw_UserAnswer)
break
except ValueError:
print("Please enter a correct input")