python随机数和比较

时间:2018-02-09 05:37:27

标签: python random numbers

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

  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)
    

6 个答案:

答案 0 :(得分:2)

尝试以下

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")

答案 1 :(得分:1)

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:
    try:
        age = int(input("How old are you? "))
    except ValueError:
        pass 
print("Hello " + str(name) + ", you are " + str(age) + " years old.")

my_random = random.randint(1, 100)
if  my_random > age:
    print("Im older than you")
elif my_random < age:
    print("I'm younger than you")
else:
    print("We are the same age")

在年龄段周围加上一个试块。如果用户输入非int答案,那么它将通过。然后我保存了你生成它的随机int,并将它与年龄进行比较,以找出随机int是否大于年龄。

答案 2 :(得分:1)

嗨,你可以试试这个。

import random
name = input("What is your name? ")
print("Hello " + str(name))
while True :
    try :
        age = int(input("How old are you? "))
        break
    except :
        print("Your entered age is not integer. Please try again.")
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
randNumber=random.randint(1, 100)
if randNumber > age :
    print("I am older than you")
if randNumber < age :
    print("I am younger than you")
else :
    print("we are the same age")

仅对要求修改的现有代码进行了少量更改。

答案 3 :(得分:1)

要回答第一个问题,请使用int()

age = int(input("How old are you? "))

如果该值不是整数,则会引发异常(错误)。

要回答第二个问题,您可以将随机数存储在变量中,并使用条件语句(ifelif将其与用户的年龄进行比较,else)。例如:

random.seed()  # you need to seed the random number generator
n = random.randint(1, 100)

if n < age:
    print("I am younger than you.")
elif n > age:
    print("I am older than you.")
else:
    print("We are the same age.")

我希望这能回答你的问题。有关条件语句的更多信息,请参阅official Python docs

答案 4 :(得分:0)

我的猜测是你应该将变量age转换为整数。例如:

年龄=输入(“你多大了?”)

age = int(age)

这应该有用。

答案 5 :(得分:0)

第一个问题的答案。

x = int(输入(“输入任意数字:”))

如上所述,强制程序在输入语句中输入数字add int。我也是python的初学者。