簡體   English   中英

如何在python中實現空字符串

[英]how to implement empty string in python

我需要能夠提示用戶輸入一個空字符串,以便它可以檢查答案是否正確。 但是每次這樣做,我都會為int()說無效的文字而出錯,因此我需要更改user_input,以便它可以接受int()和strings()。 我怎樣才能做到這一點?

# program greeting 
print("The purpose of this exercise is to enter a number of coin values") 

print("that add up to a displayed target value.\n") 

print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.") 

print("Hit return after the last entered coin value.")

print("--------------------") 

#print("Enter coins that add up to 81 cents, one per line.")

import sgenrand

    #prompt the user to start entering coin values that add up to 81  
    while True: 
        total = 0 
        final_coin= sgenrand.randint(1,99)

        print ("Enter coins that add up to", final_coin, "cents, on per line") 

        user_input = int(input("Enter first coin: "))

        if user_input != 1 and user_input!=5 and user_input!=10 and user_input!=25:
        print("invalid input")

        else:
            total = total + user_input


        while total <= final_coin:
            user_input = int(input("Enter next coin:"))

            if user_input != 1 and user_input!=5 and user_input!=10 and user_input!=25:
                print("invalid input")                

            else:
                total = total + user_input


        if total > final_coin : 
            print("Sorry - total amount exceeds", (final_coin)) 

        elif total < final_coin:
            print("Sorry - you only entered",(total))

        else: 
            print("correct")    

        goagain= input("Try again (y/n)?:") 

        if goagain == "y":
            continue
        elif goagain == "n":
            print("Thanks for playing ... goodbye!" )
            break
  1. input()返回的值存儲在變量中。
  2. 在調用int()之前,請檢查字符串是否為空
    • 如果為零,則為空字符串。
    • 否則,嘗試int()處理。

暫無
暫無

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

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