simple Python code to request numbers and print the result - python-3.x

I have been practicing the basics now i am try to do a practice task in uni and i can't seem to find where i am going wrong can anyone point me in the right direction and explain to me what i am doing wrong please , thank you
this is the question
Write some Python code that requests 2 numbers and prints the result of applying the operators + - * / eg.
Please enter your first number:5
Please enter your second number:3
5 + 3 = 8
5 – 3 = 2
5 * 3 = 15
5 / 3 = 1.666666667
Test this code with at least ten different values. (Hint:You may need to think about how you manage the types)
and this is my coding
A= input ("Please enter your first number:")
B= input ("please enter your second number:")
A+B
A-B
A*B
A/B
and i get an error message saying
Please enter your first number:5
please enter your second number:3
Traceback (most recent call last):
File "/Users/salv/Documents/PRACTISE PYTHIN.py", line 6, in <module>
A-B
TypeError: unsupported operand type(s) for -: 'str' and 'str'
>>>

Input will return a string object, and the - operator expects two integers. Cast it to an int with int()
i.e.
A = int(input("Please enter your first number:"))

This happens because when python reads some user input, it reads it as a string (of type str), not as a number (of type int in this case).
So what you need to do is to convert the string representation of the number you entered, into a numeric type. This can be done by calling int() on your string as follows:
users_input = input("Enter a number: ")
A = int(users_input)
Consider this:
>>> A = input("Enter a number: ")
Enter a number: 5
>>> A
'5'
Notice the quotes around 5. This indicates that it's a string. You could confirm this with the use of type
>>> type(A)
<class 'str'>
>>> B = int(A)
>>> B
5
Note: no quotes around 5. It's a numeric type. Since it isn't followed by a .0, it's not a float (floating point decimal type). Rather, it is an int (integer type). Again, this can be confirmed with type
>>> type(B)
<class 'int'>

Related

How to print a horizontal row of numbers with user input in python

I need to write a program that asks the user to enter a number
n, where -6 < n < 93.
output: Enter the start number: 12
12 13 14 15 16 17 18
The numbers need printed using a field width of 2 and are right-justified. Fields need separated by a single space. There should be no spaces after the final field.
This is my code so far:
a = eval(input('Enter the start number : ',end='\n'))
for n in range(a,a+7):
print("{0:>2}").format(n)
print()
But it says:
File "C:/Users/Nathan/Documents/row.py", line 5, in <module>
a = eval(input('Enter the start number : ',end='\n'))
builtins.TypeError: input() takes no keyword arguments
Please help
First of all, the input function returns a string. You should cast it as integer.
Also you have some syntax error, to name a few:
You put .format after print, but it should be inside the print and after the string.
The input function doesn't take an end argument. And python gives you this error for that: TypeError: input() takes no keyword arguments
The formatting pattern is not right.
This code does what you want:
a = int(input('Enter the start number between -6 and 93: '))
assert (n >= -6) and (n <= 93), f"number must be in [-6, 93]," \
f"but got {n} instead"
for n in range(a, a+7):
print(f"{n:02d}", end=' ')
OUTPUT:
Enter the start number : 12
12 13 14 15 16 17 18
You can't pass \n to input beacouse is a special character.
If you want a white line add another print() after the input.
input() doesn't take the end argument, only print() does.
Solution
# input(): takes the input from the user, that will be in the form of string
# rstrip(): will remove the white spaces present in the input
# split(): will convert the string into a list
# map(function, iterable) : typecast the list
ar = list(map(int, input().rstrip().split()))
print(ar)
output:
1 2 3 4
[1, 2, 3, 4]

Calculation raises error "Can't multiply sequence by non-int of type 'float'"

