简体   繁体   English

Python:你如何打印出“正确!” 反而?

[英]Python: How do you print out "Correct!" instead?

 # These lines print out the question, possible answers and a prompt for the user to input
  a string

 print("ART AND LITERATURE: Who painted Starry Night?")
 print("a. Vincent Van Gogh")
 print("b. Michelangelo")
 print("c. Leonardo Da Vinci")
 answer = print(input("Enter your choice:"))
 
# Semantic error: prints out 'a' and 'The correct answer was a' when input is 'a'
# Desired output: "Correct!" when input is 'a' and 'The correct answer was a' for other 
  inputs

 if answer == 'a':
    print("Correct!")

 else:
    print("The correct answer was a")

The first block of code prints out the question, possible answers, and a prompt for the user to input a string.第一段代码打印出问题、可能的答案以及提示用户输入字符串。

The if-else statement has a semantic error as it prints out "a" and "The correct answer was a" even when the input is indeed, "a". if-else 语句存在语义错误,因为即使输入确实是“a”,它也会打印出“a”和“正确答案是 a”。

How do I fix this so that "Correct!"我该如何解决这个问题,以便“正确!” is printed when the input is 'a' and 'The correct answer was a' for other inputs?当输入为 'a' 时打印,其他输入时打印'正确答案为 a'?

You do not need to use print when using input .使用input时不需要使用print

Hence, just execute:因此,只需执行:

print("ART AND LITERATURE: Who painted Starry Night?")
print("a. Vincent Van Gogh")
print("b. Michelangelo")
print("c. Leonardo Da Vinci")
answer = input("Enter your choice:")

if answer == 'a':
    print("Correct!")

else:
    print("The correct answer was a")

OUTPUT:输出:

ART AND LITERATURE: Who painted Starry Night?
a. Vincent Van Gogh
b. Michelangelo
c. Leonardo Da Vinci
Enter your choice:a
Correct!

answer = print(input("Enter your choice:"))更改为answer = input("Enter your choice:")因为第一个只是将值打印到变量中。

answer = print(input("Enter your choice:"))

You assigned a print statement to your answer variable, so when this line is executed, it prints what the user inputs too.您为 answer 变量分配了一个打印语句,因此当执行此行时,它也会打印用户输入的内容。 Quick fix:快速解决:

answer = input("Enter your choice:")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM