簡體   English   中英

為什么這個python while循環在程序中不起作用?

[英]why does this python while loop not work in the program?

我正在嘗試在以下文章中運行該程序:

https://blockgeeks.com/guides/python-blockchain-2/

我已將所有代碼復制到我的Spyder IDE中。 當我運行它時,有一個while循環開始,要求用戶從它打印的選項列表中選擇一個數字。

選擇一個數字后,程序應執行請求的操作。 當我選擇它時,它只是循環回到while循環的開始。

它似乎忽略了while循環中的其余代碼(if語句部分)。

令人困惑的是,如果我從while循環中使用的程序中獲取代碼的一部分,並分別運行它們,它們會起作用,即,如果我運行以下代碼並選擇數字1,它將在if語句中運行代碼。

為什么if語句在這里運行而不在主程序中運行?

#function 1:
def get_user_choice():

   user_input = input("enter a number: ")

   return user_input

#function 2:
def get_transaction_value():

   tx_recipient = input('Enter the recipient of the transaction: ')

   tx_amount = float(input('Enter your transaction amount '))

   return tx_recipient, tx_amount

while True:
   print("Choose an option")

   print('Choose 1 for adding a new transaction')

   print('Choose 2 for mining a new block')

   print('Choose 3 for printing the blockchain')

   print('Choose anything else if you want to quit')

   user_choice = get_user_choice()



   if user_choice == '1':
       tx_data = get_transaction_value()
       print(tx_data)

更新:對不起,我意識到我可能還不太清楚問題是什么。

上面的代碼是整個程序的代碼的一部分,可以獨立於主程序按預期運行。

以下代碼是鏈接中文章的整個程序。 它包括程序中的所有代碼。 如果我運行此主程序,則while循環不使用if語句。 在我選擇了1、2或3之后,它似乎剛剛脫離了循環(無論如何,其他任何數字都應該脫離循環)。

這是一個屏幕快照的鏈接,顯示了我為選項選擇了數字1后控制台的外觀。

https://ibb.co/RNy2r0m

# Section 1
import hashlib

import json



reward = 10.0



genesis_block = {

   'previous_hash': '',

   'index': 0,

   'transaction': [],

   'nonce': 23

}

blockchain = [genesis_block]

open_transactions = []

owner = 'Blockgeeks'



def hash_block(block):

   return hashlib.sha256(json.dumps(block).encode()).hexdigest()

# Section 2
def valid_proof(transactions, last_hash, nonce):

   guess = (str(transactions) + str(last_hash) + str(nonce)).encode()

   guess_hash = hashlib.sha256(guess).hexdigest()

   print(guess_hash)

   return guess_hash[0:2] == '00'



def pow():

   last_block = blockchain[-1]

   last_hash = hash_block(last_block)

   nonce = 0

   while not valid_proof(open_transactions, last_hash, nonce):

       nonce += 1

   return nonce

# Section 3
def get_last_value():

   """ extracting the last element of the blockchain list """

   return(blockchain[-1])



def add_value(recipient, sender=owner, amount=1.0):

   transaction = {'sender': sender,

   'recipient': recipient,

   'amount': amount}

   open_transactions.append(transaction)

# Section 4

def mine_block():

   last_block = blockchain[-1]

   hashed_block = hash_block(last_block)

   nonce = pow()

   reward_transaction = {

           'sender': 'MINING',

           'recipient': owner,

           'amount': reward

       }

   open_transactions.append(reward_transaction)

   block = {

       'previous_hash': hashed_block,

       'index': len(blockchain),

       'transaction': open_transactions,

       'nonce': nonce

   }

   blockchain.append(block)

# Section 5

def get_transaction_value():

   tx_recipient = input('Enter the recipient of the transaction: ')

   tx_amount = float(input('Enter your transaction amount '))

   return tx_recipient, tx_amount



def get_user_choice():

   user_input = input("Please give your choice here: ")

   return user_input

# Section 6

def print_block():

   for block in blockchain:

       print("Here is your block")

       print(block)

# Section 7

while True:

   print("Choose an option")

   print('Choose 1 for adding a new transaction')

   print('Choose 2 for mining a new block')

   print('Choose 3 for printing the blockchain')

   print('Choose anything else if you want to quit')

   user_choice = get_user_choice()



   if user_choice == 1:

       tx_data = get_transaction_value()

       recipient, amount = tx_data

       add_value(recipient, amount=amount)

       print(open_transactions)



   elif user_choice == 2:

       mine_block()



   elif user_choice == 3:

       print_block()



   else:

       break


  [1]: https://i.stack.imgur.com/FIrn7.png

比較值時,Python在數據類型方面比其他一些語言更強。 這意味着Python中沒有字符串將等於數字。

或者換句話說, "1" == 1將為False

這意味着您必須考慮在Python 3中您將從input()接收到一個字符串input()在Python 2中不一定如此)。

您可以將其直接與另一個字符串進行比較:

user_choice = input()

if user_choice == "1":
    print("You chose item 1")

或者,您可以先將其轉換為數字,然后將其與數字進行比較:

user_choice = int(input())

if user_choice == 1:
    print("You chose item 1")

請注意,在前一種情況下,如果用戶輸入多余的空格,則可能不夠魯棒;而在后一種情況下,如果用戶未輸入整數(甚至根本沒有輸入),它將大聲失敗。

如果需要,可以使用額外的代碼來處理這兩種方式。 在前一種情況下,可以使用user_input = input().strip()空格,而在后一種情況下,可以使用try ... except ...塊捕獲異常。

您只處理了user_choice == '1' 如果輸入非1,程序將控制權返回到while循環的開始。

我建議您使用調試器查看if條件之前的user_choice 如果沒有,則僅使用打印件。

print("user_choice: {}, type: {}".format(user_choice, type(user_choice))

暫無
暫無

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

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