python random numbers and comparison - python

I'm a new programmer and just starting off with Python. I have the following 2 questions, however, I decided to put them in one post.
When asking to input age, how do I force the program to only accept numbers?
The concept is that after the user has entered their age, the program would pick a random number between 1 and 100 and compare it to the user input, returning either "I'm older than you", "I'm younger than you" or "we are the same age".
# 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)

Try the following
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")

Hi you can try this simply.
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")
Only made few changes to existing code with modifications asked.

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")
Includ a try block around the age part. If the user inputs an non-int answer then it will just pass. I then saved the random int that you generated it and compared it to the age to find if the random int was greater than the age.

To answer your first question, use int() as such:
age = int(input("How old are you? "))
This will raise an exception (error) if the value is not an integer.
To answer your second question, you may store the random number in a variable and use it in comparison to the user's age, using conditional statements (if, elif, else). So for instance:
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.")
I hope this answers your question. You can refer to the official Python docs for more info on conditional statements.

My guess is that you should convert the variable age into integer. For example:
age = input("How old are you?")
age = int(age)
This should work.

The answer to the 1st question.
x = int(input("Enter any number: "))
To force the program to enter number add int in your input statement as above.

Related

How to ignore certain strings from user input?

Beginner question:
How do I have my input code ignore certain strings of text?
What is your name human? I'm Fred
How old are you I'm Fred?
How do I ignore user input of the word "I'm"?
How old are you I'm Fred? I'm 25
Ahh, Fred, I'm 25 isn't that old.
How do I again ignore user input when dealing with integers instead?
This is the code I have so far:
name = input("What is your name human? ")
while True:
try:
age = int(float(input("How old are you " + name + "? ")))
if age >= 50:
print(str(age) + "! Wow " + name + ", you're older than most of the oldest computers!")
else:
print ("Ahh, " + name + ", " + str(age) + " isn't that old.")
break
except ValueError:
print("No, I asked how old you were... ")
print("Let us try again.")
You could use .replace('replace what','replace with') in order to acheive that.
In this scenario, you can use something like:
name = input("What is your name human? ").replace("I'm ","").title()
while True:
try:
age = int(input("How old are you " + name + "? ").replace("I'm ",""))
if age >= 50:
print(str(age) + "! Wow " + name + ", you're older than most of the oldest computers!")
else:
print ("Ahh, " + name + ", " + str(age) + " isn't that old.")
break
except ValueError:
print("No, I asked how old you were... ")
print("Let us try again.")
Similarly, you can use for the words you think the user might probably enter, this is one way of doing it.
Why not use the list of words that should be ignored or removed from the input, i suggest you the following solution.
toIgnore = ["I'm ", "my name is ", "i am ", "you can call me "]
name = input("What is your name human? ")
for word in toIgnore:
name = name.replace(word, "")
while True:
try:
age = int(float(input("How old are you " + name + "? ")))
if age >= 50:
print(str(age) + "! Wow " + name + ", you're older than most of the oldest computers!")
else:
print ("Ahh, " + name + ", " + str(age) + " isn't that old.")
break
except ValueError:
print("No, I asked how old you were... ")
print("Let us try again.")
The output is following

Program not printing

I wrote this program but it is not executing when I print it:
age= int(input("How old is your dog?"))
if age>0:
print("Please input positive number")
elif age<=2:
dage= age*10.5
else age>2:
dage=21+((age-2)*4)
print("The dog is", dage, "years old")
print(age)
What am I missing to make it run?
I think you want to unindent the conditional statements. I think your conditional statements also need some work -- I've updated it a bit. See below.
Try
age = int(input("How old is your dog?" ))
dage = 0
if age < 0:
print("Please input positive number")
elif age <= 2:
dage = age*10.5
else:
dage = 21+((age-2)*4)
print("The dog is", dage, "years old")
print("age", age)

How would I make an infinite loop in Python until a user inputs otherwise?

