简体   繁体   English

Python 2.7打印问题

[英]Python 2.7 Trouble With Printing

I'm making a program that will convert digital storage units. 我正在制作一个可以转换数字存储单元的程序。 Like, you could ask it how many bits are in x amount of megabits. 就像,您可以问它x兆位中有多少位。 I'm just testing it with one if statement, but I CANNOT get it to print the answer. 我只是用一个if语句测试它,但是我无法显示它。

import re

UNITS = ["bit", "byte", "exabit", "exabyte", "gigabit", "gigabyte", 
"kilobit", "kilobyte", "megabit", "megabyte", "petabit", "petabyte", 
"terabit", "terabyte"]

PLURAL_UNITS = ["bits", "bytes", "exabits", "exabytes", "gigabits", 
"gigabytes", "kilobits", "kilobytes", "megabits", "megabytes", "petabits", 
"petabytes", "terabits", "terabytes"]

PROMPT_1 = "How many "
PROMPT_2 = "are in "

def convert():
    first_unit = raw_input(PROMPT_1)
    second_unit = raw_input(PROMPT_2)

    number_of = re.findall('\d+', second_unit)

    number = number_of[0]

    if first_unit == PLURAL_UNITS[0] and second_unit == " " + PLURAL_UNITS[1]:
        answer = float(number)*8
        print(answer)


convert()

Look at this line: 看这行:

if first_unit == PLURAL_UNITS[0] and second_unit == " " + PLURAL_UNITS[1]:

With this line your code will only print if the first input is "bits" and the second input is " bytes" . 在此行中,仅当第一个输入为"bits"而第二个输入为" bytes"您的代码才会打印。 Inputting anything else makes the code under the if statement (which includes your print ) get skipped. 输入其他任何内容都会使if语句下的代码(包括print )被跳过。

It doesn't print because it doesn't reach your print statement. 它不会打印,因为它没有到达您的print语句。 One or both of your conditions of your if statement is False . if语句的条件之一或全部为False To check which, print their results: 要检查哪个,请打印其结果:

def convert():
    first_unit = raw_input(PROMPT_1)
    second_unit = raw_input(PROMPT_2)

    number_of = re.findall('\d+', second_unit)

    number = number_of[0]

    print('first check:', first_unit == PLURAL_UNITS[0])
    print('second check:', second_unit == " " + PLURAL_UNITS[1])
    if first_unit == PLURAL_UNITS[0] and second_unit == " " + PLURAL_UNITS[1]:
        answer = float(number)*8
        print(answer)


convert()

In python2, print is a statement, not a function. 在python2中,print是一个语句,而不是一个函数。 print answer 打印答案

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

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