This question already has answers here:
Date Ordinal Output?
(14 answers)
Closed 6 years ago.
I have been developing a small program.
It works perfectly how it is but I want to make the code a bit smaller.
import time, math
name= input("Enter Your Name: ")
age= int(input("Enter Your Age: "))
end= "th"
if age == 3 or age == 13 or age == 23 or age == 33 or age == 43 or age == 53 or age == 63 or age == 73 or age == 83 or age == 93:
end= "rd"
if age == 2 or age == 22 or age == 32 or age == 42 or age == 52 or age == 62 or age == 72 or age == 82 or age == 92:
end= "nd"
print ("Your Name Is "+ name + ", You Are " + str(age) + " Years Old.")
print ("Hi " + name + ", Happy " + str(age) + end + " birthday!")
time.sleep(5)
I would like to have an easier way to change the 'end' to other values without having to write them all, can I have it start at 3 then do it for everything 10 more than three.
Use the modulo operator:
if age % 10 == 3:
end = "rd"
elif age % 10 == 2:
end = "nd"
Or use a dict:
ends = {2: "nd", 3: "rd"}
end = ends[age % 10]
You can also use a default:
ends = {1: "st", 2: "nd", 3: "rd"}
end = ends.get(age % 10, "th)
Extract the digit at tenth's place. Then it's straightforward. Though this question belongs to the codereview counterpart of SO.
import time, math
name= input("Enter Your Name: ")
age= int(input("Enter Your Age: "))
tenth_place = age % 10
if tenth_place == 3:
end = "rd"
elif tenth_place == 2:
end = "nd"
else:
end = "th"
print ("Your Name Is "+ name + ", You Are " + str(age) + " Years Old.")
print ("Hi " + name + ", Happy " + str(age) + end + " birthday!")
time.sleep(5)
if age in range(3,93,10) :
end = "rd"
You can try this:
if int(age[-1]) == 3:
end= "rd"
if int(age[-1]) == 2:
end= "nd"
Might not be shorter necessarily, but it works (and keeps 12th and 13th proper).
import time, math
name = input("Enter Your Name:")
age = int(input("Enter Your Age:"))
end = "th"
# initializing age lists
list1 = []
list2 = []
# filling list1 with ages 3-93
for i in range(0,10):
list1.append(10*i+3)
# filling list2 with ages 2-92
for i in range(0,10):
list2.append(10*i+2)
# if block to include correct suffix
for ages in list1:
if ages == 13:
end = end;
elif ages == age:
end = "rd"
for ages in list2:
if ages == 12:
end = end
elif ages == age:
end = "nd"
print ("Your Name Is "+ name + ", You Are " + str(age) + " Years Old.")
print ("Hi " + name + ", Happy " + str(age) + end + " birthday!")
time.sleep(5)
Thanks For All Of It Guys,
I have also found another flaw and fixed it, here is my current code.
Thanks.
import time, math
name= input("Enter Your Name: ")
age= int(input("Enter Your Age: "))
end= "th"
if age % 10 == 3:
end = "rd"
elif age % 10 == 2:
end = "nd"
elif age % 10 == 1:
end = "st"
if age < 20 and age > 10:
end = "th"
print ("Your Name Is "+ name + ", You Are " + str(age) + " Years Old.")
print ("Hi " + name + ", Happy " + str(age) + end + " birthday!")
time.sleep(2)
Thanks,
Bilbo
Related
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
How do I print only 1 copy of data? I am a complete beginner. This is Python code I did for Add data.
This is my current output:
Row | Name | Age | Grade
1 jo 23 1
2 jo 23 1
1 ki 24 2
2 ki 24 2
This is my expected output:
Row | Name | Age | Grade
1 jo 23 1
2 ki 24 2
Here is my code:
name = []
age = []
grade = []
record = []
rowCount = 0
choice = 1
while int(choice) != 0:
if int(choice) > 4 or int(choice) < 1:
choice = input ("Invalid input. Enter choice: ")
else:
print("Main Menu:")
print("1- Add")
print("2- Delete")
print("3- Edit")
print("4- Print Report")
print("0- End Program")
choice = input ("Enter choice: ")
if int(choice) == 1: #Add function
name.append(input("Input Name: "))
age.append(input("Input Age: "))
grade.append(input("Input Grade: "))
print ("Row | Name | Age | Grade")
for x, y, z in zip(name,age,grade):
for w in range(len(name)):
print(str(w+1) + " " + x + " " + y + " " + z)
w+1
elif int(choice) == 2: #Delete function
print("Delete func")
elif int(choice) == 3: #Update function
print("Edit func")
elif int(choice) == 4: #Print function
print("Print func")
print("Ending Program...")
For each entry in zip(name, age, grade), you have another nested loop (for w). This causes the program to print multiple rows per entry. One way to solve it is to include w inside the zip; i.e., replacing
for x, y, z in zip(name,age,grade):
for w in range(len(name)):
print(str(w+1) + " " + x + " " + y + " " + z)
w+1
with
for x, y, z, w in zip(name, age, grade, range(len(name))):
print(str(w+1) + " " + x + " " + y + " " + z)
You could use a list of lists for each group of data, then use set function
For example:
students = []
...
while True:
name = input("Input Name: ")
age = input("Input Age: ")
grade = input("Input Grade: ")
student.append([name, age, grade])
Then, to get only the unique data on your list of lists, you can use set, but set doesn't work on list of lists, so you can iterate though it and treat each list as a tuple, then use set on the tuples, which I adapted from this answer i.e.:
unique_students = set(tuple(row) for row in (students)))
Now you have a new variable with the unique data from students and you can iterate though it and print the data as you wish.
How do I stop from printing an extra input line? I'm new with python/coding
class1 = "Math"
class2 = "English"
class3 = "PE"
class4 = "Science"
class5 = "Art"
def get_input(className):
classInput = raw_input("Enter the score you received for " + className + ": ")
while int(classInput) >= 101 or int(classInput) <= -1:
print "Needs to be in the range 0 to 100"
classInput = raw_input("Enter the score you received for " + className + ": ")
return int(classInput)
def get_letter_grade(grade):
if grade >= 93:
return"A"
elif grade >= 90:
return"A-"
elif grade >= 87:
return"B+"
elif grade >= 83:
return"B"
elif grade >= 80:
return"B-"
elif grade >= 77:
return"C+"
elif grade >= 73:
return"C"
elif grade >= 70:
return"C-"
elif grade >= 67:
return"D+"
elif grade >= 63:
return"D"
elif grade >= 60:
return"D-"
else:
return"F"
print "Your " + class1 + " score is " + str(get_input(class1)) + ", you got a " +
get_letter_grade(get_input(class1))
Prints out:
Enter the score you received for Math: 85
Enter the score you received for Math: 85
Your Math score is 85, you got a B
Inside your print, you call get_input() method twice:
print "Your " + class1 + " score is " + str(get_input(class1)) + ", you got a " +
get_letter_grade(get_input(class1))
What you need to do is store your score by calling get_input() method once and use the stored value in print method:
score = get_input(class1)
print("Your " + class1 + " score is " + str(score) + ", you got a " +
get_letter_grade(score))
I would separate out your calls to get_input from your print statement, not just here, but generally.
score = str(get_input(class1))
print "Your " + class1 + " score is " + score + ", you got a " +
get_letter_grade(score)
As a rule of thumb, any user input should almost always be immediately stored in a variable to be manipulated and/or used later.
a = input("Enter your Full Name ")
b = int(input("Enter your age "))
if b >= 20:
print("You can drive " + a)
else:
print("You can't drive " + a + " You are underage")
i want to print only first name here, so if given name is Don Jon then the output should be "You can drive Don" or You can't drive Don You are underage
You need:
a = input("Enter your Full Name ")
b = int(input("Enter your age "))
if b >= 20:
print("You can drive ", a.split()[0])
else:
print("You can't drive " , a.split()[0]," You are underage")
You can also use str.find()
a = input("Enter your Full Name ")
b = int(input("Enter your age "))
if b >= 20:
print("You can drive ", a[:a.find(" ")])
else:
print("You can't drive " , a[:a.find(" ")]," You are underage")
I'm making a guessing game and i need to know how to stop it from putting my answers in lexicographical order as that makes a bug in my game.
I've tried instead of having elif Guess < str(value): making it elif Guess < int(value): but i get the error message "'<' not supported between instances of 'str' and 'int'" and i'm having no luck with anything else
Here is the code im working with
from random import *
from random import randint
import os
numbers = []
Guesses = []
dif = []
os.system('CLS')
print("I want you to guess my number")
print("\n \n \n \nIf you give up type 'give up' word for word")
f = open("Data.txt", "a")
print("Say 'yes' If You're Ready")
YN = input()
if YN == "yes":
os.system('cls')
print("Select a difficulty")
print('impossible 1 - 10000')
print('annoying 1 - 1000')
print('hard 1 - 500')
print('medium 1 - 200')
print('easy 1 - 99')
print('beginner 1 - 10')
diff = input()
if diff == 'easy':
os.system('CLS')
value = randint(1, 99)
numbers.append(value)
dif.append(diff)
elif diff == 'beginner':
os.system('CLS')
value = randint(1, 10)
numbers.append(value)
dif.append(diff)
elif diff == 'medium':
os.system('CLS')
value = randint(1, 199)
numbers.append(value)
dif.append(diff)
elif diff == 'hard':
os.system('CLS')
value = randint(1, 499)
numbers.append(value)
dif.append(diff)
elif diff == 'annoying':
os.system('CLS')
value = randint(1, 1000)
numbers.append(value)
dif.append(diff)
elif diff == 'impossible':
os.system('CLS')
value = randint(1, 10000)
numbers.append(value)
dif.append(diff)
os.system('cls')
while True:
Guess = input()
if Guess == "give up":
print("The Number Was " + str(numbers))
f.write("------------------------------------------------------------- \n \r")
f.write("Guesses " + str(Guesses) + "\n \r")
f.write("Difficulty: " + str(dif) + "\n \r")
f.write("[USER GAVE UP] \n \r")
f.write("Correct Answer: " + str(numbers) + "\n \r")
f.write("------------------------------------------------------------- \n \r")
break
elif Guess < str(value):
print("Higher")
Guesses.append(Guess + " - Higher")
elif Guess > str(value):
print("Lower")
Guesses.append(Guess + " - Lower")
elif Guess == str(value):
os.system('CLS')
length = len(Guesses)
f.write("------------------------------------------------------------- \n \r")
f.write("Guesses " + str(Guesses) + "\n \r")
f.write("Difficulty: " + str(dif) + "\n \r")
f.write("Number Of Guesses [" + str(length) + "]\n \r")
f.write("Correct Answer: " + str(numbers) + "\n \r")
f.write("------------------------------------------------------------- \n \r")
print("That Was Correct!")
for x in Guesses:
print(x)
break
input()
You may try to convert Guess from str to int, and compare in integer.
elif int(Guess) < value:
As maruchen notes you should be casting the Guess variable and not the value variable.
However, that alone is still going to leave you with problems. The user isn't forced to enter an integer and indeed string answers such as "give up" are expected. If you try an cast a string to an integer and the string contains non-numerics, then you will be faced with a ValueError. So best is to define a function like this:
def guess_less_than_value(guess, value):
try:
return int(guess) < int(value)
except ValueError:
return False
Then you can but in the body of your code:
if guess_less_than_value(Guess, value):
....
And likewise with greater than.