I'm trying to make a very simple BTC To USD converter in python (bear with me I'm in the beginning stages), however when I print the value it prints the entered number 275 times (the value of 1 btc). I need it to return the amount entered by the user times 275 (so the user enters 1 and it multiplies 1 by 275 to return 275) Here is my current code:
enteramt = raw_input ("How many")
value = enteramt * 275
print ("This is worth" , value)
What it prints:
This is worth, 555555555555555555555555555555555555555555555555555555555555555
Except, theres 275 of them, but you get the point
In python 2 raw_input returns a string and in python somestring * value repeats the string value times. You want to convert the input to an int and then do the multiplication. (you also want to remove the parens from the print, that's a python 3 thing)
enteramt = raw_input ("How many")
value = int(enteramt) * 275
print "This is worth" , value
In python 3, raw_input is replaced by input, so you'd write
enteramt = input ("How many")
value = int(enteramt) * 275
print("This is worth" , value)
This is because enteramt is a string. Multiplying a string in python will produce the string repeated. For example:
str = '12'
str * 4
>>> '12121212'
You should convert your input to float or int:
str = float(str)
str * 4
>>> 48.0
You need to convert your raw_input()
So your new code should be like this:
enteramt = float(raw_input("How many"))
value = enteramt * 275
print ("This is worth" , value)
Or this:
enteramt = raw_input("How many")
value = float(enteramt) * 275
print ("This is worth" , value)
Related
I have a csv with one of the columns that contains periods:
timespan (string): PnYnMnD, where P is a literal value that starts the expression, nY is the number of years followed by a literal Y, nM is the number of months followed by a literal M, nD is the number of days followed by a literal D, where any of these numbers and corresponding designators may be absent if they are equal to 0, and a minus sign may appear before the P to specify a negative duration.
I want to return a data frame that contains all the data in the csv with parsed timespan column.
So far I have a code that parses periods:
import re
timespan_regex = re.compile(r'P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)D)?')
def parse_timespan(timespan):
# check if the input is a valid timespan
if not timespan or 'P' not in timespan:
return None
# check if timespan is negative and skip initial 'P' literal
curr_idx = 0
is_negative = timespan.startswith('-')
if is_negative:
curr_idx = 1
# extract years, months and days with the regex
match = timespan_regex.match(timespan[curr_idx:])
years = int(match.group(1) or 0)
months = int(match.group(2) or 0)
days = int(match.group(3) or 0)
timespan_days = years * 365 + months * 30 + days
return timespan_days if not is_negative else -timespan_days
print(parse_timespan(''))
print(parse_timespan('P2Y11M20D'))
print(parse_timespan('-P2Y11M20D'))
print(parse_timespan('P2Y'))
print(parse_timespan('P0Y'))
print(parse_timespan('P2Y4M'))
print(parse_timespan('P16D'))
Output:
None
1080
-1080
730
0
850
16
How do I apply this code to the whole csv column while running the function processing csv?
def do_process_citation_data(f_path):
global my_ocan
my_ocan = pd.read_csv(f_path, names=['oci', 'citing', 'cited', 'creation', 'timespan', 'journal_sc', 'author_sc'],
parse_dates=['creation', 'timespan'])
my_ocan = my_ocan.iloc[1:] # to remove the first row
my_ocan['creation'] = pd.to_datetime(my_ocan['creation'], format="%Y-%m-%d", yearfirst=True)
my_ocan['timespan'] = parse_timespan(my_ocan['timespan']) #I tried like this, but sure it is not working :)
return my_ocan
Thank you and have a lovely day :)
Like with Python's builtin map, Pandas also has that method. You can check its documentation here. Since you already have your function ready which takes a single parameter and returns a value, you just need this:
my_ocan['timespan'] = my_ocan['timespan'].map(parse_timespan) #This will take each value in the column "timespan", pass it to your function 'parse_timespan', and update the specific row with the returned value
And here is a generic demo:
import pandas as pd
def demo_func(x):
#Takes an int or string, prefixes with 'A' and returns a string.
return "A" + str(x)
df = pd.DataFrame({"Column_1": [1, 2, 3, 4], "Column_2": [10, 9, 8, 7]})
print(df)
df['Column_1'] = df['Column_1'].map(demo_func)
print("After mapping:\n{}".format(df))
Output:
Column_1 Column_2
0 1 10
1 2 9
2 3 8
3 4 7
After mapping:
Column_1 Column_2
0 A1 10
1 A2 9
2 A3 8
3 A4 7
So I was able to run part of a program doing below (using tuples)
def reverse_string():
string_in = str(input("Enter a string:"))
length = -int(len(string_in))
y = 0
print("The reverse of your string is:")
while y != length:
print(string_in[y-1], end="")
y = y - 1
reverse_string()
The output is:
Enter a string:I Love Python
The reverse of your string is:
nohtyP evoL I
I am still thinking how for the program to reverse the position of the words instead of per letter.
The desired output will be "Phython Love I"
Is there anyway that I will input a string and then convert it to a tuple similar below:
So If I enter I love Phyton, a certain code will do as variable = ("I" ,"Love", "Python") and put additional codes from there...
Newbie Programmer,
Mac
I'm new to coding and trying to teach myself about recursion by building a very simple function that calls itself. However my code is behaving slightly differently to how I was expecting:
get user input number that must not be greater than 50
def getinput():
input = int(raw_input("type number under 50 >>> "))
if input < 50:
return input
else:
print input, "no, must be under 50"
getinput()
print getinput()
This results in the following behavior:
This bit as expected
C:\Python27>python recur.py
type number under 50 >>> 23
23
This bit unexpected
C:\Python27>python recur.py
type number under 50 >>> 63
63 no, must be under 50
type number under 50 >>> 23
None
My question is, why is the last line "None", and not 23? My code seems to correctly call the function again if the user inputs a number 50 or greater, but why doesn't the second call return 23 (the same as the initial output)?
Any advice much appreciated
You don't return the result of the getInput() if the number is greater than 50
def getinput():
input = int(raw_input("type number under 50 >>> "))
if input < 50:
return input
else:
print input, "no, must be under 50"
return getinput()
print getinput()
You missed a return in the else condition. The following code should work:
def getinput():
input = int(raw_input("type number under 50 >>> "))
if input < 50:
return input
else:
print input, "no, must be under 50"
return getinput()
print getinput()
In this case your function will return input
if input < 50:
return input
You are using recursion, so it is just like a stack at the end all the return values will come back to the function which was called. When the condition if input < 50 not satisfied it will return None and you are using print(getinput()).
| 23 |
| 63 | -> None
-----
That's just my understanding about recursion.
so when the value is greater than 50, do return a value instead of None to the function back.
return getinput()
Also please use different variable names instead of input.
I have an input file like this:
number of elements = 4
number of nodes = 6
number of fixed points = 2
number of forces = 1
young = 2.0E8
poiss = 0.2
thickness = 0.002
node group
1 2 6
2 3 4
2 4 5
2 5 6
And I use this to read the file
fid = fopen(input_file);
tline = fgetl(fid);
line_number = 1;
while ischar(tline)
# this will locate the string, and find the number
if ~isempty(strfind(tline,'number of elements'))
NELEM = str2double(regexp(tline, '\d+', 'match'));
end
if ~isempty(strfind(tline,'young'))
YOUNG = str2double(regexp(tline, '\d+', 'match'));
end
line_number=line_number+1;
tline = fgetl(fid);
end
fclose(fid);
The first works fine, however, for the second, YOUNG, the output is actually [2 0 8](original number is 2e8) The regexp turns the string into an array.
And for poiss, it read as [0,2].
How can I turn the string into the original number?
Your regular expression needs to match floating point numbers with exponents, try changing '\d+' to
'[0-9]*\.?[0-9]+([eE][0-9]+)?'
This then matches numbers with an optional decimal point and exponent. For example:
str2double(regexp('young = 2.0E8', '[0-9]*\.?[0-9]+([eE][0-9]+)?', 'match'))
gives 200000000.
I have a dictionary like
>> dic = {'yearly': 79.00, 'monthly': 59.00}
when the dic is printed the, it removes the last zero from the decimal number.
>> print dic
>> {'monthly': 59.0, 'yearly': 79.0}
How to get the original value as 59.00 not as 59.0 ?
when you print a number, you could do
x = 5
print '%.2f' % x
where the 2 specifies u want 2 decimal place
alternatively, the more updated/versatile version is
print '{:.2f}'.format(x)
if you really want your dict object to print nicely, you could create a custom class that specifies the __str__ function to print the dict however you want to print it