I'm new in coding or programming so I hope for respect.
How can I create a program that continually accepts input from the user. The input shall be in this format operatornumber like -3
Like
num = 0
while((a := input("Enter operatornumber like -9;")) != "-0"):
if (len(a) >= 2) and (a[0] in "/*-+"):
num = eval(f"{num}{a}")
else:
print("Invalid input, try again.")
print(num)
But how can I make the first input of the user to only use the add (+) or subtract(-) operators but in the next input they can now use the other operators.
Like
Enter operatornumber like -9; +9
Enter operatornumber like -9; -8
Enter operatornumber like -9; -0
1
And how can I combine all the input like
+9-9 is 1?
In the input statement, you're closing the "Enter operator and number like" msg. This is creating more problems after that line, where all green parts are considered as string now. Also, in while statement, "w" should be small letter, python is case sensitive. Try doing this:
Number = input("Enter operator and number like '-9' ")
Operator = ("+","-","/")
while Number == (Operator + Number):
if Number == "-0":
Total = 0
Total += Number
print(f"the result of {num} is {total} ")
You can use double quotes for the text and single quotes for the number, so they don't close each other.
You can get input forever using following code:
while True:
Number = input("Enter operator and number like '-9'")
# Place your next code here.
Here is another answer. We have to take input from user with operator as well, so len(<user_input<) should be >=2. Now, we'll take another variable h in which we'll traverse the string from index 1 to end, which means the operator gets removed and we'll convert it into int. Then we'll put if condition in which we'll check the user_input[0] is +,-,*,/ and then acc to that, we'll update the result. We'll ask the user whether he wants more operations or no, if y, then keep asking, else, break the while loop. Here's my code:
result=0
while True:
a=input("Enter operator and number= ")
if len(a)>=2 and a[0] in ["+","-","*","/"]:
h=int(a[1::])
if a[0]=="+":
result+=h
elif a[0]=="-":
result-=h
elif a[0]=="*":
result*=h
elif a[0]=="/":
result/=h
else:
print("choose only from +-/*")
else:
print("invalid input")
ch=input("Enter more?")
if ch=='n':
break
print(f"The result is {result}")
Check for indentation errors because I've copied and pasted it so it may have indentation errors
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.
I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.
I am trying to create a basic calculator that takes the first number, takes the operation(+,-,*,/), and second number. If a person puts in a zero for the first number and/or the second number my program is supposed to go back to the number it was at and ask again for a number other than 0. So if a person puts in 0 for number 2 then my program will take the person back to number two. I am also supposed to do the same concept for the operation but have the person start over if they do not put in the operation available to use which includes the ones previously shown in parentheses. Below is the code I have so far. Any help would be appreciated. My class is currently on while loops and breaks among other things, but I am wondering if those two would be beneficial in my code.
#Programming Fundamentals Assignment Unit 5
#Create a basic calculator function
while True:
#Num1 will require user input
num1 = input ("Enter the first number\n")
#Operation will require user input
operation = raw_input("Enter the operation(+,-,*,/)\n")
#Num2 will require user input
num2 = input("Enter the second number\n")
#Now to define how the operation will be used
if operation == "+":
print num1+num2
elif operation == "-":
print num1-num2
elif operation == "*":
print num1*num2
elif operation == "/":
print num1/num2
else:
print "Please enter an operation"
#Exit will end the calculation from going into a loop
exit()
Put loops around your various inputs to ensure proper checking. So for the first number, you could have:
num1 = 0
while num1 == 0:
num1 = input ("Enter the first number\n")
This'll keep asking till they input something that isn't a 0.
For the second issue (starting over if they enter an invalid operation), you want to immediately check if the operation is valid and if it isn't, then you need to re-loop (which is just by skipping the remaining parts of the current loop).
So to easily check if it's valid:
operation not in ["+","-","*","/"]
which will return false if they enter invalid, and then the second part (skipping the rest of the loop) can easily be accomplished with the "continue" keyword.
if operation not in ["+","-","*","/"]:
continue
This will take you back to the beginning of the loop, asking for new number first number.
When you want to stop execution, you'll need to implement "break" which will break out of the inner most loop that it's a part of.
I have a function below which is part of my big main function, what I want this function to do is that whenever called, I want the function to check if the user input is
a number or not. If it is a number it will return the number and break.
But if it is not a number I want it to loop again and again.when I try to
run it, it gives me unexpected an error:
unexpected eof while parsing
can any body help me what I am missing or how I should rearrange my code? thank you!
def getnumber():
keepgoing==True
while keepgoing:
number = input("input number: ")
result1 = number.isdigit()
if result1 == 1:
return number
break
elif keepgoing==True:
A neater and clearer what to do what you are already doing:
def getnumber():
while True:
number = input("Input number: ")
if number.isdigit():
return number
That's all you need, the extra variables are superfluous and the elif at the end makes no sense. You don't need to check booleans with == True or == 1, you just do if condition:. And nothing happens after return, your break will never be reached.
You don't need the last line:
elif keepgoing==True:
It's waiting for the rest of the file after the :.
Side note, it should be a single = in the first part, and can just be written simpler as well.
def getnumber():
while True:
number = input("input number: ")
result1 = number.isdigit()
if result1:
return number
Since you're inside the while loop, it'll keep executing. Using return will end the while loop, as will breaking and exiting the program. It will wait for input as well each time, though.
While assigning you have used keepgoing == True, I think it should be keepgoing=True
The following solution works on my machine, although I am running Python 2.7
def get_num():
while True: #Loop forever
number_str = raw_input("> Input a number: ") #Get the user input
if number_str.isdigit(): #They entered a number!
return int(number_str) #Cast the string to an integer and return it
I used raw_input rather than input, because raw_input gives you the exact string the user entered, rather than trying to evaluate the text, like input does. (If you pass the 12 to input, you'll get the number 12, but if you pass "12", you'll get the string '12'. And, if you pass my_var, you'll get whatever value was in my_var).
Anyway, you should also know that isdigit() returns whether or not the string has only digits in it and at least one character - that is not the same thing as isNumber(). For instance, "123".isdigit() is True, but "123.0".isdigit() is False. I also simplified your loop logic a bit.
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)