Modify code to accept any real numbers(integer or float) - python

I can figure out how to make this code accept float points as well as integers.
What this code does is it: Accepts an unlimited amount of user inputs, must as non-negative integers. when a blank line is detected the input ends.
The code; prints the list in ascending order. prints a total of all the numbers and then prints the average number.
code:
nums = []
response = " "
total = 0
print("Type a positive integer: ")
while response != "":
response = input()
if response.isnumeric():
nums.append(int(response))
print("Next number: ")
elif response == '':
break
else:
print("Error, you have to type a non-negative integer.")
nums.sort()
for item in nums:
total = total + item
if nums != []:
print("The numbers in order: ",nums)
print("Total number: ",total)
print("The average is",sum(nums) / len(nums))
else:
print("There are no numbers in the list")

The line:
nums.append(int(response))
is casting your string input to integerss. Simply change it to:
nums.append(float(response))

If you want it to take integers as well as floats then you need to remove the cast entirely:
nums.append(response)

If you want to append integers as int and floats as float, you can use :
nums.append(float(response) if "." in number else int(response))

The float class has an .is_integer() function:
buf = float(response)
if buf.is_integer():
buf = int(buf)
nums.append(buf)

Related

Python code is not running correctly to measure length of strings

my python code is not running correctly, I wrote a code that could measure the length of strings, but when I entered an integer or float number the result was that he measured the length of the number, which is not correct .
Here is my code :
def Names_to_length(Names):
return(len(Names))
Names = (input("Enter = "))
if type(Names) == str :
print("Sorry, integers don't have length")
else:
print(Names_to_length(Names))
Can you help ?
input will return a str - you'll have to check if it's numeric / float. Here is one way of doing it:
def isfloat(num):
try:
float(num)
return True
except ValueError:
return False
def Names_to_length(Names):
return(len(Names))
Names = (input("Enter = "))
if Names.isnumeric() or isfloat(Names):
print("Sorry, numbers don't have length")
else:
print(Names_to_length(Names))

Determining the two largest numbers from user input

