如何将用户输入的值转换为具有可用值的变量?

时间:2015-10-02 21:42:10

标签: python python-3.x turtle-graphics

from turtle import*

branch_width=4
grass_color=input("Would you like your grass to be snowy, dead, or healthy? ")
sky_color=input("Would you like it to be morning, afternoon, or evening? ")

morning="cadetblue"
afternoon="cornflowerblue"
evening="royalblue"
snowy="snow"
dead="wheat"
healthy="darkgreen"

每当我尝试将输入用作color(sky_color)时,用户的输入都不会转换为morning="cadetblue"等,这会返回错误。我该如何解决?我是否需要让用户输入颜色?

1 个答案:

答案 0 :(得分:0)

您混淆了变量名称和字符串。 您将名为 morning 的变量设置为字符串“cadetblue”。 这与输入字符串“morning”无关。 必须明确地设置它。

字典会对此有所帮助:

sub test_step_3 {

    my $toops = gen_random_4_toops( 1, 100, 5 );

    print "---- random 4-toops:\n";

    my $tn = 1;
    foreach ( @{ sort_random_4_toops_by_sum( @{$toops} ) } ) {
        print "toop $tn:\t(@{$_}); " . sum( @{$_} ) . "\n";
        $tn++;
    }

    print "---- random 4-toops sorted by sum:\n";

    my $sorted_toops = sort_random_4_toops_by_sum( @{$toops} );

    $tn = 1;
    foreach ( @{$sorted_toops} ) {
        print "toop $tn:\t(@{$_}); sum = " . sum( @{$_} ) . "\n";
        $tn++;
    }
}

现在你可以试试

interpret_color = {
    "morning": "cadetblue",
    "afternoon": "cornflowerblue",
    "evening": "royalblue",
    "snowy": "snow",
    "dead": "wheat",
    "healthy": "darkgreen"
}

这会让你感动吗?