输入为输入时检查字母

2024-09-30 08:28:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我写的这段代码是为一个用户输入一个数字,然后电脑给你pi,用小数点后的数字量作为用户的选择。我想检查用户是否输入“Q”退出程序。问题是,当我把这个数字转换成一个整数以确保它不大于15时,我就不能检查这个数字是否是q。同时,如果我将输入转换为str,我将无法检查该数字是否大于15,任何帮助都将不胜感激,谢谢

import math
import sys


def piee():
    pie = str(math.pi)
    pi_list = list(pie)

    print(pie)

    try:
        num = int(input("How many numbers after the decimal do I show?, max is 15 - "))
    except ValueError:
        print("That's not a number!")
        sys.exit()

    if num > 15:
        print("That's too large of a number!")
        sys.exit()
    elif num < 1:
        print("That's too small of a number!")
        sys.exit()

    new_num = num + 2
    del pi_list[new_num:]
    final = ''.join(pi_list)
    print(final)
    again = input("Again? [Y/N] ").lower()
    if again == 'y':
        print('+' * 25)
        piee()
    else:
        sys.exit()
piee()

Tags: 用户importnumberthatsysexitpi数字
1条回答
网友
1楼 · 发布于 2024-09-30 08:28:48

非常接近

try:
    inp = input("How many numbers after the decimal do I show?, max is 15 - ")
    num = int(inp)
except ValueError:
    if inp == 'Q':
        sys.exit()
    else:
        print("That's not a number!")

注意,sys.exit()散落在各处。他们中的大多数人都应该回来

相关问题 更多 >

    热门问题