The project is to create a simple Python program that will prompt the user for his or her age and then print out the lower and upper age limits for the user's date based on the Permissible Dating Age Algorithm.
The PDA Algorithm is: d = a/2 + 7, a is your age, and d is the lowest permissible age of your date where a is an integer.
Here is the code I have so far:
import random
import sys
import time
def findACompanion():
print "Welcome to the Permissible Dating Age Program!"
sys.stdoutflush()
time.sleep(3)
a = float(raw_input("What is your age?"))
if a <= 14:
print "You are too young!"
else:
d = a/2 + 7
print "You can date someone"
print d
print "years old."
It seems to be running okay, yet nothings printing out and I'm confused as to what's going wrong with the print statements.
You weren't that far off the mark to be honest but your print statements were not faulty. Rather, they are contained within a function that you never call so they never actually run. There is also a small typo. This code will run:
import random #Not needed with current code
import sys
import time
def findACompanion():
print "Welcome to the Permissible Dating Age Program!"
sys.stdout.flush() #You missed a full-stop
time.sleep(3)
a = float(raw_input("What is your age?"))
if a <= 14:
print "You are too young!"
else:
d = a/2 + 7
print "You can date someone"
print d
print "years old."
#Something to call your function and start it off
start_program = findACompanion()
Stick with the classes, it won't take long till it falls into place. Being thrown in at the deep-end is the best way :)
You've defined a function findACompanion, but nothing is calling the function, so none of the statements within the function are being executed. You can call it yourself from the prompt:
>>> findACompanion()
There's a convention that is common in Python to detect if you are running a file as your main program and to make the call automatically, see Top-level script environment. The convention calls for the function to be called main but you can call anything you'd like.
if __name__ == "__main__":
findACompanion()
Related
I'm super new to programming and I'm learning python. I am excited to announce that I have written 3 short programs so far. I am experimenting with while and for loops but can't get either implemented into my programs. Here is my pseudocode trying to use a for loop for the first time.
Declare count
Run leapyearprogram3
Count + 1 = Count
Go back to line 2
I appreciate that there are multiple ways of doing this (range, xrange, while, etc.) and I am trying to understand how a for loop works and how to implement it in more than just the following code.
# My leap year Python program.
# This program demonstrates the following:
# Determines if a user input of year is a leap year using the calendar
# function
#
# Author: Thomas Schuhriemen
# Course: CIS1400
import calendar
t1= int(input())
print ("Welcome to my leap year program")
print ("You may type any year and I will tell you if it is a leap year")
# some of the following is based on code written by INDIAN VILLAN on
# comments on w3resource.com
# 3.0 is a stable build but this one (4.1) is experimenting with for to
# repeat the question.
count = 0
for count >= 5:
if calendar.isleap(t1) is True:
print (t1, "is a leap year.")
else:
print (t1, "is not a leap year.")
count = count + 1
I can't seem to grasp why this keeps giving me errors. I have given me an error saying there is something wrong with the code immediately following the for command the code it says "for count >= 5 & count <= 0:" has an invalid syntax error highlighting the
"="
Thank you for your interest in helping me learn how to use for!
Thomas. Don't worry about the harsh tries at the beginning of your journey. I suggest you take a look at The Python Tutorial, a tutorial for beginners, at the official Python documentation. Here is the link to the explanation of the for loop.
For now, keep this in mind: one of the most basic concepts of a programming language (in fact, even of human language) is the syntax. It means everything has its rightful place in a sentence, so a meaning can be taken out of this sentence.
In Python, the for loop has the following basic syntax:
for [variable] in [collection of things]:
[block of code inside the loop]
Everything I put inside brackets you can modify.
See that the words for and in (and also the colon at the end) are mandatory. You have to keep them in this setup.
As I said, take a look at The Python Tutorial, at your own pace, from the beginning to the end. It will give you a boost in learning Python through the best source of information: the official Python documentation.
import calendar
print ("Welcome to my leap year program")
print ("You may type any year and I will tell you if it is a leap year")
count = 0
for i in range(5):
count = count + i
t1= int(input())
if calendar.isleap(t1): # returns true if t1 is leap year else returns
false
print (t1, "is a leap year.") # if test condition is true
else:
print (t1, "is not a leap year.") # if test condition is false
I learned proper syntax and I was able to come up with this. Thanks everyone who posted suggestions on learning about for.
The for loop syntax is wrong and there is no need to use it here. Refer the Python Wiki here
import calendar
print ("Welcome to my leap year program")
print ("You may type any year and I will tell you if it is a leap year")
count = 0
while count <= 5:
t1= int(input())
if calendar.isleap(t1): # returns true if t1 is leap year else returns false
print (t1, "is a leap year.") # if test condition is true
else:
print (t1, "is not a leap year.") # if test condition is false
count = count + 1
See this in action here
import calendar
print ("Welcome to my leap year program")
print ("You may type any year and I will tell you if it is a leap year")
count = 0
for i in range(5):
count = count + i
t1= int(input())
if calendar.isleap(t1): # returns true if t1 is leap year else returns
false
print (t1, "is a leap year.") # if test condition is true
else:
print (t1, "is not a leap year.") # if test condition is false
So I'm fairly new to python and for my programming class, I have to write a program about a 100 metre race and tells if you qualified or not based on the time it took you to finish. If you're a male and you took longer than 10.18 seconds to finish; then you didn't qualify. If you're a female and it took you longer than 11.29 seconds to finish; then again, you didn't qualify.
My problem is that both messages saying if you qualified or didn't qualified appear no matter what your time was. I am using Python 2.7.10. My code so far is:
gender = raw_input("Are you Male (M) or Female (F)?: ")
time = raw_input("What time did you get for the 100m race?: ")
if gender is "M" and time > 10.18:
print "Sorry, you did not qualify"
else:
print "Congratulations, you qualified!"
if gender is "F" and time > 11.29:
print "Sorry, you did not qualify"
else:
print "Congratulations, you qualified!"
Raw_input returns a string. You need to do
time = float(raw_input("What time..."))
(Note that python will allow you to compare a string to a float, but it doesn't try to convert the string to match)
(Edit: And as noted by the other two answers at the time of this posting, you should use elif)
Try using elif for better handling
if gender is "M" and time > 10.18:
print "Sorry, you did not qualify"
elif gender is "F" and time > 11.29:
print "Sorry, you did not qualify"
else:
print "Congratulations, you qualified!"
The else for each clause will always run because gender will always be opposite to what the user has inputted. You also need to cast the 2nd input to float to correctly compare the value to either 10.18 or 11.29.
To correct this (without refactoring):
gender = raw_input("Are you Male (M) or Female (F)?: ")
time = float(raw_input("What time did you get for the 100m race?: "))
if gender is "M" and time > 10.18:
print "Sorry, you did not qualify"
elif gender is "F" and time > 11.29:
print "Sorry, you did not qualify"
else:
print "Congratulations, you qualified!"
Take the logic step-by-step. Let's consider an example of a Female with a time of 10 seconds:
The first 'if' comes out False, because she's female (False AND anything is still False, so the time doesn't even matter). So the first "Sorry" message doesn't get printed.
But since that 'if' was not executed, the 'else' immediately following does get executed, printing the message.
That's the problem: Just because someone is not a Male who failed, doesn't mean that they are a Male who succeeded. The female we're using as an example is neither.
Then, after incorrectly printing that message, it tries all over again for the female-who-failed case, and prints the message you did want.
You need to make the logic of the program, exactly match the logic of the real-life situation. So think in detail about which decisions affect what other decisions in this case.
I'll leave the exact change up to you, since that's likely what your teacher wants you to work through and figure out.
Basically I want to record high scores in my program. I'm new to coding so need a bit of help. I will create this basic program to demonstrate what I want.
import time
name = input("Please enter your name: ")
mylist=["Man utd are the best team","I am going to be a pro typer.","Coding is really fun when you can do it."]
x=random.choice (mylist)
print ("The sentence I would like you to type is: ")
print (x)
wait = input ("Please press enter to continue, The timer will start upon hitting enter!")
start = time.time()
sentence = input("Start typing: ")
end = time.time()
overall = end - start
if sentence == (x):
print ("It took you this many seconds to complete the sentence: %s" % overall)
if overall <= 9:
print ("Nice job %s" % name)
print ("You have made it to level 2!")
How would I be able to save the time it took and if someone beats the time make that the new high score?
You're looking for a way to persist data across program executions. There are many ways to do it, but the simplest is just writing to a file.
In addition, if you want to use a database, look into SQLite3 for Python.
I start my python script asking the user what they want to do?
def askUser():
choice = input("Do you want to: \n(1) Go to stack overflow \n(2) Import from phone \n(3) Import from camcorder \n(4) Import from camcorder?");
print ("You entered: %s " % choice);
I would then like to:
Confirm the user has entered something valid - single digit from 1 - 4.
Jump to corresponding function based on import. Something like a switch case statement.
Any tips on how to do this in a pythonic way?
Firstly, semi-colons are not needed in python :) (yay).
Use a dictionary. Also, to get an input that will almost certainly be between 1-4, use a while loop to keep on asking for input until 1-4 is given:
def askUser():
while True:
try:
choice = int(input("Do you want to: \n(1) Go to stack overflow \n(2) Import from phone \n(3) Import from camcorder \n(4) Import from camcorder?"))
except ValueError:
print("Please input a number")
continue
if 0 < choice < 5:
break
else:
print("That is not between 1 and 4! Try again:")
print ("You entered: {} ".format(choice)) # Good to use format instead of string formatting with %
mydict = {1:go_to_stackoverflow, 2:import_from_phone, 3:import_from_camcorder, 4:import_from_camcorder}
mydict[choice]()
We use the try/except statements here to show if the input was not a number. If it wasn't, we use continue to start the while-loop from the beginning.
.get() gets the value from mydict with the input you give. As it returns a function, we put () afterwards to call the function.
I'm having trouble with the extra credit on Exercise 13 of Learn Python the Hard Way.
It wants me to combine argv with raw_input, which I can't figure out.
Could anyone help me out? Examples would be great!
Thanks so much!
Edit: The original code for the exercise is:
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
an example would be indistinguishable from the answer, which is unlikely to be the best way to help you. perhaps you are overthinking the question, though. i believe the idea is to use some command-line input (which goes into argv) and some entered input (which comes through raw_input) to make a script which reports on both. For example, it might produce:
The script is called: ex13.py
Your first variable is: cheese
Your second variable is: apples
You entered the following data: foo bar baz
This is how I tried to do it:
from sys import argv
script, weather, feeling = argv
print "Hot or Cold",
weather = raw_input()
print "Happy or sad",
feeling = raw_input()
print "The name of the script is:" , script
print "The day is:", weather
print "Today I am feeling:", feeling
import sys
def main():
all_args = sys.argv[:]
user = None
while user != 'STOP':
user = raw_input('You have %d args stored. Enter STOP or add another: ' % len(all_args))
if user != 'STOP':
all_args.append(user)
print 'You entered %d args at the command line + %d args through raw_input: [%s]' % (len(sys.argv), len(all_args) - len(sys.argv), ', '.join(all_args))
if __name__ == '__main__':
main()
This was confusing to me as well. The author puts this in his faq at the bottom.
Q: I can't combine argv with raw_input().
A: Don't overthink it. Just slap two lines at the end of this script that uses raw_input() to get something and then print it. From that start playing with more ways to use both in the same script.
Here is how I solved this: (note: you still have to provide the arguments when initially running the script)
from sys import argv
script, first, second, third = (argv)
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
first = raw_input("\nNew First Variable? ")
second = raw_input("New Second Variable? ")
third = raw_input("New Last Variable? ")
print "\n\nYour new variables are %s, %s, and %s" % (first, second, third)
Here's the output I get:
C:\Users\mbowyer\Documents\Python_Work>python ex13a.py 1 2 3
The script is called: ex13a.py
Your first variable is: 1
Your second variable is: 2
Your third variable is: 3
New First Variable? a
New Second Variable? b
New Last Variable? c
Your new variables are a, b, and c
C:\Users\mbowyer\Documents\Python_Work>