I've been working on a small program to learn more about Python, but I'm stuck on something.
Basically, the user has to input a sequence of positive integers. When a negative number is entered, the program stops and tells the user the two largest integers the user previously inputted. Here is my code:
number = 1
print("Please enter your desired integers. Input a negative number to end. ")
numbers = []
while (number > 0):
number = int(input())
if number < 0:
break
largestInteger = max(numbers)
print(largestInteger)
integers.remove(largestInteger)
largestInteger2 = max(numbers)
print(largestInteger2)
There are two issues with your code:
You need to update the list with the user input for every iteration of the while loop using .append().
integers isn't defined, so you can't call .remove() on it. You should refer to numbers instead.
Here is a code snippet that resolves these issues:
number = 1
print("Please enter your desired integers. Input a negative number to end. ")
numbers = []
while number > 0:
number = int(input())
if number > 0:
numbers.append(number)
largestInteger = max(numbers)
print(largestInteger)
numbers.remove(largestInteger)
largestInteger2 = max(numbers)
print(largestInteger2)
I would build a function that would call itself again if the user enters a number larger or equal to 0, but will break itself and return a list once a user inputs a number smaller than 0. Additionally I would then sort in reverse (largest to smallest) and call only the first 2 items in the list
def user_input():
user_int = int(input('Please enter your desired integers'))
if user_int >= 0:
user_lst.append(user_int)
user_input()
else:
return user_lst
#Create an empty list
user_lst = []
user_input()
user_lst.sort(reverse=True)
user_lst[0:2]
You forgot to append the input number to the numbers list
numbers = []
while (True):
number = int(input())
if number < 0:
break
numbers.append(number)
print("First largest integer: ", end="")
largestInteger = max(numbers)
print(largestInteger)
numbers.remove(largestInteger)
print("Second largest integer: ", end="")
largestInteger2 = max(numbers)
print(largestInteger2)```
The above code will work, according to your **desire**

How to use a for-loop/range to end a specific character input in Python?

If user entered anything other than an integer it should be ignored, whereas, if it were to be an integer it should be added to the lst (list)
the function should display the list of integers, ignoring anything that wasn't an integer and display the max and min number.
lst = []
n = int(input("Enter Integers: "))
for index in range(min(n), max(n)):
if index == ' ':
return
for i in range(min(n),max(n)):
elements = int(input())
lst.append(elements)
print(lst)
print(len(lst))
for num in lst:
if num % 2 == 0:
print(num, end= ' ')
I have a function here that prompts users to enter a list of integers, if SPACE is inputted: it should END the input.
I'm quite new at python and not sure how to go about this code.
The expression
input("Enter Integers: ")
evaluates to a string. Since you want to read strings until a space is inserted, you need a infinite loop:
numbers = []
while True:
value = input("Enter an integer: ")
If the user provides a space, stop reading numbers:
numbers = []
while True:
value = input("Enter an integer: ")
if value == ' ':
# Exit the loop
break
If you want to convert it to an integer, use the int function and append it to numbers:
numbers = []
while True:
value = input("Enter an integer: ")
if value == ' ':
break
numbers.append(int(value))
You can also add a validation, if the user provides a value that isn't a number:
numbers = []
while True:
value = input("Enter an integer: ")
if value == ' ':
break
try:
number = int(value)
except ValueError:
print('The value is not a number!')
# Continue looping
continue
numbers.append(number)
Your code there is somewhat misleading and adds confusion to the question. My solution below is based off the question before the code.
lst = []
print("Enter Integers:")
while True:
n = input()
try:
# Try converting to an int, if can't ignore it
lst.append(int(n))
except ValueError:
pass
# If space input, break the loop
if n == ' ':
break
print("Integer list: ")
print(lst)
if len(lst) > 0:
print("Min: " + str(min(lst)))
print("Max: " + str(max(lst)))

why different digit number won't work in this python code?

I try to use python to prompt user to enter different number, and keep the largest one, and finish when user enter "done". but I find out it can not work with different digit of number. for example, 1st entry: 91, 2nd:94, it will run well. but 1st entry:91 and 2nd:100, it can not record 100 as the largest number. did somebody know what's going on? thank you so much!
code:
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
if num == "done":
break
try: int (num)
except:
print "Please enter a numeric number"
if largest is None and smallest is None:
largest = num
smallest = num
#print "l", largest
#print "s", smallest
if num > largest:
largest = num
print largest, num
#if num < smallest:
# smallest = num
# print "s2", smallest
print num
print "Maximum is ", largest
#print "Minimum is ", smallest
you're doing ASCII comparisons, not numeric. you need to actually assign something like number = int(num) and use number for comparison.
The problem is you're not converting num to an integer, so it's using string comparison rather than numeric comparison. Change:
try: int (num)
to:
try:
num = int(num)
You've got a number of problems. Take a look at this, maybe you can incorporate it into your own code?
largest = 0
while True:
prompt = raw_input("Enter a number: ")
try:
num = int(prompt)
if num > largest:
largest = num
except:
if prompt == 'done':
break
print largest
raw_input returns a string. So when you compare num > largest you are using string (alphabetical) comparison. You want to compare numbers. The easiest way would be to simply rewrite the comparion to int(num) > int(largest).
try: int (num) ... already checks if the input is a number but it does not change the value of the variable.
Note: except without an exception type is generally not a good idea. You should explicitly write down the exception you want to catch: ValueError

Finding largest and smallest number where user inputs numbers using a loop

I am creating a program where I am asking the user to input numbers using a loop (not function).
I need to assume the numbers are floating.
User will continue to input numbers until they hit the enter key a second time.
Then the program will generate the largest number, smallest number, sum of the list and average number.
I've figured everything out but when I type in a number 10 or larger, the program doesn't identity it as the largest. In fact, I noticed that 10 is considered the smallest number.
Also I'm not able to convert the numbers in floating numbers.
myList = []
done = False
while not done:
enterNumber = raw_input("Enter a number (press Enter key a second time to stop): ")
nNumbers = len(myList)
if enterNumber == "":
done = True
break
else:
myList.append(enterNumber)
print "You've typed in the following numbers: " + str(myList)
smallest = 0
largest = 0
for nextNumber in myList:
if smallest == 0 or nextNumber < smallest:
smallest = nextNumber
for nextNumber in myList:
if largest == 0 or largest < nextNumber:
largest = nextNumber
print "Largest number from this list is: " + largest
print "Smallest number from this list is: " + smallest
sum = 0
for nextValue in myList:
sum = sum + float(nextValue)
print "The sum of all the numbers from this list is: " + str(sum)
average = float(sum/nNumbers)
print "The average of all the numbers from this list is: " + str(average)
This tells me that you are probably not comparing what you think :)
Your code is mostly correct, except for the fact that you never told python what the "type" of the user input was. I am guessing python assumed the user entered a bunch of strings, and in the string world - "10" < "9"
So in your code, force the type of "enterNumber" to be a float before adding it to your list of floats like so:
while not done:
enterNumber = raw_input("Enter a number (press Enter key a second time to stop): ")
nNumbers = len(myList)
if enterNumber == "":
done = True
break
else:
myList.append(float(enterNumber))
you need to convert it before you add it to your list
enterNumber = raw_input("Enter a number (press Enter key a second time to stop): ")
nNumbers = len(myList)
if enterNumber == "":
done = True
break
else:
myList.append(float(enterNumber)) # convert it here...
#you may want to check for valid input before calling float on it ...
but my favorite way to get a list of numbers is
my_numbers = map(float,
iter(lambda:raw_input("Enter a number or leave blank to quit").strip(),""))

Categories