python脚本中的逻辑问题

python脚本中的逻辑问题
#!/usr/bin/env python3
# tarchiver.py
# Purpose: Creates a tar archive of a directory
#
# USAGE: ./tarchiver.py
#
# Author:
# Date January 15th 2023
import os

correct_answer = 'yes'
correct_answer2 = 'no'
compression1 = 'gzip'
compression2 = 'bzip2'
compression3 = 'xzip'

print("Please enter the directory you would like to archive")
directory = input()
print("Please enter the name of the archive")
name = input()
print("Would you like your archive to be compressed?")
answer = input()
while correct_answer != answer or correct_answer2 != answer:
    answer = input()
    print('Please enter either yes or no')
    if answer == correct_answer or answer == correct_answer2:
        break
if answer == 'yes':
    print("What kind of compression do you want?")
    print("gzip, bzip2, or xzip?")
    answer2 = input()
    while compression1 != answer2 or compression2 != answer2 or compression3 != answer2:
        print('Please enter a valid answer')
        answer2 = input()
        if answer2 == compression1 or answer == compression2 or answer == compression3:
            break
    if answer2 == "gzip":
        os.system(f"tar -cvPzf {name} {directory}")
    if answer2 == "bzip2":
        os.system(f"tar -cvPjf {name} {directory}")
    if answer2 == "xzip":
        os.system(f"tar -cvPJf {name} {directory}")

我对代码中的逻辑有疑问。当它询问我是否想要压缩并输入“是”时,我必须输入两次才能使代码继续进行下一部分。另外,当它要求输入类型并且我输入“gzip”时,它首先告诉我这是一个无效的输入,我需要更正我的答案,但我只是输入相同的内容,然后它继续执行其余的部分代码。这是一个学校项目,我是 python 新手,所以如果有一个明显的解决方案可以解决这个问题,请原谅。

答案1

while compression1 != answer2 or compression2 != answer2 or compression3 != answer2: answer2 最多只能等于一种压缩类型,因此它将不等于至少两种。因此这条线相当于 while True:

并且您始终必须输入压缩类型,直到您break

相关内容