簡體   English   中英

應用`raw_input`時如何使用`if`?

[英]How do you use `if` when applying a `raw_input`?

我對 Python 和一般編碼有點raw_input ,我需要一些幫助來處理raw_inputif語句。 我的代碼如下;

    age = raw_input ("How old are you? ")
    if int(raw_input) < 14:
    print "oh yuck"
    if int(raw_input) > 14:
    print "Good, you comprehend things, lets proceed"

問題

您的代碼存在三個問題:

  • Python 使用縮進來創建塊。
  • 您已將輸入分配給變量age ,因此請使用age
  • 在 Python 3 中,你必須使用print(...)而不是print ...

正確的解決辦法

age = raw_input("How old are you? ")

if int(age) < 14:
    print("oh yuck")
else:
    print("Good, you comprehend things, lets proceed")

請注意,這不等同於您的代碼。 您的代碼跳過 case age == 14 如果你想要這種行為,我建議:

age = int(raw_input("How old are you? "))

if age < 14:
    print("oh yuck")
elif age > 14:
    print("Good, you comprehend things, lets proceed")

學習 Python

if int(raw_input) < 14:

應該是int(age) ,另一個if應該是一樣的。 raw_input是您調用的函數,但您將其結果存儲在變量age 你不能把一個函數變成一個整數。

而不是反復將年齡轉換為整數,你可以只做一次,當你做輸入時:

age = int(raw_input("How old are you? "))

然后你可以做if age > 14等等,因為它已經是一個整數。

我假設縮進問題(每個if后面的行應該縮進至少一個空格,最好是四個)只是一個格式問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM