要求用戶在Python中輸入整數| 限制用戶僅輸入整數值

input() function can be used for the input, but it reads the value as a string, then we can use the int() function to convert string value to an integer.

input()函數可用于輸入,但它將值讀取為字符串,然后可以使用int()函數將字符串值轉換為整數。

Consider the below program,

考慮下面的程序,

# input a number
num = int(input("Enter an integer number: "))
print("num:", num)

Output

輸出量

RUN 1:
Enter an integer number: 10
num: 10
RUN 2:
Enter an integer number: 12.5
Traceback (most recent call last):
File "main.py", line 2, in <module>
num = int(input("Enter an integer number: "))
ValueError: invalid literal for int() with base 10: '12.5'
RUN 3:
Enter an integer number: Hello
Traceback (most recent call last):
File "main.py", line 2, in <module>
num = int(input("Enter an integer number: "))
ValueError: invalid literal for int() with base 10: 'Hello'

See the output – the program works fine if we input an integer value (RUN 1), but if we input other than integer (RUN 2, RUN3) program returns a ValueError.

看到輸出結果–如果輸入整數值(RUN 1),則程序運行正常,但是如果輸入的不是整數(RUN 2,RUN3),程序將返回ValueError 。

What's next?

下一步是什么?

To handle ValueError, we can use a try-except statement.

為了處理ValueError異常 ,我們可以使用一個嘗試 - 除了聲明。

See the below program,

參見下面的程序,

# input a number
try:
num = int(input("Enter an integer number: "))
print("num:", num)
except ValueError:
print("Please input integer only...")  

Output

輸出量

RUN 1:
Enter an integer number: 10
num: 10
RUN 2:
Enter an integer number: 12.5
Please input integer only...
RUN 3:
Enter an integer number: Hello
Please input integer only...

See the output – the program works fine if we input an integer value (RUN 1), but if we input other than integer (RUN 2, RUN3) program's control transferred to the except block and printed our message. Here, we have handled the exception but still, our task is not completed.

看到輸出結果–如果我們輸入整數值(RUN 1),則程序運行正常,但是如果輸入非整數(RUN 2,RUN3),程序的控制權將轉移到except塊并打印我們的消息。 在這里,我們已經處理了異常,但是仍然沒有完成我們的任務。

What's next?

下一步是什么?

We need to take input until a valid integer value is not entered. For that, we will use while True (for an infinite loop) and will be taking the input till the valid integer.

我們需要接受輸入,直到沒有輸入有效的整數值。 為此,我們將使用while True (用于無限循環),并將輸入輸入直到有效整數。

See the below program,

參見下面的程序,

限制用戶僅輸入整數值的程序 (Program for limiting the user to input only integer value)

# input a number
while True:
try:
num = int(input("Enter an integer number: "))
break
except ValueError:
print("Please input integer only...")  
continue
print("num:", num)

Output

輸出量

Enter an integer number: 12.5
Please input integer only...
Enter an integer number: Hello world
Please input integer only...
Enter an integer number: Ten
Please input integer only...
Enter an integer number: Twenty Four
Please input integer only...
Enter an integer number: 24
num: 24

Finally, we did it. By using this method we can set the limit to the user to input/accept only integers.

最后,我們做到了。 通過使用此方法,我們可以將限制設置為用戶僅輸入/接受整數

Recommended posts

推薦的帖子

  • Read input as an integer in Python

    在Python中將輸入讀取為整數

  • Read input as a float in Python

    在Python中以浮點形式讀取輸入

  • Parse a string to float in Python (float() function)

    解析要在Python中浮動的字符串(float()函數)

  • How do you read from stdin in Python?

    您如何從Python的stdin中讀取信息?

  • Asking the user for input until a valid response in Python

    要求用戶輸入直到Python中的有效響應

  • Input a number in hexadecimal format in Python

    在Python中以十六進制格式輸入數字

  • Input a number in octal format in Python

    在Python中以八進制格式輸入數字

  • Input a number in binary format in Python

    在Python中以二進制格式輸入數字

  • How to get the hexadecimal value of a float number in python?

    如何在python中獲取浮點數的十六進制值?

  • Convert an integer value to the string using str() function in Python

    使用Python中的str()函數將整數值轉換為字符串

  • Convert a float value to the string using str() function in Python

    使用Python中的str()函數將浮點值轉換為字符串

  • Input and Output Operations with Examples in Python

    使用Python中的示例進行輸入和輸出操作

  • Taking multiple inputs from the user using split() method in Python

    使用Python中的split()方法從用戶獲取多個輸入

  • Fast input / output for competitive programming in Python

    快速輸入/輸出,可在Python中進行有競爭力的編程

  • Precision handling in Python

    Python中的精確處理

  • Python print() function with end parameter

    帶有結束參數的Python print()函數

