Need help converting string or int to float - string

So I have been stuck on this one for a while and could use some help. I have been trying to fix this code and I keep getting an error about invalid syntax. So here is the code I need help with need to convert from str or int to float.
# Input from the command line
import sys
A = sys.argv[1]
B = sys.argv[2]
C = sys.argv[3]
# Your code goes here
num = A * (B + C / 3)
# Outputs
print (float(num))

By default,python gets inputs from command line as str.So,you must convert them to floats before applying any operation
import sys
A=float(sys.argv[1])
B=float(sys.argv[2])
C=float(sys.argv[3])
.....

Related

How to get the type of an object which data has passed by user

I taking input from user in python, How to know user has passed int or string or float etc??
number1 = eval(sys.argv[1])
number2 = eval(sys.argv[2])
if user passed input is float or int, i want to sum them, but how to know which type of data user passed? because all data which user passes is default type is string.
Python advocates the approach of "ask forgiveness, not permission". All user input is probably going to be a string - especially if you're getting it from sys.argv - but the best way to determine this is to attempt to make them numbers (using try/except) and then revert to different behavior if that fails.
num1str, num2str = sys.argv[1], sys.argv[2]
try:
# might as well do float, because every valid integer that can be represented in a
# string is also a valid float
num1 = float(num1str)
num2 = float(num2str)
num3 = num1 + num2
except ValueError:
# this happens if the variable cannot be converted, e.g. the user entered something
# that cannot be interpreted as a float
...
There are built in methods for that:
int()
str()
for example convert, if possible, while type() tells you what it is:
x = "Hi there"
print(type(x))
y = 3
print(type(y))
y = str(y)
print(type(y))
When receiving user input, you can try converting it and if successful, work with the result of the conversion:
_in = input("Some input please ")
try:
_in = int(_in)
except:
try:
_in = float(_in)
except:
pass
print(_in)
print(type(_in))
>>Some input please 3
>>3
>><class 'int'>
>>Some input please 3.5
>>3.5
>><class 'float'>
We can use eval() for that,
import sys
def main():
number1 = eval(sys.argv[1])
number2 = eval(sys.argv[2])
print(number1 + number2)
if __name__ == '__main__':
main()
when the user enters an integer as an input the input() function returns a string, but in the case of eval() it will evaluate the returned value from a string to an integer, same in float . No need to check data type every time.
see 3rd number of below link,
https://towardsdatascience.com/python-eval-built-in-function-601f87db191

Python: ValueError: invalid literal for int() with base 10:'\x00

I am making a client-server program implementing the Diffie-Hellman algorithm
Client:
from __future__ import print_function
import math
import socket
host = "localhost"
port = 1200
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print("Connected with Server")
sharedPrime = 23 # p
sharedBase = 5 # g
aliceSecret = 6 # a
s.send(bytes(aliceSecret))
bobSecret=s.recv(1024)
# Alice Sends Bob A = g^a mod p
A = (sharedBase**aliceSecret) % sharedPrime
s.send(bytes(A))
B=s.recv(1024)
B=B.decode()
# Alice Computes Shared Secret: s = B^a mod p
aliceSharedSecret = (int(B)** aliceSecret) % sharedPrime
print( "Alice Shared Secret: ", aliceSharedSecret )
The server code is basically the same, except it handles "Bob's" side of the algorithm. My problem starts at this line:
aliceSharedSecret = (int(B)** aliceSecret) % sharedPrime
Which gives me this error:
invalid literal for int() with base 10: '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
I've gone back to see what "B" actually is and it's just blank. What am I doing wrong?
Look at this line:
s.send(bytes(aliceSecret))
You convert int value to bytes here. This produces result like b'\x00\x00\x00\x00\x00\x00' that later cannot be directly casted to int even after decoding because it's not number in decimal form. There are 2 possible solutions:
1) Properly decode value, this line will interpret bytes object as int splitted into bytes:
B = int.from_bytes(B, byteorder='big', signed=False) # instead of B = B.decode()
2) Convert your original int value to str before converting to bytes so back convertation will work

len(str) giving wrong result after retrieving str from filename

Any idea why I am getting a length of 6 instead of 5?
I created a file called björn-100.png and ran the code using python3:
import os
for f in os.listdir("."):
p = f.find("-")
name = f[:p]
print("name")
print(name)
length = len(name)
print(length)
for a in name:
print(a)
prints out the following:
name
björn
6
b
j
o
̈
r
n
instead of printing out
name
björn
5
b
j
ö
r
n
If you're using python 2.7, you can simply decode the file name as UTF-8 first:
length = len(name.decode('utf-8'))
But since you're using python 3 and can't simply decode a string as if it were a bytearray, I recommend using unicodedata to normalize the string.
import unicodedata
length = len(unicodedata.normalize('NFC', name))
The way to get the correct string with the two dots inside the o char is:
import unicodedata
name = unicodedata.normalize('NFC', name)

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

Finding the additive and multiplicative roots of a number using python

http://www.cs.uni.edu/~diesburg/courses/cs1510_sp15/homework/PA04/index.htm
So I have this assignment. I have been trying to work out the code to find the additive and multiplicative roots of a user given input. I am new to python and know how to work the problem out, but without the tools (coding know how) have been just running in circles for quite a while now. So if anyone could be so kind as to help me figure out the coding. I have tried slicing the list, but keep getting an error if I try to make the string an int and if I leave it as an string it just doesn't seem to run. I know there is probably a way using modulous as well, but have yet to quite master it.
Thank you for any help any of you are able to leave me.
Edit
Here is the code I have so far.
import sys
userStr = input("What number should I use for my \
calculations? ")
userInt = int (userStr)
original = userStr #Save Copy of original value
originalTwo = userStr #Save second Copy of original value
addCount = 0
mulCount = 0
#Stop the program if the integer is less than or equal to 0
while userInt <= 0:
print ("Thanks for playing along!")
sys.exit()
#Use a while loop to repeat the process of splitting an integer into single digits and then adding the individual digits.
print = ("Addition")
while userInt > 9:
userInt = sum(map(int, userStr))
print("New Value: ",userStr)
addCount = addCount + 1
#Use a while loop to repeat the process of splitting an integer into single digits and then multiplying the individual digits.
print = ("Multiplication")
while original > 9:
original = (map (int, original))
print("New Value: ",original)
mulCount = mulCount + 1
#Print the outputs to the screen for the user.
print("For the Integer: ",userInt)
print(" Additive Persistence= ",addCount,", Additive Root= ", userInt)
print(" Multiplicative Persistence= ",mulCount,",
Multiplicative Root= ", original)

Resources