How to use a for loop with input function - python

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))

Related

stuck on float manipulation task

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

TypeError: can only concatenate str (not "float")

I'm trying to make a program that prints the area, perimeter, and diagonal of a rectangle I am analyzing.
This is the part of the code that is returning an error:
number2 = int(input(" Enter Width: "));
print("The area of the rectangle: " + str(number1 * number2));
print("The perimeter of the rectangle: " + str(number1 * 2 + number2 *2));
import math
print("The length of the diagonal: " + math.sqrt(number1**2 + number2**2))
The error which I am receiving:
TypeError Traceback (most recent call last)
<ipython-input-4-09f680f30f33> in <module>
7 import math
8
----> 9 print("The length of the diagonal: " + math.sqrt(number1**2 + number2**2))
TypeError: can only concatenate str (not "float") to str
math.sqrt returns a float, which you are trying to append to the string "The length of diagonal:". Here a couple of options
Use args of print()
print("The length of the diagonal:", math.sqrt(number1**2 + number2**2))
Format the result of math.sqrt
print("The length of the diagonal: {}".format(math.sqrt(number1**2 + number2**2))
Use a formatted string
either old way:
print("The length of the diagonal: {0}".format(math.sqrt(number1**2 + number2**2)))
Note that the 0 is not required in this case but can be used to specify the index in the arg tuple to .format().
or using the newer f-string:
print(f"The length of the diagonal: {math.sqrt(number1**2 + number2**2)}")

How do I multiply from a input variable?

I am having trouble figuring out how to multiply my users input.
I have tried changing the functions of the variables for 'int' to 'float' and to 'str' but i cant seem to figure it out. My code:
pops = input("Enter your favorite pop: ")
cost = input("Enter how much they cost: ")
how_many = input("Enter how many pops you have: ")
print('My favorite pop is ' + pops + '!')
print('They cost about ' + cost + ' dollars.')
print('I have about ' + how_many + ' pops!')
result = str(cost) * str(how_many)
print("You have spent over " + result + " dollars on pops!")
I've got next error:
result = str(cost) * str(how_many)
TypeError: can't multiply sequence by non-int of type 'str'
First of all, I highly recommend you to start with some guides/tutorials or at least read official python docs to get in touch with language basics.
Regarding your problem. I'll show you basic algorithm how to use official docs to find solution.
Let's check docs of input() function.
The function then reads a line from input, converts it to a string, and returns that.
Strings in python are represented as str. So, after execution of input() variables pops, cost and how_many contains str values.
In your code you're using str() function. Let's check in docs what does this function perform:
Return a str version of object.
Now you understand that expressions str(cost) and str(how_many) convert str to str which means .. do nothing.
How to multiply values from input?
You need to multiply two values, which requires converting str to one of numeric types.
For cost we will use float, cause it can contain fractional number. For how_many we can use int cause count normally is integer. To convert str to numbers we will use float() and int() functions.
In your code you need just edit line where error occurred and replace useless call of str() with proper functions:
result = float(cost) * int(how_many)
Result of multiplication float and int will be float.
How to print result?
Code you're using will throw an error, cause you can't sum str and float. There're several ways how to print desired message:
Convert result to str.
It's the most obvious way - just use str() function:
print("You have spent over " + str(result) + " dollars on pops!")
Use features of print() function:
In docs written:
print( *objects, sep=' ', end='\n', file=sys.stdout, flush=False )
Print objects to the text stream file, separated by sep and followed by end.
As we see, default separator between objects is space, so we can just list start of string, result and ending in arguments of print() function:
print("You have spent over", result, "dollars on pops!")
String formatting.
It's very complex topic, you can read more information by following provided link, I'll just show you one of methods using str.format() function:
print("You have spent over {} dollars on pops!".format(result))
You are trying to multiply two strings.
You should multiply like this:
result = float(cost) * int(how_many)
But don't forget to reconvert the result to string in the last line or it will give you another error (TypeError in this case)
print("You have spent over " + str(result) + " dollars on pops!")
str(item) converts item to a string. Similarly, float(item) converts item to a float (if possible).
The code:
result = float(cost) * int(how_many)
will not produce the same error as you indicated occurred, but may introduce a ValueError, if the input given is not what you are expecting.
Example:
a = "b"
float(a)
Output
ValueError: could not convert string to float: 'b'
result = int(cost) * int(how_many) can fix the issue. Cost and how_many are non-numeric and converting them to int gives the desired output.
pops = input("Enter your favorite pop: ")
cost = input("Enter how much they cost: ")
how_many = input("Enter how many pops you have: ")
print('My favorite pop is ' + pops + '!')
print('They cost about ' + cost + ' dollars.')
print('I have about ' + how_many + ' pops!')
result = float(cost) * int(how_many)
print("You have spent over " + str(result) + " dollars on pops!")
The problem is that you are trying to convert the cost to a string, conversion from one type to another except when using the bool() is illegal. That is why the program is raising a TypeError.
pops = input("Enter your favorite pop: ")
cost = input("Enter how much they cost: ")
how_many = input("Enter how many pops you have: ")
print('My favorite pop is ' + pops + '!')
print('They cost about ' + cost + ' dollars.')
print('I have about ' + how_many + ' pops!')
result = cost * how_many
print("You have spent over " + result + " dollars on pops!"

Python: Calling a function called read_min_max

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

Simple Python Print Command Giving Unsupported Type Error

No clue why but this simple Python code is giving me an error:
'''
Created on Aug 2, 2017
#author: Justin
'''
x = int(input("Give me a number, now....."))
if x % 2 != 0:
print(x + " is an odd number!")
else:
print(x + " is an even number!")
The error is saying:
Traceback (most recent call last):
File "C:\Users\Justin\Desktop\Developer\Eclipse Java Projects\PyDev Tutorial\src\Main\MainPy.py", line 9, in <module>
print(x + " is an odd number!")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Please help!
Thanks!
You need to convert x into str while printing.
print(str(x) + " is an odd number!")
Or better you can use formatting
print('{} is an odd number'.format(x))
You cannot add an integer to a string. You can however, add a string to a string. Cast x to a string before you add it:
print(str(x) + " is an odd number!")
you need to concatenate string into string . but x is an integer so before concatenate you need to convert it into string... are use below concatenate method...
try this,
print("{} is an odd number!".format(x))
You need to convert int to str.
You should better use new formatting in python:
print("{} is an odd number!".format(x))
you can concatenate string + string not string + int
in your code x is int type so you can't add directly with string, you have to convert into the string with str keyword
x = int(input("Give me a number, now....."))
if x % 2 != 0:
print(str(x) + " is an odd number!")
else:
print(str(x) + " is an even number!")

Categories

Resources