翻譯自: https://www.includehelp.com/python/asking-the-user-for-integer-input-in-python-limit-the-user-to-input-only-integer-value.aspx

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/540491.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/540491.shtml
英文地址,請注明出處:http://en.pswp.cn/news/540491.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

[轉載] python——if語句、邏輯運算符號

參考鏈接&#xff1a; 用Python鏈接比較運算符 1.if條件判斷語句&#xff1a; if 要判斷的條件(True): 條件成立的時候&#xff0c;要做的事情 elif 要判斷的條件(True): .... elif 要判斷的條件(True): .... else: 條件不成立的時候要做的事情 示例&#xff1a; 判斷學生…

洛谷 P2689 東南西北【模擬/搜索】

題目描述 給出起點和終點的坐標及接下來T個時刻的風向(東南西北)&#xff0c;每次可以選擇順風偏移1個單位或者停在原地。求到達終點的最少時間。 如果無法偏移至終點&#xff0c;輸出“-1”。 輸入輸出格式 輸入格式&#xff1a; 第一行兩個正整數x1,y1&#xff0c;表示小明所…

單鏈表遍歷_單鏈表及其遍歷實現的基本操作

單鏈表遍歷單鏈表 (Single linked list) Single linked list contains a number of nodes where each node has a data field and a pointer to next node. The link of the last node is to NULL, indicates end of list. 單個鏈表包含許多節點&#xff0c;其中每個節點都有一…

[轉載] python中for語句用法_詳解Python中for循環的使用_python

參考鏈接&#xff1a; 在Python中將else條件語句與for循環一起使用 這篇文章主要介紹了Python中for循環的使用,來自于IBM官方網站技術文檔,需要的朋友可以參考下 for 循環 本系列前面 “探索 Python&#xff0c;第 5 部分&#xff1a;用 Python 編程” 一文討論了 if 語句和…

windows 軟鏈接的建立及刪除

在windows服務器上有時有這樣的需求&#xff0c;你的文件在f:\test中&#xff0c;但由于其它原因用戶訪問的是e:\test&#xff0c;如果又希望e:\test 中的文件與f:\test的保持同步&#xff0c;除了用同步軟件來做外&#xff0c;可以用windows 的文件夾映射來做 cmd: mklink /J …

8086簡單的指令流水線_在8086微處理器中執行流水線的指令和概念的步驟

8086簡單的指令流水線Any computer or machine works according to some instructions. These instructions are responsible for all the work that the machine does. But how does a machine work to understand and execute that instruction? 任何計算機或機器都按照某些…

[轉載] 使用Python編寫打字訓練小程序

參考鏈接&#xff1a; 在Python中切換大小寫(替換) 你眼中的程序猿 別人眼中的程序猿&#xff0c;是什么樣子&#xff1f;打字如飛&#xff0c;各種炫酷的頁面切換&#xff0c;一個個好似黑客般的網站破解。可現實呢&#xff1f; 二指禪的敲鍵盤&#xff0c;寫一行代碼&#…

shell兩個數字相乘_使用8086微處理器將兩個16位數字相乘而不帶進位

shell兩個數字相乘Problem statement: 問題陳述&#xff1a; To perform multiplication operation between 2 16bit numbers with carry using 8086 Microprocessor. 使用8086微處理器在2個16位數字之間進行帶進位的乘法運算。 Algorithm: 算法&#xff1a; Load the first…

Dwr 框架簡單實例

