Python条件语句成绩判断报错:如何解决grade未定义的NameError问题
Fixing the
NameError for grade & Running Your Python Script Hey there! That NameError is popping up because you're trying to use the grade variable before you've told Python what it is. Let's break down how to fix this, plus walk through running your simple script.
Step 1: Define the grade variable
You need to assign a value to grade before your if statement. Here are a few easy ways to do this, depending on what you want:
Option 1: Hardcode a value
If you just want to test the logic with a specific score, assign a number directly:
# Define the grade variable first grade = 85 # Now your condition will work if grade >= 80 and grade < 90: print("You got a B!")
Option 2: Get input from the user
If you want to let someone type in a score, use input() (and convert it to an integer since input() returns a string by default):
# Ask the user for their grade and convert it to an integer grade = int(input("Enter your score: ")) if grade >= 80 and grade < 90: print("You got a B!")
Step 2: Run your Python module
Since you already saved your code as automate tasks for beginners.py, here's how to run it:
Using Command Prompt (Windows)
- Open Command Prompt (search for "cmd" in the Start menu).
- Navigate to the folder where your script is saved. For your path, type:
cd C:\Users\onura\Desktop\Kodlama Egzersizleri - Run the script with:
Note: Ifpython "automate tasks for beginners.py"pythondoesn't work, trypython3instead.
Using an IDE (like VS Code or PyCharm)
- Open your
.pyfile in the IDE. - Look for a "Run" button (usually a play icon in the top right corner) and click it. The output will show up in the IDE's terminal panel.
内容的提问来源于stack exchange,提问作者modionur
相关产品推荐
相关产品推荐

