I am extremely new to coding and I'm currently working with this.
print("What month were you born?")
m = input()
print("What day were you born?")
d = input()
print("What year were you born?")
y = input()
print("Your birthday is " + m + "/" + d + "/" + y)
If I input January 1 2000 for my birthday I get January/1/2000 but the output I want is 1/1/2000. Any advice?
You need a way to map the month name to the number representing the month. This can be done with a list or dictionary. Below we have a list of months. The number representing that month is simply the index of the month in the list + 1:
print("What month were you born?")
m = input()
print("What day were you born?")
d = input()
print("What year were you born?")
y = input()
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
print("Your birthday is " + str(months.index(m)+1) + "/" + d + "/" + y)
You can build upon this and add code to make the input case-insensitive and catch exceptions if the user enters the wrong value.
print("What month were you born?")
m = input()
newm = 'lol'
if m == "January" or "january":
newm = '1'
if m == "February" or "february":
newm = '2'
#KEEP GOING TILL DECEMBER
print("What day were you born?")
d = input()
print("What year were you born?")
y = input()
print("Your birthday is " + newm + "/" + d + "/" + y)
The other comments here are suggesting things that aren't on your level of skill. I think this answers your question in a way that you can understand what is happening.
When you get better, there are better ways to go about doing this, such what the other comments have suggested. There are even better ways of doing this code lol such as ignoring case on January/january.
Related
So I want to calculate the day of the week by a given user input:
input1 = int(input("Please enter the year in which you were born\n"))
input2 = int(input("Please enter the month in which you were born\n"))
input3 = int(input("Please enter the day on which you were born\n"))
if 1 <= input2 <= 2:
input1 -= 1
elif input2 < 3:
input2 = input2 + 10
else:
input2 = input2 - 2
print(f'On which day of the week were you born?\n'
f'Please input your answer of the day of the week as follows:\n'
f'"mo", "tu", "we", "th", "fr", "sa", "su"')
inputweekday = str(input(f'Enter the day of the week on which you were born here\n'))
week_days=["su", "mo", "tu", "we", "th", "fr", "sa"]
D = abs(input1) % 100
C = int(str(input1)[:2])
A = 13*(input2 +1)
F = (input3 + (A//5) + D + (D//4) + (C//4) - 2*C) % 7
for i, x in enumerate(week_days):
if F == i:
F = x
if F == inputweekday:
print('You were correct.')
else:
print(f'Your answer was not correct.')
sys.exit(0)
I dont know why I cant seem to get the right days. Ive been struggling for hours and i couldnt find the answer online since almost all of them are implementented on C++.
Any tips?
Try this:
year = int(input("Please enter the year in which you were born\n"))
month = int(input("Please enter the month in which you were born\n"))
day = int(input("Please enter the day on which you were born\n"))
if month < 3:
month += 12
year -= 1
# inputweekday = str(input(f'Enter the day of the week on which you were born here\n'))
week_days=["sat", "su", "mo", "tu", "we", "th", "fr"]
century = int(year / 100)
century_year = year % 100
weekday = (day + 13*(month + 1)//5 + century_year + century_year//4 + century//4 - 2*century) % 7
print(weekday)
print(week_days[weekday])
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
I need to find the len() of multiple strings.
current_year = input ("What year is it?")
current_year = int(current_year)
birth_year = input ("What year were you born in?")
birth_year = str(birth_year)
if len(birth_year) != 4:
print ("Please make your year of birth 4 digits long.")
else:
birth_year = int(birth_year)
print("You are " + str(current_year - birth_year) + " years old.")
I would like to include the len() of birth_year.
Use an elif statement to check the current year input.
current_year = input ("What year is it?")
birth_year = input ("What year were you born in?")
if len(birth_year) != 4:
print ("Please make your year of birth 4 digits long.")
elif len(current_year) != 4:
print ("Please make the current year 4 digits long.")
else:
birth_year = int(birth_year)
current_year = int(current_year)
print("You are " + str(current_year - birth_year) + " years old.")
There's no need for birth_year = str(birth_year), since input() always returns a string.
You should probably include try/except code around the calls to int(), so you can print an error if they enter a year that isn't actually a number.
Here is a way to get what you want that is somewhat more dynamic. With this basic function, if a user inputs an inappropriate string, they will be asked to retry. You could even add a line to check if the year was after the current year.
Note that there is a loop in here with an exit that doesn't have a constraint. If you were going to implement this, I'd add a counter as well which would kill the process to prevent infinite loops.
def get_year(input_string):
# Set loop control Variable
err = True
# while loop control variable = true
while err == True:
# get input
input_year = input(input_string + ' ')
# Ensure format is correct
try:
# Check length
if len(input_year) == 4:
# Check Data type
input_year = int(input_year)
# if everything works, exit loop by changing variable
err = False
# if there was an error, re-enter the loop
except:
pass
# return integer version of input for math
return input_year
# set variables = function output
birth_year = get_year('What year were you born? Please use a YYYY format!\n')
current_year = get_year('What is the current year? Please use a YYYY format!\n')
# print output displaying age
print("You are " + str(current_year - birth_year) + " years old.")
I'm learning Python, and decided to dab with a 'What year is it' thing. Here's what I have:
from datetime import datetime
now = datetime.now()
currentyear = now.year
userinput = input("What year is it? ")
if userinput == currentyear:
print ("Correct! The year is %s") % (currentyear)
However, it never prints out. What am I doing wrong?
As others have pointed out, Python 3 does not implicitly evaluate input. Using a call to int() will fix the issue.
from datetime import datetime
now = datetime.now()
currentyear = now.year
userinput = input("What year is it? ")
if int(userinput) == currentyear
print ("Correct! The year is %s") % (currentyear)
For the month of February I am trying to make it so it has 3 correct answers for the number of days in the month 28,29 29 28 but it doesn't seem to be working when I try to change
user = int(input(""))
if month == "January":
answer = 31
elif month == "Feburary":
answer = 28
to
user = int(input(""))
if month == "January":
answer = 31
elif month == "Feburary (use comma to seperate two numbers)":
answer = 28,29 or 28 or 29
I realise that there is a problem with using integer in the input but I am not sure how to fix that with the comma and it won't let me put a space in between the 28 and 29 .
This is the rest of the code:
import random
import shelve
from tkinter import *
result = []
highscore = []
root = Tk()
highscore = 0
correct = 0
d = shelve.open('highscore.txt')
d['highscore'] = highscore
d.close()
name = input("What is your name: ")
print ("Hello there",name,"!")
for count in range(12):
month = random.choice(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"])
while month in result:
month = random.choice(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"])
result.append(month)
print ("How many Days in?", month)
user = int(input(""))
if month == "January":
answer = 31
elif month == "February":
answer = 28,29 or 29 or 28
elif month == "March":
answer = 31
elif month == "April":
answer = 30
elif month == "May":
answer = 31
elif month == "June":
answer = 30
elif month == "July":
answer = 31
elif month == "August":
answer = 31
elif month == "September":
answer = 30
elif month == "October":
answer = 31
elif month == "November":
answer = 30
elif month == "December":
answer = 31
if user == answer:
print("Correct!")
correct = correct + 1
else:
print ("Wrong, the correct answer was", answer)
if correct > highscore:
highscore = correct
print (name,", You Beat The Highscore and got",highscore,"Out Of 12")
photo = PhotoImage(file='/Users/HoneyCentaur/Desktop/Approval.gif')
photo_label = Label(image=photo)
photo_label.grid()
photo_label.image = photo
text = Label(text=" ")
text.grid()
root.deiconify()
root.mainloop()
else:
print (name, ", You Got", correct, "Out Of 12")
d = shelve.open('highscore.txt')
d['highscore'] = highscore
d.close()
You will likely want to use a list to check if the user answer was in the list of possible answers for the number of days in a month. you can then use the in keyword in python check if user is in the possible answers list.
The code would look a bit like the following:
if month == "Janurary":
answer=[31]
elif month == "Feburary":
answer=[28,29]
if user in answer:
print("Correct!")
correct = correct + 1
EDIT #1
Keep in mind there are many other options for going at this. To have a single element in a list kind of defeats the purpose and hinders understandability.
A better option might be to just cast the users answer from 28 to 29 or vice-a-versa if you're just using it to count points:
if month == "Janurary":
answer=31
elif month == "Feburary":
if(user == 28):
user = 29
answer=29
if user in answer:
print("Correct!")
correct = correct + 1
I believe "or" is only used for boolean or comparison operations.
i.e.
if month == "Janurary" or month == "Feburary":
do_something
if the quiz is looking for the possible "last days" of a month, I'm assuming the function would want a list of options.
if month == "Janurary":
answer=[31]
elif month == "Feburary":
answer=[28,29]