Dwr 是一個 Java 開源庫&#xff0c;幫助你實現Ajax網站。 它可以讓你在瀏覽器中的Javascript代碼調用Web服務器上的Java&#xff0c;就像在Java代碼就在瀏覽器中一樣。 Dwr 主要包括兩部分&#xff1a; 在服務器上運行的 Servlet 來處理請求并把結果返回瀏覽器。 運行在瀏覽器…

[轉載] Python進階:設計模式之迭代器模式

參考鏈接&#xff1a; Python中的迭代器 在軟件開發領域中&#xff0c;人們經常會用到這一個概念——“設計模式”&#xff08;design pattern&#xff09;&#xff0c;它是一種針對軟件設計的共性問題而提出的解決方案。在一本圣經級的書籍《設計模式&#xff1a;可復用面向對…

JavaScript | 如何為變量分配十進制,八進制和十六進制值?

Just like C programming language, we can assign integer value in the different format to the variable. 就像C編程語言一樣 &#xff0c;我們可以將不同格式的整數值分配給變量。 Assigning decimal value: It can be assigned simply without using any prefix. 分配十…

路由器DHCP和DHCP中繼的配置

路由器 DHCP和DHCP中繼的配置 路由器作為DHCP服務器&#xff1a; 1.配置router的地址&#xff1a;Route(config)# hostname gateway (更改主機名字) Gateway(config)# interface gigabitethernet 0/0 …

[轉載] 大數據分析Python For循環教程

參考鏈接&#xff1a; Python中的迭代器函數1 大數據分析Python除了循環遍歷列表之外&#xff0c;for循環還有很多其他功能&#xff0c;在現實世界的數據科學工作中&#xff0c;您可能需要將numpy數組和pandas DataFrames用于其他數據結構的循環。 大數據分析Python For循環教…

node.js 爬蟲入門總結

node.js爬蟲 前端同學可能向來對爬蟲不是很感冒&#xff0c;覺得爬蟲需要用偏后端的語言&#xff0c;諸如 php &#xff0c; python 等。當然這是在 nodejs 前了&#xff0c;nodejs 的出現&#xff0c;使得 Javascript 也可以用來寫爬蟲了。由于 nodejs 強大的異步特性&#xf…

數組重復次數最多的元素遞歸_使用遞歸計算鏈接列表中元素的出現次數

數組重復次數最多的元素遞歸Solution: 解&#xff1a; Required function: 所需功能&#xff1a; func_occurence ( node *temp) //recursive functionInput: 輸入&#xff1a; A singly linked list whose address of the first node is stored in a pointer, say head and…

SecureCRT中文亂碼解決方法

服務端export LANGzh_CN.UTF-8客戶端SecureCRT編碼選擇UTF-8客戶端SecureCRT字體選擇新宋體&#xff0c;字符集選擇中文總結&#xff1a;客戶端和服務端字符編碼一致&#xff0c;客戶端字體字符集支持轉載于:https://blog.51cto.com/leomars/1972669

[轉載] Python 迭代器 深入理解 與應用示例

參考鏈接&#xff1a; Python | 可迭代和迭代器之間的區別 本篇文章簡單談談可迭代對象&#xff0c;迭代器和生成器之間的關系。 三者簡要關系圖 可迭代對象與迭代器 剛開始我認為這兩者是等同的&#xff0c;但后來發現并不是這樣&#xff1b;下面直接拋出結論&#xff1a; 1…

Python程序查找表示O(1)復雜度的數字所需的位數

Problem statement 問題陳述 Find total Number of bits required to represent a number in binary 查找以二進制表示數字所需的總位數 Example 1: 范例1&#xff1a; input : 10output: 4Example 2: 范例2&#xff1a; input : 32output : 6Formula used: 使用的公式&am…

正則split

string content "第1行導入失敗&#xff0c;失敗原因為&#xff1a; 《加班原因》字段必填";string[] resultString Regex.Split(content, "失敗原因為&#xff1a;", RegexOptions.IgnoreCase);foreach (string i in resultString){Console.WriteLine(i…

將八進制數制轉換為二進制,十進制和十六進制數制

1)將八進制數制轉換為二進制數制 (1) Conversion of Octal Number System to Binary Number System) To convert octal numbers into binary numbers, we can use the relationship between octal and binary numbers. 要將八進制數轉換為二進制數&#xff0c;我們可以使用八進…