I'm a beginner to Python. I have written code to find the greatest of 3 numbers which is working fine other than these numbers 100,10,20 which are provided as input. I'm getting the output as "The largest number is 20" but my expectation is is should be "The largest number is 100"
My code is as follows:
a = input("Enter 1st value")
b = input("Enter 2nd value")
c = input("Enter 3rd value")
if (a > b) and (a > c):
lnum = a
elif (b > a) and (b > c):
lnum = b
else:
lnum = c
print("The largest number is", lnum)
Can anyone help me to understand why the output is showing 20 as greatest instead of 100?
Your variables are strings, you must convert them to ints like this:
a = int(input('Enter 1st value'))
a = input("Enter 1st value") stores string into a you should convert it into integer by using int() method.
a = int(input("Enter 1st value")) or try a= input("Enter 1st value") then a=int(a).
you have to convert your inputs to int:
a = input("Enter 1st value")
b = input("Enter 2nd value")
c = input("Enter 3rd value")
print("The largest number is", max(map(int, (a, b, c))))
You could do this easier with max(list) when you store your values in a list. Example:
values = []
values.append(int(input('Enter 1st value ')))
values.append(int(input('Enter 2st value ')))
values.append(int(input('Enter 3st value ')))
lnum = max(values)
print("The largest number is", lnum)
Your inputs are strings and are sorted by comparing the characters left to right.
Comparing "100" against "20" first compares "1" and "2". "1" is smaller so your code picks "20" as the larger value.
As others have mentioned if you convert the input to integer using int(input('Enter 1st value ') then it will work as you intended and there is a max() function you can use.
Note: There still is another mistake in your code:
Enter 1st value20
Enter 2nd value20
Enter 3rd value10
('The largest number is', 10)
The check for (b > a) is wrong and causes you to output c if a == b.
Related
a = [1,2,3,4,5,6]
print(a)
s=input("Enter a number from the list given \n")
if s in a:
print("the number given is", s)
else:
print("please select the number given in the list")
When I give 2 as input, the if statement is not being checked directly; the else part is printed. But if provide the value hardcoded in the program, the code is working as expected.
If my input is any number from the list, it should print that number. If not, the other part should be printed.
s=int(input("Enter a number from the list given \n"))
I believe
You are taking string as an input and not int. Try using
s = int(input("Some value")
You can change your if condition like this:
a = [1,2,3,4,5,6]
print(a)
s = input("Enter a number from the list given: ")
if s in set(str(e) for e in a):
print("the number given is", s)
else:
print("please select the number given in the list")
In this way you do not have to convert the user input to int which is fraught with problems if the value(s) entered cannot be converted to int.
An alternative is to use exception handling as follows:
a = [1, 2, 3, 4, 5, 6]
while True:
try:
print(a)
s = int(input("Enter a number from the list given: "))
if s in a:
print("the number given is", s)
break
else:
raise ValueError("please select the number given in the list")
except ValueError as ve:
print(ve)
I am writing a python code that returns me the larger of two inputs.
def bigger_num(a, b):
if a < b:
print ("First number is smaller than the second number.")
elif a > b:
print ("First number is greater than the second number.")
else:
print ("Two numbers are equals.")
a = input("Enter first number: ")
a = float(a)
b = input("Enter second number : ")
b = float(b)
print(bigger_num(a, b))
Result:
Enter first number: 19
Enter second number : 9
First number is greater than the second number.
None
How do I display the numeric result (a/b) in the print?
Ideal solution example: First number, 19 is greater than the second number
Also, is there a way to remove none from the print result?
You can use the format() method or simply concatenate the number to display it. To remove the None, just call the function without the wrapping it with a print() because you print the output inside the function
def bigger_num(a, b):
if a < b:
print ("First number, {0} is smaller than the second number.".format(a))
elif a > b:
print ("First number, {0} is greater than the second number.".format(a))
else:
print ("Two numbers are equals.")
a = input("Enter first number: ")
a = float(a)
b = input("Enter second number : ")
b = float(b)
bigger_num(a, b)
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 want to perform this:
Read two integers from STDIN and print three lines where:
The first line contains the sum of the two numbers.
The second line contains the difference of the two numbers (first - second).
The third line contains the product of the two numbers.
Can someone help me on this?
Start slow and break it down
# Get your data from the user, use input
num_one = input("Please enter the first number: ")
num_two = input("Please enter the second number: ")
# Create the sum, diff, and product, casting as integer
sum = int(num_one) + int(num_two)
diff = int(num_one) - int(num_two)
product = int(num_one) * int(num_two)
# Print each output casting as a string since we can't concatenate a string to an integer
print("The sum is: "+str(sum))
print("The difference is: "+str(diff))
print("The product is: "+str(product))
Now you should also do some error checking here incase the user doesn't enter anything:
# Get your data from the user, use input
num_one = input("Please enter the first number: ")
num_two = input("Please enter the second number: ")
if(num_one == "" or num_two == ""):
print("You did not enter enter two numbers. Exiting...")
exit
else:
# Create the sum, diff, and product, casting as integer
sum = int(num_one) + int(num_two)
diff = int(num_one) - int(num_two)
product = int(num_one) * int(num_two)
# Print each output casting as a string since we can't concatenate a
string to an integer
print("The sum is: "+str(sum))
print("The difference is: "+str(diff))
print("The product is: "+str(product))
Python 2.7
raw_input to read the input, int to convert string to integer, print to print the output
a = int(raw_input("numebr 1: "))
b = int(raw_input("numebr 2: "))
print a + b
print a - b
print a * b
Python 3.7
input to read the input, int to convert string to integer, print to print the output
a = int(input("numebr 1: "))
b = int(input("numebr 2: "))
print (a + b)
print (a - b)
print (a * b)
a = int(input())
b = int(input())
from operator import add, sub, mul
operators = [add, sub, mul]
for operator in operators:
print(operator(a, b))
I'm writing for creating a list of number from input and get the average of the list. The requirement is: when the user enters a number, the number will be appended to the list; when the user press Enter, the input section will stop and conduct and calculation section.
Here is my code:
n = (input("please input a number"))
numlist = []
while n != '':
numlist.append(float(n))
n = float(input("please input a number"))
N = 0
Sum = 0
for c in numlist:
N = N+1
Sum = Sum+c
Ave = Sum/N
print("there are",N,"numbers","the average is",Ave)
if I enter numbers, everything works fine. But when I press Enter, it shows ValueError. I know the problem is with float(). How can I solve this?
You don't need the float() around the input() function inside your loop because you call float() when you append n to numlist.
this should solve ur prob ,by adding a try,catch block around ur print statement
n = (input("please input a number"))
numlist = []
while True :
numlist.append(float(n))
#####cath the exception and break out of
try :
n = float(input("please input a number"))
except ValueError :
break
N = 0
Sum = 0
for c in numlist:
N = N+1
Sum = Sum+c
Ave = Sum/N
print("there are",N,"numbers","the average is",Ave)