im relatively new to python and im not really sure how does the indentation for if else works.
Write a Python program that calculates the sum of all the numbers from x to y, where x and y are numbers entered by the user.
print("This program prints the sum of range from x to y. ")
print("For example, if x is 10 and y is 50, the program will print the sum of numbers from 10 to 50. ")
x = int(input("Please enter the value of x: "))
y = int(input("Please enter the value of y: "))
if type(x) == int and type(y) == int:
if x > 0 and y > 0:
if y > x:
sum_of_numbers = []
for counter in range(x , y):
sum_of_numbers.append(x)
x += 1
print("The sum of numbers from {} to {} is {}".format(x,y,sum(sum_of_numbers)))
else:
print("You did not enter a value of y greater than x")
print("Unable to continue.Program terminated.")
exit()
else:
print("One or more inputs is not greater than zero")
print("Unable to continue.Program terminated.")
exit()
else:
print("One or more inputs is not numeric!")
print("Unable to continue.Program terminated.")
exit()
if type(x) == int and type(y) == int:
if x > 0 and y > 0: # indented 1
if y > x: # indented 3
sum_of_numbers = [] # indented 4
You need to have consistent indentation, preferably four spaces for each indent, as per PEP8.
Without that, the Python compiler (or you as well, really) can't tell how your code is meant to be structured.
Related
so I am doing my first project which is a triangle identifier through sides, I came across this issue where if someone wrote a letter the program would crash since you can't float the input when it's a string so I tried a few methods (try: except I tried:
if x == str and x != int and x != float:
print("please choose a viable unit ")
but it now displays that even when I have normal numbers like (4,6,6 )
I only did the x input to know if it works in the first place
my final code :
print("please input the sides of the triangle")
x = input("the first side = ")
y = input(" the second side = ")
z = input("the third side = ")
if str(x) == x and int(x) != x and float(x) != x:
print("please choose a viable unit ")
elif x == y == z:
print("the triangle is equilateral ")
elif x == y or y == z or x == z:
print("the triangle is isosceles")
elif x != y or x != z or y != z:
print("the triangle is scalene")
elif(x*x) + (y*y) == (z*z) or (z*z) + (y*y) == (x*x) or (z*z) + (x*x) == (y*y):
print("the triangle is also right")
This line:
if str(x) == x and int(x) != x and float(x) != x:
does not actually turn x into either an int or a float; it can also never be true, because it's not possible for x to be all of those types at once. x is always going to be a str because input always returns a str. The only thing this line can do is raise a ValueError (which will cause your script to exit since you haven't caught it) if x is a value that can't be converted into an int.
What you want to do is turn x, y, and z into floats as soon as you read them:
try:
x = float(input("the first side = "))
y = float(input(" the second side = "))
z = float(input("the third side = "))
except ValueError:
print("please choose a viable unit ")
exit()
After this point, if the script hasn't exited, x, y, and z are guaranteed to be float values, and you can perform math operations on them without encountering TypeErrors.
First: Do everyone a favor and change your title to something along the lines of "Help with Python Input and Ints"
Second:
When you use a python input, it reads that input as a string. So, in order to do any math with that string, it needs to NOT be a string, and instead considered a number.
That being said the inputs will have to be along the lines of
foo = float(input("bar"))
Edit: You also mentioned that you were having issues if the user inputs a string. You can use this answer for reference on how to implement a try except case for that instance
I want to check if whether input is numeric, If it is, Compare the number to another.
I tried to resolve one issue by removing int() conversion. But that would render x > 0 useless.
Tried searching online, But there's no simple resolve.
print("This program prints the sum of a range of numbers from x to y")
print("For example, if x is 10 and y is 50, the program will print the sum of numbers")
print("from 10 to 50")
x = int(input("Please enter the value of x: "))
y = int(input("Please enter the value of y: "))
if x.isnumeric() and y.isnumeric():
if x > 0 and y > 0:
print("Passed")
else:
print("failed")
else:
print("One or more of your inputs are not numeric!")
Got 'int' object has no attribute 'isnumeric' as error
or
'>' not supported between instances of 'str' and 'int'
Your code has a few issues.
str.isnumeric applies to strings, but you are trying to call it on an integer, hence you get the error 'int' object has no attribute 'isnumeric' as error
If you then don't convert x to int, and leave it as str and try to do x > 0 and y > 0, you are comparing string and integer, which is not possible, as well, hence the error '>' not supported between instances of 'str' and 'int'
To resolve this, you can read x and y as a string, and then convert them to int when comparing them to 0 as follows.
print("This program prints the sum of a range of numbers from x to y")
print("For example, if x is 10 and y is 50, the program will print the sum of numbers")
print("from 10 to 50")
#Read x and y as strings
x = input("Please enter the value of x: ")
y = input("Please enter the value of y: ")
#Check if they are numeric
if x.isnumeric() and y.isnumeric():
#Convert them to int to compare them with 0
if int(x) > 0 and int(y) > 0:
print("Passed")
else:
print("failed")
else:
print("One or more of your inputs are not numeric!")
Then your output will look like
This program prints the sum of a range of numbers from x to y
For example, if x is 10 and y is 50, the program will print the sum of numbers
from 10 to 50
Please enter the value of x: 20
Please enter the value of y: 40
Passed
This program prints the sum of a range of numbers from x to y
For example, if x is 10 and y is 50, the program will print the sum of numbers
from 10 to 50
Please enter the value of x: 10
Please enter the value of y: 60
Passed
But hold on, what happened here
This program prints the sum of a range of numbers from x to y
For example, if x is 10 and y is 50, the program will print the sum of numbers
from 10 to 50
Please enter the value of x: -20
Please enter the value of y: -40
One or more of your inputs are not numeric!
Here I will make a note here that this logic won't work for negative integers
as you can see below, isnumeric returns False for negative integers
In [1]: '-20'.isnumeric()
Out[1]: False
Hence a much better approach might be is to try to cast the string as an int, and based on that, check if x is a number or not
print("This program prints the sum of a range of numbers from x to y")
print("For example, if x is 10 and y is 50, the program will print the sum of numbers")
print("from 10 to 50")
#Read x and y as strings
x = input("Please enter the value of x: ")
y = input("Please enter the value of y: ")
def is_number(s):
#If we can cast string to int, it is an int, else it is not
is_number = False
try:
int(s)
is_number = True
except ValueError:
pass
return is_number
#Check if they are numeric
if is_number(x) and is_number(y):
#Convert them to int to compare them with 0
if int(x) > 0 and int(y) > 0:
print("Passed")
else:
print("failed")
else:
print("One or more of your inputs are not numeric!")
Now the code will work for negative integers too
This program prints the sum of a range of numbers from x to y
For example, if x is 10 and y is 50, the program will print the sum of numbers
from 10 to 50
Please enter the value of x: -20
Please enter the value of y: -40
failed
This program prints the sum of a range of numbers from x to y
For example, if x is 10 and y is 50, the program will print the sum of numbers
from 10 to 50
Please enter the value of x: hey
Please enter the value of y: hi
One or more of your inputs are not numeric!
Output keeps on generating "try again." Whats the error here?
import random
x = int(input("guess a number between 0 and 10: \n"))
y = random.randint(0,10)
n = "try again"
while n == "try again":
if y == x:
print("congradulations\n")
break;
else:
input("try again\n")
You loop for as long as n == "try again". Since nothing ever changes n, that's forever.
You break out of the loop if y == x. But, since nothing ever changes either y or x, if that wasn't true the first time, it'll never be true, so you'll never break out of the loop.
You probably wanted to store the result in x, just like you do for the first input:
n = "try again"
while n == "try again":
if y == x:
print("congradulations\n")
break;
else:
x = int(input("try again\n"))
Now, instead of ignoring the user's retries, you'll actually test them to see if they're the right answer.
But, while we're at it, you can simplify this quite a bit. First, n never changes, so it's useless; you can just loop while True:
while True:
if y == x:
print("congradulations\n")
break;
else:
x = int(input("try again\n"))
Or you can just move the y == x check into the whileloop:
while y != x:
x = int(input("try again\n"))
print("congradulations\n")
import random
x = int(input("guess a number between 0 and 10: \n"))
y = random.randint(0,10)
n = "try again"
while x != y:
x = int(input('try again'))
else:
print('congratulations!')
Or:
import random
x = int(input("guess a number between 0 and 10: \n"))
y = random.randint(0,10)
n = "try again"
var = True
while var:
if x != y:
x = int(input('try again: '))
else:
print('congratulations!')
var = False
I guess you missed to store the value of input into x in the else block.And i removed the condition check in while as you're trying to make it an infinite loop till the condition is correct.
Hope this helps..!!
x = int(input("guess a number between 0 and 10: \n"))
y = random.randint(0,10)
while True:
if y == x:
print("Congratulations !! \n")
break;
else:
x = int(input("Try Again\n"))
If I give negative numbers this code does not function any more and I don't know how to stop it if I put for example a string or something that doesn't have sense. Help me please!!
def computeHCF(x,y):
if x>y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
while True:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))
continue;
else:
print("You write something that doesn't have any sense!")
You have to make python first check for strings in the input.
Then check for negative numbers,
If none of these two errors are present it goes ahead to run your code
But if they are let it exit before giving an error
Like so:
def computeHCF(x,y):
if type(x) is str or type(y) is str:
print("You wrote something that doesn't have any sense!")
exit()
elif x < 0 or y < 0 :
print("You wrote something that doesn't have any sense!")
exit()
elif x>y:
smaller = y
elif y<x:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
while True:
num1 = (input("Enter the first number: "))
num2 = (input("Enter the second number: "))
print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))
continue;
We can simulate what happens in your code when the result is not what we expect.
We noticed that if we insert a negative number, the program stops.
so let's assume num1 = -4 and num2 = 2
def computeHCF(x,y): # x = -4, y = 2
if x>y: # we don't meet this condition
smaller = y
else: # we meet this condition
smaller = x # smaller value is -4
for i in range(1, smaller+1): # there is nothing in range(1, -3)!!
# we do not enter here
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf # hcf value has never been retrived, so an error will be raised here
you can solve this problem in many ways, two of them are:
set hfc with a base value, so if the conditions in the for loop are not met, the base value will be returned:
def computeHCF(x,y):
hcf = None
this code will return:
('The H.C.F. of', -4, 'and', 2, 'is', None)
or by having the absolute value of x and y:
def computeHCF(x,y):
x = abs(x)
y = abs(y)
this code will return:
('The H.C.F. of', -4, 'and', 2, 'is', 2)
We also see that if we insert a string or something that can't be interpreted as an int, another error is raised.
This time, the error happens when you read the input:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
in this two lines, you convert anything that the user input to an int, but strings like "Hello World!" can't be converted into an int.
One of the many way to solve this problem, is to use try/except: you try to read the input as an int, but if an error occurs, you do something else.
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))
continue
except:
print("You write something that doesn't have any sense!")
continue
with this code, the result of the inputs "Hello" and "World!" will be:
"You write something that doesn't have any sense!"
you catch also the error generated by the function computeHCF(x,y) when x = 0 or y = 0.
At last, you can erase your last two lines, with the "else" statement. That else will be executed only when the condition of the while loop is False, but True is always True!
in the end, your code could be like:
def computeHCF(x,y):
x = abs(x)
y = abs(y)
# or hcf = None
if any([type(x)!=int,type(y)!=int]):
return hcf
if x>y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
while True:
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))
except:
print("You write something that doesn't have any sense!")
continue
enter an arbitrary sequence of integers at the keyboard, and then prints the number of positive even integers user enters.
def find_even_count():
count = 0
x = raw_input("Enter a value, or q to quit: ")
while (x != "q") and (x > 0):
for num in x:
if (int(x) % 2 == 0):
count += 1
entry = raw_input("Enter a value, or q to quit: ")
return count
I have gotten this so far but it is not working any ideas?
If you are counting them as they are entered there is no need to iterate.
def find_even_count():
count = 0
x = raw_input("Enter a value, or q to quit: ")
while (x != "q") and (x > 0):
if (int(x) % 2 == 0):
count += 1
x = raw_input("Enter a value, or q to quit: ")
return count
on the other hand if you had a sequence of numbers getting the number of evens is O(n) and can be written one pythonic line.
numberOfEvens = sum([1 if k%2==0 else 0 for k in sequence])
The problem is You are getting wrong input, in the Loop, You are Using different variable for second Input. Just change the Variable name inside the Loop as x there You Go.
def find_even_count():
count = 0
x = raw_input("Enter a value, or q to quit: ")
while (x != "q") and (int(x) > 0):
if (int(x) % 2 == 0):
count += 1
x = raw_input("Enter a value, or q to quit: ")
return count
In your code, the line entry = raw_input("Enter a value, or q to quit: ") might be causing issues. if you noticed, in kpie's code, the line is inline with the if statement. in your code it will only be executed if x is even. if x is odd, your code will loop forever. additionally, entry is never used, so, again, x won't change.