Python If statement and logical operator issue [duplicate]

血红的双手。 提交于 2019-12-26 18:36:52

问题


I'm trying to create a small python program to emulate rolling a single die. My problem arises in that I want the program to accept both upper and lower-case 'Y' to trigger a re-roll. My program works when I accept either upper or lower case y but when I try to change the line

if usr == 'Y'

to

if usr == 'Y' or 'y'

creates a problem where it never enters the else statement, making the program never terminate.

import random

def DiceRoll():
 number = random.randrange(1, 7, 1)
 print("Dice Roll: ", number)
 AskUser()
 return

def AskUser():
 usr = input("Roll Again? (Y/N) \n")
 if usr == 'Y':
     DiceRoll()
 else :
     print("Thank you for playing!")
return

DiceRoll()

回答1:


You must do

if usr == 'Y' or usr == 'y'.

It is currently evaluating the statement 'y' as its own condition, and in this case 'y' always evaluates to true.



来源:https://stackoverflow.com/questions/45016954/python-if-statement-and-logical-operator-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!