Python Forum
print(f"{person}:") SyntaxError: invalid syntax when running it - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: print(f"{person}:") SyntaxError: invalid syntax when running it (/thread-30745.html)

Pages: 1 2


print(f"{person}:") SyntaxError: invalid syntax when running it - AryaIC - Nov-03-2020

Hello all...,

I'm beginner in python and have been trying to fix this but I'm lost. So please help me. I got this ^
SyntaxError: invalid syntax print(f"{person}:")
when I ran it in PyCharm. The code:

import csv
import itertools
import sys

PROBS = {

    "gene": {
        2: 0.01,
        1: 0.03,
        0: 0.96
    },

    "trait": {

        2: {
            True: 0.65,
            False: 0.35
        },

        1: {
            True: 0.56,
            False: 0.44
        },

        0: {
            True: 0.01,
            False: 0.99
        }
    },

    "mutation": 0.01
}


def main():
    if len(sys.argv) != 2:
        sys.exit("Usage: python heredityarya.py data.csv")
    people = load_data(sys.argv[1])

    probabilities = {
        person: {
            "gene": {
                2: 0,
                1: 0,
                0: 0
            },
            "trait": {
                True: 0,
                False: 0
            }
        }
        for person in people
    }

    names = set(people)
    for have_trait in powerset(names):

        fails_evidence = any(
            (people[person]["trait"] is not None and
             people[person]["trait"] != (person in have_trait))
            for person in names
        )
        if fails_evidence:
            continue

        for one_gene in powerset(names):
            for two_genes in powerset(names - one_gene):

                p = joint_probability(people, one_gene, two_genes, have_trait)
                update(probabilities, one_gene, two_genes, have_trait, p)

    normalize(probabilities)

    for person in people:
        [b]print(f" {person}:")[/b]
        for field in probabilities[person]:
            print(f"  {field.capitalize()}:")
            for value in probabilities[person][field]:
                p = probabilities[person][field][value]
                print(f"    {value}: {p:.4f}")

def load_data(filename):
    data = dict()
    with open(filename) as f:
        reader = csv.DictReader(f)
        for row in reader:
            name = row["name"]
            data[name] = {
                "name": name,
                "mother": row["mother"] or None,
                "father": row["father"] or None,
                "trait": (True if row["trait"] == "1" else
                          False if row["trait"] == "0" else None)
            }
    return data


def powerset(s):
    s = list(s)
    return [
        set(s) for s in itertools.chain.from_iterable(
            itertools.combinations(s, r) for r in range(len(s) + 1)
        )
    ]