So, I want to write a program with python 3 where it can help users calculate the circumference of a circle and sphere. So far this is what I have.
pi = 3.14159
value = input("Enter the value of your radius:")
circ = 2*pi*value
print(circ)
But, it keeps saying "can't multiply sequence by non-int of type 'float'". How do I fix this? And, how do I make the input as numbers only? Thank you.
try
value = float(input("Enter the value of your radius: "))
Note that this will throw an error if the input isn't a number.
Also, while you cant control what they input, you could just keep asking for a number if they type anything else like this:
while True:
try:
value = float(input("Enter the value of your radius: "))
except ValueError:
print("Please enter a number")
Running your program as-is reports
bash-3.2$ python3 test.py
Enter the value of your radius:10
Traceback (most recent call last):
File "test.py", line 3, in <module>
circ = 2*pi*value
TypeError: can't multiply sequence by non-int of type 'float'
The problem is value contains a string after the input returns
and python is trying to multiply a float (2*pi) and the string (character sequence value).
To correct this you probably want to convert value to a float before the multiplication.
e.g.
pi = 3.14159
value = input("Enter the value of your radius:")
circ = 2*pi*float(value)
print(circ)
Sample run with this change
bash-3.2$ python3 test.py
Enter the value of your radius:10
62.8318

Convert number string to number using python 3.6+

I have got the value from database 350,000,000.00 now I need to convert it to 350000000.
Please provide a solution on this using Python 3.6+ version
Thanks
Let the input be in a variable, say
a="350,000,000.00"
Since, the digits are comma , separated, that needs to be removed.
a.replace(",","")
>>> 350000000.00
The resultant string is a float. When we directly convert the string to integer, it will result in an error.
int(a.replace(",",""))
>>>Traceback (most recent call last):
File "python", line 2, in <module>
ValueError: invalid literal for int() with base 10: '350000000.00'
So, convert the number to float and then to int.
int(float(a.replace(",","")))
>>>350000000
Store the value in a variable and then parse it with int(variable_name)
eg. If you store the value in variable a, just write
int(float(a))
def convert(a):
r = 0
s = a.split(".")[0]
for c in s.split(","):
r = r * 1000 + int(c)
return r
s = convert("350,000,000.00")

Python- Validating User Input

My code needs to validate user input to make sure they enter a number and keep looping until they enter a number.
My code:
user_input=input("Enter a number: ")
while user_input != int:
user_input=input("Error: Enter a number: ")
My Output:
Enter a number: d
Error: Enter a number: f
Error: Enter a number: 5
Error: Enter a number: 5
Error: Enter a number: 3
Why doesnt it even accept numbers?
Answer
I think the piece of code below solves your problem in a way that is easily understood.
user_input = input("Enter a number: ")
while not user_input.isnumeric():
user_input = input("Error: Enter a number: ")
Explanation
The code you have didn't work because of while user_input != int.
When you call the input function, and the user provides an input, that input is always a string.
>>> num = input('Enter a number: ') # 5, as a string
>>> num
'5'
Your intent is to check if num is a number. So, to check if a string represents some number, you can use the str.isdigit(), str.isdecimal(), and str.isnumeric() methods. You can read more here.
It's easy to mistakenly believe the following approach is viable, but it can quickly get messy.
while not isinstance(user_input, int):
Remember, the input you receive as a result of calling the input function will be a string. Therefore, the code above will always be True, which is not what you want. Though, the code above could work if you change user_input to be of type int.
>>> num = input('Enter a number: ') # 5, as a string
>>> num
'5'
>>> int(num)
5
>>> isinstance(num, int)
True
But the interpreter would throw an error if num was something else.
>>> num = input('Enter a number: ') # 'A'
>>> int(num)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'A'
This brings us back to the answer, which involves using a string method to check if the string represents some number. I chose to use the str.isnumeric() method because it is the most flexible.
I hope this answers your question. Happy coding!

How can I put user input into a list using eval?

thanks for helping.
I am having trouble with the following code:
digitsList = input("Enter any list of 0 or more digits in the form [digit, digit, ...]:")
if element == int(list[index]):
index += 1
return True
else:
index += 1
return False
for example the user entered : [1,2,3]
then I get a following error :
ValueError: invalid literal for int() with base 10: '['
I tried everything I can but not being able to solve it.
It's a bit difficult to read your code the way you posted it, but user input could be put into a list using the .append feature.
For example:
list = digitsList.append("what the user inputs goes here")
You are giving a wrong input. The input entered by the user should be like this in a single line : 1 2 3. If you are supposed to take a list as input, do this :
digitslist = map(int, raw_input("Enter any list of 0 or more digits in the form [digit, digit, ...]:").split())
Input : 1 2 3
Output : [1, 2, 3]
The input() function is supposed to take only one int, float or string entered with quotes as input.
Use following code:
x = [i for i in eval(input("Enter comma seperated"))]

Resources