Python Forum
print(f"{person}:") SyntaxError: invalid syntax when running it
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
print(f"{person}:") SyntaxError: invalid syntax when running it
#1
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.
Reply
#2
you need to use python >= 3.6 for f-strings
Reply
#3
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.
Reply
#4
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.
Reply
#5
(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.
Reply
#6
(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.
Reply
#7
(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
Reply
#8
(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.
Reply
#9
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
Reply
#10
(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!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Making a Class Person ? Kessie1971 3 1,146 Apr-23-2023, 05:20 PM
Last Post: deanhystad
  Invalid syntax Slome 2 1,974 May-13-2022, 08:31 PM
Last Post: Slome
  Invalid syntax error, where? tucktuck9 2 3,433 May-03-2020, 09:40 AM
Last Post: pyzyx3qwerty
  How can create class Person :( Azilkhan 1 1,972 Nov-21-2019, 08:12 AM
Last Post: DeaD_EyE
  Invalid syntax defining a dictionary? ep595 6 5,113 Nov-19-2019, 08:06 PM
Last Post: ThomasL
  Syntax Error: Invalid Syntax in a while loop sydney 1 4,089 Oct-19-2019, 01:40 AM
Last Post: jefsummers
  [split] Please help with SyntaxError: invalid syntax Mason 1 2,210 Apr-28-2019, 06:58 PM
Last Post: Yoriz
  SyntaxError: Invalid syntax in a while loop ludegrae 3 14,759 Dec-18-2018, 04:12 PM
Last Post: Larz60+
  SyntaxError: invalid syntax at run .py tuxo9999 10 7,290 Aug-23-2018, 03:58 PM
Last Post: Axel_Erfurt
  Homework: Invalid syntax using if statements chehortop 3 3,668 Mar-01-2018, 04:38 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020