简体   繁体   中英

first python program, what am i doing wrong

This is my attempt at a simple dice game. when I run the program it asks me how many dice I want to roll when I enter 1, it just asks again and then closes the program.

I feel like at least one of my problems is that the input maybe isn't being read as an integer? I'm not really sure. In the mean time, I'm gonna stare at it for a while and maybe ill figure it out.

import random


def roll1Dice():
    roll = random.randint(1,6)
    print("You rolled a " + roll)


def roll2Dice():
    roll1 = random.randint(1,6)
    roll2 = random.randint(1,6)
    print("You rolled a " + roll1)
    print("You rolled a " + roll2)


def main():
    input("roll 1 or 2 dice? ")
    if input == 1:
        roll1Dice()
    elif input == 2:
        roll2Dice()

    else:
        print("Please enter a 1 or a 2.")

main()

input is a function that returns a str . You need to capture this return and then compare it.

def main():
    user_input = input("roll 1 or 2 dice? ")
    if user_input == '1': # notice that I am comparing it to an str
        roll1Dice()
    elif user_input == '2':
        roll2Dice()
    else:
        print("Please enter a 1 or a 2.")
        main() # add this line to request input again

Alternatively, you could cast to an int:

def main():
    user_input = int(input("roll 1 or 2 dice? "))
    if user_input == 1: # notice that I am comparing it to an int here
        roll1Dice()
    elif user_input == 2:
        roll2Dice()
    else:
        print("Please enter a 1 or a 2.")
        main()

If you cast to an int, however, be aware that a non-int will cause an exception.

You weren't assigning the value of input to anything (input is the function that actually accepts user input) Also, your print statements were failing because they were trying to combine an int with a string, so I've replaced it using string formatting. The below code should help

import random
def roll1Dice():
    roll = random.randint(1,6)
    print("You rolled a %s" % roll)

def roll2Dice():
    roll1 = random.randint(1,6)
    roll2 = random.randint(1,6)
    print("You rolled a %s" % roll1)
    print("You rolled a %s" % roll2)

def main():
    myinput = input("roll 1 or 2 dice? ")
    if myinput == 1:
        roll1Dice()
    elif myinput == 2:
        roll2Dice()

    else:
        print("Please enter a 1 or a 2.")
main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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