To clarify, this is similar to another question but I feel the answer is easier to understand.
I am making a very simple program for saying what year you will turn "x" years old. (It's a practice from Practice Python... Starting to relearn Python after a while) I would like the program to ask the user what age they want to know, and it does so. This works fine, but I do not remember how to have it keep asking until they write "n" and otherwise keep asking. Any ideas?
Thanks for the help! Code Below:
I've tried using a Java-esque loop, but this isn't Java, and I don't know what I'm doing. Up to any ideas.
# Libraries
import time
# Initial Code
name = input("What's your name? ")
print("Thank you " + name + "!")
age = int(input("How old are you? "))
year = int(input("Now, just for clarification, what year is it? "))
new_age = input("Now enter what age you would like to know! ")
print("Thank you! Now, I'll tell you the year you will turn " +new_age+ "!")
time.sleep(3)
print("Great, that calculation will only take a second or so!")
time.sleep(1.5)
math_year = year - age
answer = int(math_year) + int(new_age)
print(name + ", you will turn " + str(new_age) + " years old in " + str(answer) +"!")
time.sleep(3)
# Loop Code
again = input("Would you like to know another age? Y/n ")
if again == 'Y':
new_age = input("Awesome! What age would you like to know? ")
print("Great, that calculation will only take a second or so!")
time.sleep(1.5)
math_year = year - age
answer = int(math_year) + int(new_age)
print(name + ", you will turn " + str(new_age) + " years old in " + str(answer) +"!")
All results work, it just can't loop after the second time.
You can use while instead of if. Whereas if executes its block of code once, while will execute it again and again until the condition becomes false.
# Loop Code
again = 'Y'
while again == 'Y':
new_age = input("Awesome! What age would you like to know? ")
print("Great, that calculation will only take a second or so!")
time.sleep(1.5)
math_year = year - age
answer = int(math_year) + int(new_age)
print(name + ", you will turn " + str(new_age) + " years old in " + str(answer) +"!")
again = input("Would you like to know another age? Y/n ")
As of python 3.8 (so, sometime after late October this year), you'll be able to use the assignment operator := to take care of those first two lines at once:
# Loop Code
while (again := 'Y'):
...
again = input("Would you like to know another age? Y/n ")
hello try something like
while True:
"""
your code
"""
answer = input("again"?)
if answer == 'Y':
continue
elif answer == 'N':
break
else:
# handle other input as you want to
pass

How can I make a loop in order to ask the user a number when he enter a text for his age [duplicate]

This question already has answers here:
Python check for integer input
(3 answers)
Closed 5 years ago.
I am trying to do a program that asks the user his name, age, and the number of times he wants to see the answer. The program will output when he will turn 100 and will be repeated a certain number of times.
What is hard for me is to make the program asks a number to the user when he enters a text.
Here is my program:
def input_num(msg):
while True:
try :
num=int(input(msg))
except ValueError :
print("That's not a number")
else:
return num
print("This will never get run")
break
name=input("What is your name? ")
age=int(input("How old are you? "))
copy=int(input("How many times? "))
year=2017-age+100
msg="Hello {}. You will turn 100 years old in {}\n".format(name, year)
for i in range(copy):
print(msg)
When you're prompting your user for the age: age=int(input("How old are you? ")) you're not using your input_num() method.
This should work for you - using the method you wrote.
def input_num(msg):
while True:
try:
num = int(input(msg))
except ValueError:
print("That's not a number")
else:
return num
name = input("What is your name? ")
age = input_num("How old are you? ") # <----
copy = int(input("How many times? "))
year = 2017 - age + 100
msg = "Hello {}. You will turn 100 years old in {}\n".format(name, year)
for i in range(copy):
print(msg)
This will check if the user input is an integer.
age = input("How old are you? ")
try:
age_integer = int(age)
except ValueError:
print "I am afraid {} is not a number".format(age)
Put that into a while loop and you're good to go.
while not age:
age = input("How old are you? ")
try:
age_integer = int(age)
except ValueError:
age = None
print "I am afraid {} is not a number".format(age)
(I took the code from this SO Answer)
Another good solution is from this blog post.
def inputNumber(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
break

Why is this simple code wrong?

print("Hello there")
name=input("What is your name?")
print("Welcome to the some game, " + name + "!")
print("I'm going to ask you some basic questions so that we could work together")
age=input("Your age")
if age >= 14 and age < 41:
print("K")
else:
print("Sorry bruh")
print("Thanks")
keeps showing me "Sorry bruh" at the end when entered 15. Why? What's wrong?
Cast your input to int:
age = int(input("Your age"))
You could add a try-except. Your condition should equally be evaluated on or not and
Either you use Python3 and you need to cast with int(input("Your age")) or you use Python2 and then you need to use raw_input to read the name: name=raw_input("What is your name?")
Ok , so you can try this code in python2.7 and it will work as you desired:
print("Hello there")
name=raw_input("What is your name?")
print("Welcome to the some game, " + name + "!")
print("I'm going to ask you some basic questions so that we could work together")
age=input("Your age")
if age >= 14 and age < 41:
print("K")
else:
print("Sorry bruh")
print("Thanks")

Categories

Resources