【问题标题】:Run a function in the 'if statement'在“if 语句”中运行函数
【发布时间】:2022-01-11 04:20:16
【问题描述】:

当我如下运行 clear() 时,它不会打印“else”语句。它仅适用于“如果”部分。当我在外面运行一个缩进时,它会在不打印 if 和 else 的情况下清除。请指导我应该把它放在哪里。

import random
from art import logo,vs
from game_data import data
from replit import clear

def game_question():
  return random.choice(data)

def format_data(account):
    account_name = account["name"]
    account_description = account["description"]
    account_country = account["country"]

    return f"{account_name}, {account_description}, {account_country}" 

  
def count(num_a, num_b):
    if num_a > num_b:
     return  "a"
    else:
      return "b"

win = 0

play_on = False

while not play_on:
  print (logo)

  account_a = game_question()
  account_b = game_question()

  if account_a == account_b:
    account_b = game_question()
  
  num_a = account_a["follower_count"]
  num_b = account_b["follower_count"]

  print(f"Account A : {format_data(account_a)}")
  print (vs)
  print(f"Compare to Account B: {format_data(account_b)}")

  ans = input("Which account has more followers? A or B: ").lower()

  if ans == count(num_a,num_b):
    win += 1
    print ("A win")

  else:
    print (f"Wrong. You lose. Win = {win}")
    play_on = True
  clear()  

【问题讨论】:

  • 请使用 4 个空格进行缩进,因为这是公认的社区标准,在 PEP 8 -- The Style Guide for Python Code 中定义。您的缩进无处不在,很容易导致错误或意外行为。
  • 也许你想做的是在 clear() 之前插入一点延迟,例如 time.sleep(3),让人们有时间在控制台被清除之前阅读文本。

标签: python function if-statement import while-loop


【解决方案1】:

clear() 函数在 else: 中的缩进不正确。试试这个 if else 语句

if ans == count(num_a,num_b):
  win += 1
  print ("A win")

else:
  print (f"Wrong. You lose. Win = {win}")
  play_on = True
  clear()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 2015-05-03
    • 2021-04-24
    • 2022-07-28
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    相关资源
    最近更新 更多