Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I know that the program convert Decimal to Binary,in fact I'm just a beginner in programming and python is my starting language.
answering these questions will help me a lot.
def bin(i):
s = "" # what do we mean by s="" ? does it mean s=0?
while i: # where is the condition ?
if i & 1: # what is the equivalent for '&'? when I put 'and' instead of '&' I get differnt results?why?
s = "1" + s # ?
else:
s = "0" + s
i = i//2 # why?
return s
the problem is that I want to undestand what happen between the input and the output?
one more thing can we extend this code to floating numbers how ?
Let me try to answer your questions one at a time; you should then be able to piece them all together:
s = "" # what do we mean by s="" ? does it mean s=0?
s is now an empty string. You could add other strings to it, to concatenate them. Indeed, this is what is done later on, in the line s = "1" + s. Take a look:
In [21]: "1" + ""
Out[21]: '1'
In [22]: "1" + "2"
Out[22]: '12'
In [23]: s = ""
In [24]: "1" + s
Out[24]: '1'
See how string concatenation works?
Next:
while i: # where is the condition ?
Ah! there is a nuance in many programming languages (including python) that an integer whose value is 0 evaluates to a boolean of False, when used in a conditional statement (like if or while). All non-zero values evaluate to True.
Therefore, this while loop is saying while i does not take the value of 0. Note that because of the division on i later on, i will never take on a negative value, and this loop therefore terminates.
Next:
if i & 1: # what is the equivalent for '&'? when I put 'and' instead of '&' I get differnt results?why?
i&1 is a bit-wise AND operator. Suppose i has the value of 5. Then, the binary representation of i is 101. the binary representation of 1 is simply 1, or 001 (since we are comparing it with 101). So now, we perform the bit-wise AND, which basically compares each pair of corresponding bits, outputting 1 if they are both 1s (0 otherwise). The result of comparing 101 and 001 thusly, is 001, which translates to a value of 1. All this means is that when you divide i by 2, you get a remainder of 1. Since the only possibilities for this are 1 (which evaluates to True in the if-statement) or 0 (which evaluates to False in the if-statement), it lends itself to be very easily used in such a dichotomous fashion (to add either a "0" or a "1" to s)
Next:
i = i//2
This is a truncated division with an integer casting. Watch:
In [27]: i = 4
In [28]: i/2
Out[28]: 2.0
In [29]: i//2
Out[29]: 2
In [30]: i = 5
In [31]: i/2
Out[31]: 2.5
In [32]: i//2
Out[32]: 2
Get it?
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How can I get the fractional part of a number?
For example, I have a list of floats num = [12.73, 9.45] and want to get only the numbers after the decimal point, 73 and 45 in this case. How do I go about doing this?
One approach is using pure(ish) maths.
The short answer:
num = [12.73, 9.45]
[int((f % 1)*100) for f in num]
>>> [73, 44]
Explanation:
The modulo operator returns the remainder once whole division is complete (to over-simplify).
Therefore this, returns the decimal value; the fractional part of the number.
12.73 % 1
>>> 0.7300000000000004
To get the decimal value as a integer, you can use:
int((12.73 % 1)*100)
>>> 73
Just wrap this in a loop for all required values ... and you have the 'short answer' above.
num = [12.73, 9.45];
result = list(map(lambda x: int(str(x).split('.')[1]),num))
print(result)
and want to get only the numbers after the period,
There is no such thing. Numbers don't have digits; the string representation of the numbers has digits. And even then, floating-point numbers are not precise; you may be shown 0.3 in one context and 0.30000000000000004 in another, for the same value.
It sounds like what you are actually after is the fractional part of the numbers. There are many ways to do this, but they all boil down the same idea: it is the result when you divide (as a floating-point number) the input by 1.
For a single value, it looks like:
fractional_part = value % 1.0
or
# This built-in function performs the division and gives you
# both quotient and remainder.
integer_part, fractional_part = divmod(value, 1.0)
or
import math
fractional_part = math.fmod(value, 1.0)
or
import math
# This function is provided as a special case.
# It also gives you the integer part.
# Notice that the results are the other way around vs. divmod!
fractional_part, integer_part = math.modf(value)
To process each value in a list in the same way, use a list comprehension.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
square = 0
number = 1
while number < 10:
square = number ** 2
print(square)
number += 1
It's my answer for this question :" Print all squares from 0 to 99(1,4,..,81)Use number variable in while loop."
Pycharm says it doesn't match with its answer.
I think i should print those numbers in a single line but i couldn't deal with it.How can i do that ?
Your code will print each number in a newline, because, in Python, the call to print() comes with an implicit newline (see the end argument per the documentation).
Next, you're making an assumption about output formatting. As I see it, there are two primary issues with this assumption:
1) Calls to functions (e.g. print()) in a while loop "execute" when they're called -- there's no delay to see if a future pass through the loop will provide extra data to the function.
2) You're assuming that the Python interpreter will guess that printed numbers (in a while loop) are desired to be returned in a comma separated list. Computers are machines that do what you tell them to do -- if you don't write logic to explain what you need, the machine cannot give you this.
You can express your desired output in the following ways:
1) Collect the numbers (as strings) in a list, then output them after you're done looping:
square = 0
number = 1
# think of this as a result container
number_result_list = []
while number < 10:
square = number ** 2
# place that number at the end of your container:
number_result_list.append(str(square))
number += 1
# join all your number strings together, using a comma
print(",".join(number_result_list))
# prints 1,4,9,16,25,36,49,64,81
2) Specify that you want to use a comma in the call to print. Make special note of the trailing comma -- you now know why this happens:
square = 0
number = 1
while number < 10:
square = number ** 2
print(square, end=",")
number += 1
# prints 1,4,9,16,25,36,49,64,81,
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm beginning to learn the basics of python. I had just learned that str() turns non-strings into strings - example: str(2) would change 2 to "2". That raised a question - what is a string and what difference does it have from a non-string? I've googled this but I could not find this question is directly answered and the general explanations don't quite make it clear for me.
"That raised a question - what is a string and what difference does it have from a non-string?"
It sounds like python is your first language. That being said, for conceptual sake, a string is text, and a 'non-string' is a number. You will see why this is not quite true as you program more, but for understanding the difference between a string and a 'non-string' this will suffice. You can do math with 'non-strings'. "2" is a string, but 2 is a 'non-string'. Adding strings is NOT the same as arithmetic addition. "2" + "2" results in another string "22" (this operation is called concatenation ), but 2 + 2 results in a 'non-string' A.K.A. the NUMBER (not string) 4, because the addition is arithmetic addition.
A string is any sequence of characters — not just numbers, but letters and punctuation and all of Unicode.
Something that isn't a string is... not that. :) (There are lots of things that aren't strings! String isn't special.) For example, 2 is an int. You can do math on an int, because it's a number. But you can't do math on a str like "2"; it's only the way we write the number in Western mathematics, not the number itself. You couldn't ask "dog" to wag its tail, either, because it's not a real dog; it's just the written word "dog".
As a more practical example:
2 + 2 gives you 4, the result of combining two numbers.
"2" + "2" gives you "22", the result of combining two written "words".
just to put another spin on this...
objects in python come with a variety of attributes and methods. attributes tend to represent data associated with the object. methods tend to represent behaviors that can be performed by the object. if we create a string and give it the name a and look at the list of attributes/methods, we see that the list encompasses many of the things you would want to know about a string or do with a string.
In [91]: a = '1' # assign a string the name 'a'
In [92]: a.
a.capitalize a.format a.isupper a.rindex a.strip
a.center a.index a.join a.rjust a.swapcase
a.count a.isalnum a.ljust a.rpartition a.title
a.decode a.isalpha a.lower a.rsplit a.translate
a.encode a.isdigit a.lstrip a.rstrip a.upper
a.endswith a.islower a.partition a.split a.zfill
a.expandtabs a.isspace a.replace a.splitlines
a.find a.istitle a.rfind a.startswith
on the other hand, if we create a number and give it the name b and look at the list of attributes/methods, we see that they are very different and focuses on things we would want to know about a number or do with a number.
In [92]: b = 1 # assign a number the name 'b'
In [93]: b.
b.bit_length b.denominator b.numerator
b.conjugate b.imag b.real
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What is my problem ? I want act inverse number--example : 123 ==>321
def loop(a):
i=0
while(a>=1)
print(a%10)
s=s/10
i=i+1
Your solution has a few problems, aside from the indentation and the missing colon.
First of all your are using print which automatically adds a line break, so that might not be what you want the result to look like. You could store the result in a string which you append the latest character to and then print it once at the end.
Further, you are using a variable s which was never used before. In thise case it should be a as you want to strip off the last digit using an integer division by 10. Note that in this case, this will only work like that in Python 2, as Python 3 will use a float division there (e.g. 15 / 10 == 1.5). You can prevent that by explicitly using the integer division there (this will also make your intend more clear): s = s // 10 (note the two slashes).
Lastly, you are incrementing the variable i without ever using it, so you can just get rid of it.
In the end, it might look like this:
def reverse (a):
rev = ''
while a > 1:
rev += str(a % 10)
a = a // 10
A shorter solution, utilizing the fact that you can just reverse strings:
>>> num = 123
>>> rev = int(str(num)[::-1])
>>> rev
321
If you leave out the int(), you can even keep trailing/leading zeros and get a string instead:
>>> num = 3210
>>> str(num)[::-1]
'0123'
Few issues:
Your indentation does not match. PEP 8 suggests 4 spaces for indentation.
You're missing a colon after while(a>=1)
Although this isn't an issue, you don't need the parentheses in the while loop, it can just be while a >= 1
s = s/10 might not return what you expect. For example, 12/10 == 1 (unless you're dealing with floats here).
This can all be simplified using slicing:
>>> print int(str(123)[::-1])
321
It is important to indent correctly. (And don't mix tabs and spaces.)
def loop(a):
i = 0
while a >= 1:
print(a % 10)
a = a / 10
i = i + 1
You were also missing a colon after the while condition.
This question already has answers here:
How do "and" and "or" act with non-boolean values?
(8 answers)
Closed 6 months ago.
I'm a little confused with the results I'm getting with the logical operators in Python. I'm a beginner and studying with the use of a few books, but they don't explain in as much detail as I'd like.
here is my own code:
five = 5
two = 2
print five and two
>> 2
It seems to be just outputting the two variable.
five = 5
two = 2
zero = 0
print five and two and zero
So, I added another variable integer. Then I printed and got the following output:
>> 0
What is going on with Python in the background? Why isn't the output something like 7 or 5, 2.
Python Boolean operators return the last value evaluated, not True/False. The docs have a good explanation of this:
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
As a bit of a side note: (i don't have enough rep for a comment) The AND operator is not needed for printing multiple variables. You can simply separate variable names with commas such as print five, two instead of print five AND two. You can also use escapes to add variables to a print line such as print "the var five is equal to: %s" %five. More on that here: http://docs.python.org/2/library/re.html#simulating-scanf
Like others have said AND is a logical operator and used to string together multiple conditions, such as
if (five == 5) AND (two == 2):
print five, two
Boolean And operators will return the first value 5 if the expression evaluated is false, and the second value 2 if the expression evaluated is true. Because 5 and 2 are both real, non-false, and non-null values, the expression is evaluated to true.
If you wanted to print both variables you could concatenate them to a String and print that.
five = 5
two = 2
print five + " and " + two
Or to print their sum you could use
print five + two
This document explains how to use the logical Boolean operators.
This AND in Python is an equivalent of the && in Java for instance. This doesn't mean the and in the English language. The AND is a logical operator. Assume five holds 5 and two holds 2. From Python documentation: The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned. Basically, it evaluates the last integer in your case which is true.
if (five and two):
... print "True"
... else:
... print "False"
The AND is a logical operator, to test the logic for a specific case, not an arithmetic operator. If you want to get results like 7 for five and two, you should rather use "+" which means adding two integers. See below:
>>> five = 5
>>> two = 2
>>> print five + two
7
Try 0 and 9.
The result is 0 because the value of 0 is false. The operand on the left of the and operator is False so the whole expression is False and returns 0
In Python any non-zero integer value is true; zero is false.
The OP’s values are both non-zero.
The AND operator tests from left to right,
with and, if all values are True, returns the last evaluated value.
If any value is false, returns the first one.
Since both are non-zero, both are true, so the last value is returned
To convert the integer variable to a string , add str in front of each variable
five = 5
two = 2
print(str(five) + " and " + str(two))