[英]Check that a variable that has been input is between a range of two numbers, and print out a message afterwards
name = input("Hello user! What is your name?")
print("Welcome " + name + " to Rock, Scissor, Paper, Lizard, Spock!")
while True:
try:
roundsplayed = int(input("Choose how many rounds you want to play from 1 to 5!"))
except ValueError:
print("Sorry, Not a interger!")
continue
else:
break
if 1 < roundsplayed < 6:
print("You have chosen " + roundsplayed " rounds to play!")
所以我有了這個,到現在為止一切似乎都在起作用。
if 1 < roundsplayed < 6:
print("You have chosen " + roundsplayed " rounds to play!")
它帶有無效的語法,但不知道為什么,因為“ print”命令正確對齊(至少我認為是這樣)
有人有解決方案嗎?
我編譯了這段代碼 ,現在可以正常使用了
name = input("Hello user! What is your name?")
print("Welcome " + name + " to Rock, Scissor, Paper, Lizard, Spock!")
while True:
try:
roundsplayed = int(input("Choose how many rounds you want to play from 1 to 5!"))
except ValueError:
print("Sorry, Not a interger!")
continue
else:
break
if 1 < roundsplayed < 6:
print("You have chosen " + str(roundsplayed)+ " rounds to play!")
問題在於最后一行和str(roundsplayed)的縮進。 另外,您在同一行中缺少+號。
您無法在python中使用+運算符連接字符串和數字。 您要么需要將-運算符用作-
print("print("You have chosen",roundsplayed,"rounds to play!")
或者您可以將數字轉換為字符串值-
print("You have chosen " + str(roundsplayed) " rounds to play!")
如果您使用+運算符而不將數字值轉換為字符串,則會收到無效的運算符錯誤。
您可以使用range
函數來檢查數字范圍內的成員資格。 鏈接
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(2,6) [2, 3, 4, 5]
使用字符串格式而不是串聯鏈接 。 這樣可以避免不必要的類型轉換
name = input("Hello user! What is your name?") print("Welcome " + name + " to Rock, Scissor, Paper, Lizard, Spock!") while True: try: roundsplayed = int(input("Choose how many rounds you want to play from 1 to 5!")) except ValueError: print("Sorry, Not a interger!") continue else: break if roundsplayed in range(2, 6): print("You have chosen {} round to play".format(roundsplayed))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.