I am very new to coding. I need to convert a c++ program "guess that number" to python and I am stuck on one area. Any help would be much appreciated.
If the user enters anything outside the range of 1 to 100, they should receive a message that says "Please enter a number between 1 and 100.
I have this within a function called read_min_max but I am having errors when I call this function.
This is the function
def read_min_max(prompt, min, max):
result = read_integer(prompt)
while (result < min or result > max ):
print("Please enter a number between ", + (min), + " and ", + (max))
result = read_integer(prompt)
return result
This is how I call this function:
number_guessed = read_min_max("Please enter a valid number: ", 1 , 100)
This is the error
line 16, in read_min_max
print("Please enter a number between ", + (min), + " and ", + (max))
TypeError: bad operand type for unary +: 'str'
The problem is that you use both commas and pluses to print what you want to print. You could solve it by either removing the commas and making min and max strings, or remove the pluses and the brackets around min and max
So either:
def read_min_max(prompt, min, max):
result = read_integer(prompt)
while (result < min or result > max ):
print("Please enter a number between ", min, " and ", max)
result = read_integer(prompt)
return result
or:
def read_min_max(prompt, min, max):
result = read_integer(prompt)
while (result < min or result > max ):
print("Please enter a number between " + str(min) + " and " + str(max))
result = read_integer(prompt)
return result
Related
this is the task im busy with:
Write a program that starts by asking the user to input 10 floats (these can
be a combination of whole numbers and decimals). Store these numbers
in a list.
Find the total of all the numbers and print the result.
Find the index of the maximum and print the result.
Find the index of the minimum and print the result.
Calculate the average of the numbers and round off to 2 decimal places.
Print the result.
Find the median number and print the result.
Compulsory Task 2
Follow these steps:
Create
this is what i have but getting the following error:
ValueError: invalid literal for int() with base 10:
CODE:
user_numbers = []
#input request from user
numbers = int(input("Please enter a list of 10 numbers (numbers can be whole or decimal):"))
for i in range(0,numbers):
el = float(input())
user_numbers.append(el)
print("Your list of 10 numbers:" + str(user_numbers))
you can refer to the solution :
user_numbers = []
#input request from user
numbers = list(map(float, input().split()))
print("total of all the numbers : " + str(sum(numbers)))
print("index of the maximum : " + str(numbers.index(max(numbers)) + 1))
print("index of the minimum : " + str(numbers.index(min(numbers)) + 1))
print("average of the numbers and round off to 2 decimal places : " + str(round(sum(numbers)/len(numbers),2)))
numbers.sort()
mid = len(numbers)//2
result = (numbers[mid] + numbers[~mid]) / 2
print("median number :" + str(result))
let me know if you have any doubts.
Thanks
So I'm writing a basic program, and part of the output is to state the lowest and highest number that the user has entered. For some reason, the min and max are correct some of the time, and not others. And I can't figure out any pattern of when it's right or wrong (not necessarily when lowest number is first, or last, etc). Everything else works perfectly, and the code runs fine every time. Here is the code:
total = 0
count = 0
lst = []
while True:
x = input("Enter a number: ")
if x.lower() == "done":
break
if x.isalpha():
print("invalid input")
continue
lst.append(x)
total = total + int(x)
count = count + 1
avg = total / count
print("The total of all the numbers your entered is: " + str(total))
print("You entered " + str(count) + " numbers.")
print("The average of all your numbers is: " + str(avg))
print("The smallest number was: " + str(min(lst)))
print("The largest number was: " + str(max(lst)))
Any ideas? Keep in mind I'm (obviously) pretty early on in my coding study. Thanks!
If, at the end of your program, you add:
print("Your input, sorted:", sorted(lst))
you should see the lst in the order that Python thinks is sorted.
You'll notice it won't always match what you think is sorted.
That's because you consider lst to be sorted when the elements are in numerical order. However, the elements are not numbers; when you add them to lst, they're strings, and Python treats them as such, even when you call min(), max(), and sorted() on them.
The way to fix your problem is to add ints to the lst list, by changing your line from:
lst.append(x)
to:
lst.append(int(x))
Make those changes, and see if that helps.
P.S.: Instead of calling str() on all those integer values in your print statements, like this:
print("The total of all the numbers your entered is: " + str(total))
print("You entered " + str(count) + " numbers.")
print("The average of all your numbers is: " + str(avg))
print("The smallest number was: " + str(min(lst)))
print("The largest number was: " + str(max(lst)))
you can take advantage of the fact that Python's print() function will print each argument individually (separated by a space by default). So use this instead, which is simpler and a bit easier to read:
print("The total of all the numbers your entered is:", total)
print("You entered", count, "numbers.")
print("The average of all your numbers is:", avg)
print("The smallest number was:", min(lst))
print("The largest number was:", max(lst))
(And if you want to, you can use f-strings. But you can look that up on your own.)
You convert your input to int when you are adding it to the total, but not when you are finding the min and max.
When given strings, min and max return values based on alphabetical order, which may sometimes happen to correspond to numerical size, but in general doesn't.
All you need to do is to append input as ints.
total = 0
count = 0
lst = []
while True:
x = input("Enter a number: ")
if x.lower() == "done":
break
if x.isalpha():
print("invalid input")
continue
lst.append(int(x)) # this should fix it.
total = total + int(x)
count = count + 1
avg = total / count
You might also want to use string formatting to print your answers:
print(f"The total of all the numbers your entered is: {total}")
print(f"You entered {count} numbers.")
print(f"The average of all your numbers is: {avg}")
print(f"The smallest number was: {min(lst)}")
print(f"The largest number was: {max(lst)}")
I simply have to make a sum of three numbers and calculate the average
import sys
sums=0.0
k=3
for w in range(k):
sums = sums + input("Pleas input number " + str(w+1) + " ")
print("the media is " + str(sums/k) + " and the Sum is " + str(sums))
And the error :
Pleas input number 1 1
Traceback (most recent call last):
File "/home/user/Python/sec001.py", line 5, in <module>
sums = sums + input("Pleas input number " + str(w+1) + " ");
TypeError: unsupported operand type(s) for +: 'float' and 'str'
Why not do the simple version then optimize it?
def sum_list(l):
sum = 0
for x in l:
sum += x
return sum
l = list(map(int, input("Enter numbers separated by spaces: ").split()))
sum_list(l)
Your problem was that you were not casting your input from 'str' to 'int'. Remember, Python auto-initializes data types. Therefore, explicit casting is required. Correct me if I am wrong, but that's how I see it.
Hope I helped :)
The input() function returns a string(str) and Python does not convert it to float/integer automatically. All you need to do is to convert it.
import sys;
sums=0.0;
k=3;
for w in range(k):
sums = sums + float(input("Pleas input number " + str(w+1) + " "));
print("the media is " + str(sums/k) + " and the Sum is " + str(sums));
If you want to make it even better, you can use try/except to deal with invalid inputs. Also, import sys is not needed and you should avoid using semicolon.
sums=0.0
k=3
for w in range(k):
try:
sums = sums + float(input("Pleas input number " + str(w+1) + " "))
except ValueError:
print("Invalid Input")
print("the media is " + str(sums/k) + " and the Sum is " + str(sums))
input returns a string and you need to create an int or float from that. You also have to deal with the fact that users can't follow simple instructions. Finally, you need to get rid of those semicolons - they are dangerous and create a hostile work environment (at least when you bump into other python programmers...!)
import sys
sums=0.0
k=3
for w in range(k):
while True:
try:
sums += float(input("Pleas input number " + str(w+1) + " "))
break
except ValueError:
print("That was not a number")
print("the media is " + str(sums/k) + " and the Sum is " + str(sums))
The getvalidint function is explained below, as I am calling the function getvalidint and giving it a input so it may produce an integer output. It is not as I print the functions output(see below in the main program) it prints out "none", I am running on python33.
#getValidInt() takes in a minn and maxx, and gets a number from the
# user between those two numbers (inclusive)
#Input: minn and maxx, two integers
#Output: an integer, between minn and maxx inclusive
MIN_VAL = -1000000
MAX_VAL = 1000000
def getValidInt(minn, maxx):
message = "Please enter a number between " + str(minn) + " and " + \
str(maxx) + " (inclusive): "
newInt = int(input(message))
while newInt <= minn & newInt >= maxx:
# while loop exited, return the user's choice
return newInt
def main():
userNum = getValidInt(MIN_VAL, MAX_VAL)
print(userNum)
main()
If the while newInt <= minn & newInt >= maxx: condition is never met, then nothing will be returned. This means that the function will implicitly return None. Also, assuming you're using python 3 (which I induced from your int(input()) idiom).
The deeper issue is that the input code will only run once, regardless of whether or not the value meets the constraint. The typical way of doing this would be something along the lines of:
import sys
def get_int(minimum=-100000, maximum=100000):
user_input = float("inf")
while user_input > maximum or user_input < minimum:
try:
user_input = int(input("Enter a number between {} and {}: ".format(minimum, maximum)))
except ValueError:
sys.stdout.write("Invalid number. ")
return user_input
I've just started with Python (3.x), and while it is fairly easy to pick up, I'm trying to learn how to work with lists.
I've written a small program which asks for the amount of numbers to input, then asks for the numbers. Where I'm scratching my head a little is here;
t += numList[int(i)]
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
I'm sure it's obvious to someone else. I thought that lists used an integer index? And that referencing that index would return the contents?
(I have a C++ background, so I'm finding that some things don't work how I thought they would).
Full program here;
runLoop = True
numList = []
def avg():
t = 0
i = 0
while i < len(numList):
t += numList[i]
i += 1
print (" total is " + str(t))
while runLoop == True:
maxLen = int(input("Average Calculator : "
"Enter the amount of number "
"to calculate for"))
while len(numList) < maxLen:
numList.append(input("Enter number : "))
avg()
if input("Would you like to run again? (y/n) ") == "n":
quit()
Type casting:
Type casting is missing in following statement
numList.append(input("Enter number : "))
e.g. Use input() method for python 3.x
>>> a = raw_input("Enter number:")
Enter number:2
>>> type(a)
<type 'str'>
>>> b = int(a)
>>> type(b)
<type 'int'>
>>>
Add Integer type variable with Integer type variable: This will raise exception at t += numList[i] statement because we are adding integer variable with string variable, it is not allowed.
e.g.
>>> 1 + "1"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
No need to check length of list in while loop while i < len(numList):. We can iterate directly on list.
e.g.
>> numList = [1,4,10]
>>> total = 0
>>> for i in numList:
... total += i
...
>>> print total
15
>>>
Inbuilt sum() function: We can use inbuilt function sum() to get from list.
e.g.
>>> numList = [1,4,10]
>>> sum(numList)
15
>>>
Exception handling: It is good programming to handle exception on user input. Use exception handling during type casting. If user enters any non integer number and we are type casting that non integer string into integer that time python interpreter raise ValueError.
e.g.
>>> try:
... a = int(raw_input("Enter Number:"))
... except ValueError:
... print "Wrong number. Enters only digit."
...
Enter Number:e
Wrong number. Enters only digit.
Thanks to Vivik for the answer.
I have now adjusted my simple program and solved the issue I had; code as follows.
runLoop = True
numList = []
def avg(workList):
t = sum(workList)
print ("Average is " + str(t/len(workList)) )
print ("Total is " + str(t) )
while runLoop == True:
maxLen = int(input("Average Calculator : "
"Enter the amount of number "
"to calculate for : "))
while len(numList) < maxLen:
numList.append(int(input("Enter number : ")))
avg(numList)
if input("Would you like to run again? (y/n) ") == "n":
quit()
I can see that I could quite easily shorten it down to;
runLoop = True
numList = []
while runLoop == True:
maxLen = int(input("Average Calculator: Enter the amount of number to calculate for : "))
while len(numList) < maxLen:
numList.append(int(input("Enter number : ")))
print ("Average is " + str(sum(numList)/len(numList)) )
print ("Total is " + str(sum(numList)) )
if input("Would you like to run again? (y/n) ") == "n":
quit()
But, the point of my little !/pointless exercise was to explore the relationships of lists, input to lists, and printing lists.
Cheers!