this post was submitted on 31 Oct 2024
46 points (96.0% liked)

Python

6331 readers
116 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

๐Ÿ“… Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

๐Ÿ Python project:
๐Ÿ’“ Python Community:
โœจ Python Ecosystem:
๐ŸŒŒ Fediverse
Communities
Projects
Feeds

founded 1 year ago
MODERATORS
 

Note: The attached image is a screenshot of page 31 of Dr. Charles Severance's book, Python for Everybody: Exploring Data Using Python 3 (2024-01-01 Revision).


I thought = was a mathematical operator, not a logical operator; why does Python use

>= instead of >==, or <= instead of <==, or != instead of !==?

Thanks in advance for any clarification. I would have posted this in the help forums of FreeCodeCamp, but I wasn't sure if this question was too.......unspecified(?) for that domain.

Cheers!

ย 


Edit: I think I get it now! Thanks so much to everyone for helping, and @[email protected] and @[email protected] in particular! ^_^

you are viewing a single comment's thread
view the rest of the comments
[โ€“] [email protected] 8 points 4 days ago* (last edited 4 days ago) (1 children)

It's a convention set by early programming languages.

In most C-like languages, if (a = b)... is also a valid comparison. The = (assignment) operation returns the assigned value as a result, which is then converted to a boolean value by the if expression. Consider this Javascript code:

let a = b = 1
  1. It first declares the b variable and assigns it the value of the expression 1, which is one.
  2. It returns the result of the expression b = 1, which is the assigned value, which is 1.
  3. It declares the a variable and assigns the previously returned value, which is 1.

Another example:

let a = 1
let b = 2
let c = 3
console.log(a == b) // prints "false" because the comparison is false
console.log(a = b) // prints 2 because the expression returns the value of the assignment, which is 'b', which is 2

// Using this in an 'if' statement:
if (b = c) { // the result of the assignment is 3, which is converted to a boolean true
    console.log("what")
}

You can't do the same in Python (it will fail with a syntax error), but it's better to adhere to convention because it doesn't hurt anyone, but going against it might confuse programmers who have greater experience with another language. Like I was when I switched from Pascal (which uses = for comparison and := for assignment) to C.

[โ€“] [email protected] 5 points 4 days ago (1 children)

With python you can use the := to assign and return new value.

[โ€“] [email protected] 3 points 4 days ago

Walrus operator my beloved