Multiplication in Python not working - python-3.x

I have the bizarre error in python 3.4 where multiplication does not work!
This is my code:
timerlenth = input('Please enter the amount of minute: ')
int(timerlenth)
timersec = (timerlenth*60)
print (timersec)
Here is a photo of the result:
I am practically clueless on trying to solve the problem!

The input function returns a string. Therefore the variable timerlenth stores a string. Next line, int(timerlenth) converts this variable to integer, but does nothing with the result, leaving the timerlenth as the same string it used to be. Python has this functionality where [string]*x will repeat the string x times and that's what you see in the output.
To get actual multiplication, you'll have to store the value of int(timerlenth) to a variable, preferably a new one (good programming practice) and use the new value with multiplication operation.

timerlenth is a string, so the * operator just concatinates it 60 times instead of multiplying it. This caused by your misuse of int - it doesn't change the passed argument, it returns an integer value for it, which you then lose by not assigning it anywhere. Just reassign it to timerlenth and you should be fine:
timerlenth = int(timerlenth)

Related

Inner workings of map() in a specific parsing situation

I know there are already at least two topics that explain how map() works but I can't seem to understand its workings in a specific case I encountered.
I was working on the following Python exercise:
Write a program that computes the net amount of a bank account based a
transaction log from console input. The transaction log format is
shown as following:
D 100
W 200
D means deposit while W means withdrawal. Suppose the following input
is supplied to the program:
D 300
D 300
W 200
D 100
Then, the output should be:
500
One of the answers offered for this exercise was the following:
total = 0
while True:
s = input().split()
if not s:
break
cm,num = map(str,s)
if cm=='D':
total+=int(num)
if cm=='W':
total-=int(num)
print(total)
Now, I understand that map applies a function (str) to an iterable (s), but what I'm failing to see is how the program identifies what is a number in the s string. I assume str converts each letter/number/etc in a string type, but then how does int(num) know what to pick as a whole number? In other words, how come this code doesn't produce some kind of TypeError or ValueError, because the way I see it, it would try and make an integer of (for example) "D 100"?
first
cm,num = map(str,s)
could be simplified as
cm,num = s
since s is already a list of strings made of 2 elements (if the input is correct). No need to convert strings that are already strings. s is just unpacked into 2 variables.
the way I see it, it would try and make an integer of (for example) "D 100"?
no it cannot, since num is the second parameter of the string.
if input is "D 100", then s is ['D','100'], then cm is 'D' and num is '100'
Then since num represents an integer int(num) is going to convert num to its integer value.
The above code is completely devoid of error checking (number of parameters, parameters "type") but with the correct parameters it works.
and map is completely useless in that particular example too.
The reason is the .split(), statement before in the s = input().split(). This creates a list of the values D and 100 (or ['D', '100']), because the default split character is a space ( ). Then the map function applies the str operation to both 'D' and '100'.
Now the map, function is not really required because both values upon input are automatically of the type str (strings).
The second question is how int(num) knows how to convert a string. This has to do with the second (implicit) argument base. Similar to how .split() has a default argument of the character to split on, so does num have a default argument to convert to.
The full code is similar to int(num, base=10). So as long as num has the values 0-9 and at most 1 ., int can convert it properly to the base 10. For more examples check out built in int.

Is it possible to Add 0 in Double Var in VB Net

