This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 months ago.
i=0
while (i==0):
n1=float(input("Enter the first number: \n"))
n2=float(input("Enter the second number: \n"))
a=str(input("Choose the operation: \n 1.) + \n 2.) - \n 3.) * \n 4.) / \n 5.) % \n"))
if(a==1):
print("The addition of the inputted numbers is ", sum(n1,n2),"\n")
elif(a==2):
print("The difference between the inputted numbers is ", diff(n1,n2),"\n")
elif(a==3):
print("The multiplication of the inputted numbers is ", product(n1,n2),"\n")
elif(a==4):
print("The division of the inputted numbers is ", div(n1,n2),"\n")
elif(a==5):
print("The modulus of the inputted numbers is ", modulus(n1,n2),"\n")
else:
print("Do you want to quit the calculator?")
b=int(input("Press 00 for 'Yes' and 11 for 'No'\n"))
if(b==00):
break
else:
print("Enter a valid option for the operation number.\nThe calculator is re-starting.")
continue
This is my python code. I have defined all the functions used here.
The output I am getting is:
When I inputted the correct operation number 3 at the place I have circled in the image, why is the output not giving me the final calculated answer? Why is it repeating the same loop again and again?
Please help me in this.
Hacker already provided you with all the changes that need to be done. You need to look at your integer vs string comparison, your while loop usage, and your Try-Except options.
To help you have a reference point, here's modified code for you to compare:
while True:
while True:
try:
n1=float(input("Enter the first number: \n"))
break
except:
print ('Enter a number. It can be integer or float')
while True:
try:
n2=float(input("Enter the second number: \n"))
break
except:
print ('Enter a number. It can be integer or float')
while True:
try:
a=int(input("Choose the operation: \n 1.) + \n 2.) - \n 3.) * \n 4.) / \n 5.) % \n"))
if 1 <= a <= 5:
break
else:
print ('Enter a number within range 1 and 5')
except:
print ('Not a number. Please enter an integer')
if (a==1):
print("The addition of the inputted numbers is ", (n1+n2),"\n")
elif (a==2):
print("The difference between the inputted numbers is ", (n1-n2),"\n")
elif (a==3):
print("The multiplication of the inputted numbers is ", (n1*n2),"\n")
elif (a==4):
print("The division of the inputted numbers is ", n1/n2,"\n")
elif (a==5):
print("The modulus of the inputted numbers is ", int(n1%n2),"\n")
print("Do you want to quit the calculator?")
while True:
try:
b=int(input("Press 00 for 'Yes' and 11 for 'No'\n"))
if b==0: break
elif b!= 11: print ('Enter a valid option: 00 or 11')
except:
print ('Not a number. Please enter an integer')
I am just going to summarize the comments and add some stuff.
The while loop will run forever if you do not break it because i is always going to be 0 because it is not changed inside of the loop.
As Thierry Lathuille pointed ot friendly a is defined as a stra str can never be equal to a number: you would have to do:
int(a)==1 or a==str(1)
Your input was 11 and as expected the calculator said that he is going to restart and did not break.
continue will restart the loop while break will stop it. As #chepner pointed out: if continue is the last possible statement then it doesn`t do anything.
Also pointed out by #chepner is that 00 is equal to 0
Related
I write a code in python to ask a user to input a number and check if is it less than or equal to zero and print a sentence then quit or otherwise continue if the number is positive , also it checks if the input is a number or not
here is my code
top_of_range = input("Type a number: ")
if top_of_range.isdigit():
top_of_range = int(top_of_range)
if top_of_range <= 0:
print ("please enter a nubmer greater than 0 next time.")
quit()
else:
print(" please type a number next time.")
quit()
As the help on the isdigit method descriptor says:
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
When you pass a negative number, e.g. -12. All characters in it are not a digit. That is why you're not getting the desired behavior.
You can try something like the following:
top_of_range = input("Type a number: ")
if top_of_range.isdigit() or (top_of_range.startswith("-") and top_of_range[1:].isdigit()):
top_of_range = int(top_of_range)
if top_of_range <= 0:
print ("please enter a nubmer greater than 0 next time.")
quit()
else:
print(" please type a number next time.")
quit()
Based on Mark's comment, if we employ the EAFP principle it will look something like this:
top_of_range = input("Type a number: ")
try:
top_of_range = int(top_of_range)
if top_of_range <= 0:
print ("please enter a nubmer greater than 0 next time.")
quit()
except ValueError:
print(" please type a number next time.")
quit()
Here's the instructions:
This question deals with numbers that can be used as keys: two numbers
are considered to be key if the largest of the two numbers is prime. A
prime number is one that is divisible by 1 and itself. Your task is to
write a python program that reads two integers (as described above)
from the user and checks if they are valid keys. If the user inputs a
float, the appropriate conversion must be done. If the user inputs a
non digit number, the appropriate error catch must be used Allow the
user to repeat the process as many times as she/he would like
Here is my attempt at an answer but the answers of this code keep changing and I don't know why...
i=1
while i!=0:
int1=int(input("dear user please enter the 1st number "))
int2=int(input("dear user please enter the 2nd number"))
largest=max(int1 , int2)
if largest >1:
for i in range (2, int(largest/2)+1):
if ( largest % i )== 0:
print("it cannot be a key ", largest)
break
else:
print("the key is ", largest) break print (" enter another keys")
If you mean that it prints "valid key" and "invalid key" in the same run, it's because it runs through every value for i, so for example 27 % 3 = 0 but 27 % 2 != 0 therefore it will for i = 3 print that it is a valid key.
To fix this you could do this:
valid_key = False
if largest > 1: for i in range(2, (int(largest/2)) + 1):
if (largest % i) == 0:
valid_key = False
break
else:
valid_key = True
if(valid_key):
print(largest, "is a valid key"
else:
print(largest, "is not a prime number")
You can use for-else. It will check if the largest number can divide by i and if it doesn't divide by any of those numbers it will go for the else and say that its a prime number so it wont print negative and positive at the same time. Here's how to use it:
while 1 != 0:
int1 = int(input("dear user please enter the 1st number "))
int2 = int(input("dear user please enter the 2nd number"))
largest = max(int1, int2)
if largest > 1:
for i in range(2, int(largest/2)+1):
if (largest % i) == 0:
print("it cannot be a key ", largest)
break
else:
print("the key is ", largest)
print("enter another keys")
It is because, for every condition it is printing some or the other thing. You've to take a new variable which has some inital value. Check the if condition in loop, if the condition is satisfied, change the value of the variable. After completion, check if the variable value is changed or not. If changed, the condition was satisfied else, it was never satisfied. Your code:
i=1
f=0
while i!=0:
int1=int(input("dear user please enter the 1st number "))
int2=int(input("dear user please enter the 2nd number"))
largest=max(int1 , int2)
if largest >1:
for i in range (2, int(largest/2)+1):
if ( largest % i )== 0:
f=1
break
if f==1:
print("It cannot be key")
if f==0:
print("It can be key")
break
Apologies if the question to this is worded a bit poorly, but I can't seem to find help on this exercise anywhere. I am writing a basic Python script which sums two numbers together, but if both numbers inputted are the same the sum will not be calculated.
while True:
print('Please enter a number ')
num1 = input()
print('Please enter a second number ')
num2 = input()
if num1 == num2:
print('Bingo equal numbers!')
continue
elif num1 == num2:
print('It was fun calculating for you!')
break
print('The sum of both numbers is = ' + str(int(num1) + int(num2)))
break
If both numbers are equal I want the script to loop back once more and if the numbers inputted are equal again I want the program to end. With the code I have provided the issue I am having is that when I enter two equal numbers it keeps constantly looping until I enter two different numbers.
You would likely want to have a variable keeping track of the number of times that the numbers were matching. Then do something if that counter (keeping track of the matching) is over a certain threshold. Try something like
matches = 0
while True:
num1 = input('Please enter a number: ')
num2 = input('Please enter a second number: ')
if num1 == num2 and matches < 1:
matches += 1
print('Bingo equal numbers!')
continue
elif num1 == num2:
print('It was fun calculating for you!')
break
print('The sum of both numbers is = ' + str(int(num1) + int(num2)))
break
You can add give input code again inside first if statement or use some other dummy variable for loop so that you can break the loop, for e.g. use while j == 0 and increase it j += 1when you are inside the first if statement
continue skips the execution of everything else in the loop. I don't see it much useful in your example. If you want to print the sum then just remove it.
How continue works can be demonstrated by this sample (taken from python docs)
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
Result
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
I'm currently working on a program in Python and I need to figure out how to convert a string value to a float value.
The program will ask the user to enter a number, and uses a loop to continue asking for more numbers. The user must enter 0 to stop the loop (at which point, the program will give the user the average of all the numbers they entered).
What I want to do is allow the user to enter the word 'stop' instead of 0 to stop the loop. I've tried making a variable for stop = 0, but this causes the program to give me the following error message:
ValueError: could not convert string to float: 'stop'
So how do I make it so that 'stop' can be something the user can enter to stop the loop? Please let me know what I can do to convert the string to float. Thank you so much for your help! :)
Here is some of my code:
count = 0
total = 0
number = float(input("Enter a number (0, or the word 'stop', to stop): "))
while (number != 0):
total += number
count += 1
print("Your average so far is: " , total / count)
number = float(input("Enter a number (0, or the word 'stop', to stop): "))
if (number == 0):
if (count == 0):
print("")
print("Total: 0")
print("Count: 0")
print("Average: 0")
print("")
print("Your average is equal to 0. Cool! ")
else:
print("")
print("Total: " , "%.0f" % total)
print("Count: " , count)
print("Average: " , total / count)
Please let me know what I should do. Thanks.
I'd check the input to see if it equals stop first and if it doesn't I'd try to convert it to float.
if input == "stop":
stop()
else:
value = float(input)
Looking at your code sample I'd do something like this:
userinput = input("Enter a number (0, or the word 'stop', to stop): ")
while (userinput != "stop"):
total += float(userinput) #This is not very faulttolerant.
...
You could tell the user to enter an illegal value - like maybe your program has no use for negative numbers.
Better, would be to test if the string you've just read from sys.stdin.readline() is "stop" before converting to float.
You don't need to convert the string to a float. From what you've said it appears that entering 0 already stops the loop, so all you need to do is edit you're currently existing condition check, replacing 0 with "stop".
Note a few things: if the input is stop it will stop the loop, if it's not a valid number, it will just inform the user that the input were invalid.
while (number != 0):
total += number
count += 1
print("Your average so far is: " , total / count)
user_input = input("Enter a number (0, or the word 'stop', to stop): ")
try:
if str(user_input) == "stop":
number = 0
break
else:
number = float(user_input)
except ValueError:
print("Oops! That was no valid number. Try again...")
PS: note that keeped your code "as is" mostly, but you should be aware to not use explicit counters in python search for enumerate...
This is the problem I have to solve : Write a program to sum a series of numbers entered by the user. The program should first prompt the user for how many numbers are to be summed. It should then input each of the numbers and print a total sum. This is what I have so far:
def excercise13():
print("Programming Excercise 13")
print("This program adds a series of numbers.")
while True:
try:
numberTimes = float(input("Enter how many numbers will be added: "))
except ValueError:
print("Invalid input.")
else:
break
numberTimes = int(numberTimes)
while True:
try:
for i in range(1,(numberTimes+1)):
("""I don't know what to put here""")
except ValueError:
print("Invalid input.")
else:
break
totalSum =
print("The sum of",nums,"is:",totalSum)
print()
excercise13()
I will go through the solution, based on your code, code block by code block.
def excercise13():
currentnumber = 0
Here we create the function excercise13() and set currentnumber to 0
print("Programming Excercise 13")
print("This program adds a series of numbers.")
while True:
try:
numberTimes = int(input("Enter how many numbers will be added: "))
except ValueError:
print("Invalid input.")
else:
break
You should use int instead of float. Can you imagine doing a process 3.5 times? This also reduces your previous repetition.
for x in range(numbertimes): #More pythonic way.
new_number = input ("Please enter a number to be added.")
currentnumber += new_number
The above code block makes the program ask for a new number numbertimes times. It then adds this number to currentnumber
totalSum = currentnumber
print("The sum of",nums,"is:",totalSum)
print()
This sets the totalSum to the final currentnumber
excercise13()
This starts your code.
Python has this functionality built in as the sum function.
def makesum():
try:
numbers = input('Enter the numbers to sum, comma seperated: ')
print 'The sum is {0}'.format(sum(numbers))
except:
print 'Input invalid. Try again.'
makesum()
makesum()