gpt4 book ai didi

python随机数和比较

转载 作者:太空宇宙 更新时间:2023-11-04 08:36:12 25 4
gpt4 key购买 nike

我是一名新程序员,刚开始使用 Python。我有以下 2 个问题,但是,我决定将它们放在一个帖子中。

  1. 当要求输入年龄时,如何强制程序只接受数字?
  2. 这个概念是,在用户输入他们的年龄后,程序会选择 1 到 100 之间的随机数并将其与用户输入进行比较,返回“我比你大”、“我“比你小”或“我们同龄”。

    # Print Welcome Message
    print("Hello World")
    # Ask for Name
    name = input("What is your name? ")
    print("Hello " + str(name))
    # Ask for Age
    age = input("How old are you? ")
    print("Hello " + str(name) + ", you are " + str(age) + " years old.")
    random.randint(1, 100)

最佳答案

尝试以下操作

import random
# Print Welcome Message
print("Hello World")
# Ask for Name
name = input("What is your name? ")
print("Hello " + str(name))
# Ask for Age
while True: # only numbers
try:
age = int(input("How old are you? "))
except:
pass

print("Hello " + str(name) + ", you are " + str(age) + " years old.")
t=random.randint(1, 100)
if t==age:
print("we are the same age") #compare ages
if t<age:
print("I'm younger than you")
if t>age:
print("I'm older than you")

关于python随机数和比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48699343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com