def joint_probability(people, one_gene, two_genes, have_trait):
    probability = 1
    for person in people:

        num_genes = num_genes_of_person(person, one_gene, two_genes)

        has_trait = person in have_trait

        if people[person]['mother'] is None and people[person]['father'] is None:
            probability *= PROBS["gene"][num_genes] * PROBS["trait"][num_genes][has_tr

            else:
            num_genes_mother = num_genes_of_person(people[person]['mother'], one_gene
            num_genes_father = num_genes_of_person(people[person]['father'], one_gene

            if num_genes == 0:
                probability *= probability_inheritence(num_genes_mother, False) * prob

            elif num_genes == 1:
                probability *= probability_inheritence(num_genes_mother, True) * proba
                               + probability_inheritence(num_genes_mother, False) *

            elif num_genes == 2:
                probability *= probability_inheritence(num_genes_mother, True) * proba

            probability *= PROBS["trait"][num_genes][has_trait]
    return probability

def update(probabilities, one_gene, two_genes, have_trait, p):
    for person in probabilities:

        num_genes = num_genes_of_person(person, one_gene, two_genes)

        has_trait = person in have_trait

        probabilities[person]["gene"][num_genes] += p
        probabilities[person]["trait"][has_trait] += p

def normalize(probabilities):
    for person in probabilities:
        trait_sum = sum(probabilities[person]["trait"].values())
        gene_sum = sum(probabilities[person]["gene"].values())

        for gene in probabilities[person]["gene"]:
            probabilities[person]["gene"][gene] /= gene_sum

        for trait in probabilities[person]["trait"]:
            probabilities[person]["trait"][trait] /= trait_sum

if __name__ == "__main__":
    main()
Why print(f"{person}:") is invalid syntax? What changes should I make on this?
And I got No such file or directory when I ran it in Visual Studio Code. What did I miss?

Many thanks in advance.


RE: print(f"{person}:") SyntaxError: invalid syntax when running it - Axel_Erfurt - Nov-03-2020

you need to use python >= 3.6 for f-strings


RE: print(f"{person}:") SyntaxError: invalid syntax when running it - AryaIC - Nov-03-2020

Did you mean I need to install Python 3.6?
I have IDLE 3.8.3 , pycharm 2020.1.4 (communitiy edition) and Visual studio code Version: 1.50.1 installed in MacBook macos sierra 10.12. The default python is 2.7.10.

Today I just reinstalled IDLE 3.8.3 and removed the 3.9 version because I got an internal error of pygame when I wanted to play a game. I ran the code in IDLE. So I was able to run the code and play the game using pygame again after removing IDLE 3.9 and reinstalling IDLE 3.8.3.

I'm just very nervous if I need to install python 3.6 as you suggested, because it sounds like to me I have to remove IDLE 3.8.3 again and that would mean I might encounter the same error again. And I suppose I might erase the NumPy, scikit-learn, TensorFlow, Keras that I just installed them. And maybe I might lose other python modules/libraries too.

Forgive me if I'm wrong about it.


RE: print(f"{person}:") SyntaxError: invalid syntax when running it - deanhystad - Nov-03-2020

Does this work?
people = ['me', 'you', 'him', 'her', 'they']
for person in people:
    print(f" {person}:")
A syntax error may have nothing to do with the line that gets flagged. It could be an error that started some line above but only became noticeable at the reported line.


RE: print(f"{person}:") SyntaxError: invalid syntax when running it - AryaIC - Nov-03-2020

(Nov-03-2020, 06:36 PM)Axel_Erfurt Wrote: you need to use python >= 3.6 for f-strings
Did you mean I need to install Python 3.6?
I have IDLE 3.8.3 , pycharm 2020.1.4 (communitiy edition) and Visual studio code Version: 1.50.1 installed in MacBook macos sierra 10.12. The default python is 2.7.10.

Today I just reinstalled IDLE 3.8.3 and removed the 3.9 version because I got an internal error of pygame when I wanted to play a game. I ran the code in IDLE. So I was able to run the code and play the game using pygame again after removing IDLE 3.9 and reinstalling IDLE 3.8.3.

I'm just very nervous if I need to install python 3.6 as you suggested, because it sounds like to me I have to remove IDLE 3.8.3 again and that would mean I might encounter the same error again. And I suppose I might erase the NumPy, scikit-learn, TensorFlow, Keras that I just installed them. And maybe I might lose other python modules/libraries too.

Forgive me if I'm wrong about it.


RE: print(f"{person}:") SyntaxError: invalid syntax when running it - AryaIC - Nov-03-2020

(Nov-03-2020, 07:11 PM)deanhystad Wrote: Does this work?
people = ['me', 'you', 'him', 'her', 'they']
for person in people:
    print(f" {person}:")
A syntax error may have nothing to do with the line that gets flagged. It could be an error that started some line above but only became noticeable at the reported line.
Thanks for the suggestion. I was thinking that too. But unfortunately I should not modify anything else other than joint_probability , update , and normalize function.


RE: print(f"{person}:") SyntaxError: invalid syntax when running it - Axel_Erfurt - Nov-04-2020

(Nov-03-2020, 07:04 PM)AryaIC Wrote: I'm just very nervous if I need to install python 3.6 as you suggested ...

python >= 3.6

means 3.6 or higher


RE: print(f"{person}:") SyntaxError: invalid syntax when running it - AryaIC - Nov-05-2020

(Nov-04-2020, 11:29 AM)Axel_Erfurt Wrote:
(Nov-03-2020, 07:04 PM)AryaIC Wrote: I'm just very nervous if I need to install python 3.6 as you suggested ...

python >= 3.6

means 3.6 or higher

Ok. But already have Python 3.8.3 downloaded from python.org. And the problem/issue remains the same.

The default python is 2.7.10 as I check it in Terminal and this default one should not be messed up, somebody else said to me. And I won't upgrade it.


RE: print(f"{person}:") SyntaxError: invalid syntax when running it - Axel_Erfurt - Nov-05-2020

you have

if len(sys.argv) != 2:
    sys.exit("Usage: python heredityarya.py data.csv")
to use f-strings you should start it with

python3 heredityarya.py data.csv


RE: print(f"{person}:") SyntaxError: invalid syntax when running it - AryaIC - Nov-06-2020

(Nov-05-2020, 09:15 PM)Axel_Erfurt Wrote: you have

if len(sys.argv) != 2:
    sys.exit("Usage: python heredityarya.py data.csv")
to use f-strings you should start it with

python3 heredityarya.py data.csv

Thank you for your kind advice! As you advised, I put down python3 heredityarya.py data.csv , and it worked! What interests me is it didn't work when I only typed python without adding 3 in front of it. Could you pls enlight me on this? Once again, thank you, Sir!