I'm trying to add 0 before each number I'm having but it seems it's not working because I'm using double. I'm using double so I can input numbers such as 1.5 (hours) and translate it to seconds, minutes, and hours (Output should be 0 seconds, 30 minutes, and 1 hour and 01:30:00). I'm having no problems with the first output but I can't seem to do the second output (The desired 01:30:00 only displays 1:30:0). What I did first is I tried to convert the double variable to int32 then to string but it seems to not work. Here's the code:
If SecondsRemainder >= 0 And SecondsRemainder < 10 Then
SecondsRemainder = Convert.ToInt32(SecondsRemainder)
SecondsRemainder.ToString.PadLeft(2, "0")
End If
This line of code:
SecondsRemainder.ToString.PadLeft(2, "0")
Doesn't seem to do anything, am I missing something out? Or is there any other way I can do? Looking forward to your answers!
Let's look at this line piece by piece, and see what it actually does:
SecondsRemainder.ToString.PadLeft(2, "0")
We start with the SecondsRemainder variable. This variable is still a Double, in spite of the earlier code using Convert.ToInt32(). Remember, at it's core VB.Net is a statically typed language! When you declare a variable with a specific type, the variable's type can never change.
We now call the .ToString() method for this variable. Note this really is a method, not a property. Good practice for .Net is to include the parentheses when calling methods, even though they aren't strictly required with VB. If I reviewed that code, I'd ask you to change it to show the parentheses. Remember, we're also getting the Double version of this method, rather than the Integer version. You're probably okay here, but the double version can do weird things for formatting you might not expect from an integer.
Finally, we take the string result from the previous method and call PadLeft(). This mostly does what you expect. However, there is no overload that takes a number and a string. Frankly, I'm surprised this even compiles, and it tells me you likely don't have Option Strict set correctly. No self-respecting programmer runs with Option Strict Off anymore. The correct way to call this function is like this:
.PadLeft(2, "0"c)
Where the c suffix gives you a character value rather than a string value.
And that's it. We're done. This function returns a result. It does not modify the calling variable. So we've done all this work, and discard the result without actually changing anything.
What I would do to fix your issue is declare a new string variable to receive the result. Then I would use this code to assign to it:
'Create a string variable to hold your string result
Dim RemainderString As String = ""
'Use double literals to compare with double variables!
If SecondsRemainder >= 0.0 And SecondsRemainder < 10.0 Then
'Use a format string directly from the initial double value to create your string result
' and don't forget to assign it to a variable
RemainerString = SecondsRemainder.ToString("00")
End If
You may also want to use Math.Round() first, as this code would still create "01" from a 1.9999 input.
Finally, I'm wondering how you're using this SecondsRemainder value. VB.Net has a whole set of methods for building date and time strings and values, and a variable name like SecondsRemainder sounds like you're doing something the hard way that could be much MUCH easier.
I'm wondering if the answer is that you are approaching the problem incorrectly. You seem to be computing some time value. If so use TimeSpan.
Dim ts As TimeSpan = TimeSpan.FromHours(1.51#)
' ts.TotalSeconds
' ts.Seconds
Dim s As String = ts.ToString("hh\:mm\:ss")

Python Function with 2 values

Homework Question I am struggling with
Specification:
The third function you will write should be called ‘excelPrep’. Your function should take one (1) argument:
a string that will contain the Excel formula. The function should return two (2) values: first, a string
containing the modified Excel formula; and second an integer containing the number of dollar signs
removed.
Example Test Case:
excelPrep(‘=SUM($A$4:$A$12)’)
returns
=sum(a4:a12)
and
4
I will not write the entire code since this is stackoverflow and not homework helper so I think you should complete with your own mind.
The function should be something like:
Remove the $ by checking every letter in the string with for loop, at the same time add a number counter so that you can know how many $s you’ve removed. Making the input from =SUM($A$4:$A$12) into =SUM(A4:A12).
You could return the value now however if the assignment specified to make the letters in to lowercase. Make a new string variable and append all the letters from the function returned variable =SUM(A4:A12) check if the letter is a number if not .lower(). Which leaves you with =sum(a4:a12).
To return two values, in the end of your function type return stringVariable, integerVariable. Just be careful when ever you are calling the function, you will need to variables to store the outputs. Like: a, b = excelPrep(“=SUM($A$4:$A$12) which for your information a = “=sum(a4:a12)”, b = 4.
Hope that helps.

Performing arithmetic on string values

I would like to ask something about data types in Lua.
I get from serial link some message (command:value) like this:
tmp_string = "BRAKE:1"
then I parse this string to command and value in two different functions (one is for command and other one is for value). This is function for parsing value
function parser(value)
index = string.find(value, ":")
result = value.sub(value, index+1)
return result
end
I would like to now what sort of data type result is? If I use string match it works.
...if string.match(state, "1") then...
However it also works when I do something like this
x = (state*65536)/3.2808)
I thought the result is string, but I don't understand why it works also with numerical operations. Thank you in advance.
Lua 5.3 Reference Manual, §3.4.1 - Arithmetic Operators
With the exception of exponentiation and float division, the arithmetic operators work as follows: If both operands are integers, the operation is performed over integers and the result is an integer. Otherwise, if both operands are numbers or strings that can be converted to numbers (see §3.4.3), then they are converted to floats, the operation is performed following the usual rules for floating-point arithmetic (usually the IEEE 754 standard), and the result is a float.
Emphasis is mine.
When dealing with operations, Lua will attempt to convert string operands to floats, and if it works - it works. If it fails, you get an error.
>| '55' / 2
<| 27.5
>| 'foo' / 2
<| error: [string "return 'foo' / 2"]:1: attempt to perform arithmetic on a string value
If you want to be explicit about this (and safe) use tonumber, and handle the nil-case.
If you need to know the type of a value in Lua, you can pass the variable to type and check the resulting string.

How can I write the following script in Python?

So the program that I wanna write is about adding two strings S1 and S2 who are made of int.
example: S1='129782004977', S2='754022234930', SUM='883804239907'
So far I've done this but still it has a problem because it does not rive me the whole SUM.
def addS1S2(S1,S2):
N=abs(len(S2)-len(S1))
if len(S1)<len(S2):
S1=N*'0'+S1
if len(S2)<len(S1):
S2=N*'0'+S2
#the first part was to make the two strings with the same len.
S=''
r=0
for i in range(len(S1)-1,-1,-1):
s=int(S1[i])+int(S2[i])+r
if s>9:
r=1
S=str(10-s)+S
if s<9:
r=0
S=str(s)+S
print(S)
if r==1:
S=str(r)+S
return S
This appears to be homework, so I will not give full code but just a few pointers.
There are three problems with your algorithm. If you fix those, then it should work.
10-s will give you negative numbers, thus all those - signs in the sum. Change it to s-10
You are missing all the 9s. Change if s<9: to if s<=9:, or even better, just else:
You should not add r to the string in every iteration, but just at the very end, after the loop.
Also, instead of using those convoluted if statements to check r and substract 10 from s you can just use division and modulo instead: r = s/10 and s = s%10, or just r, s = divmod(s, 10).
If this is not homework: Just use int(S1) + int(S2).

Resources