Python Program counting and list question - python

I made a Python program to repeat the number of internships that I applied for, BUT I need it to store the amount I add so that I can ask it later how many I applied for, rather than me having to enter a number every time. Also, I want it to be able to update if the number of internships I applied for changes, I will input the new number of internships manually. How can I change my program to do that? Please take a look thanks
print("Welcome back, Ryan")
internships = {}
asking_ryan = True
amount = input("Enter how many internships you have applied for: ")
amount = int(amount)
if amount > 1:
print("You have applied for: " + str(amount) + " internship(s)")
str(amount)
if amount < 1:
print("Error! you cannot apply for 0 internships!")
if amount == 1:
print("You have applied for: " + str(amount) + " internship")
Program output:
Welcome back, Ryan.
Enter how many internships you have applied for: 2
You have applied for: 2 internship(s)

I saw your question. I kind of understand it.
You want to be able to update the internships you have done so you don't have to always rerun the program so it counts your internship?
You might have to use some files for that, should be simple!
First, you can make a file called opens.txt and add a 0 to the file that tracks how many times you opened that program. When you run the program do this:
opens = open("opens.txt", w+)
open_count = int(opens.read())
opens.write(open_count + 1)
if open_count == 1:
amount = input("Enter how many internships you have applied for: ")
... # Other Code
Then make a file called something like internships.txt where it will store how many internships you currently have, default it to 0.
internships = open("internships.txt", w+)
internship_count = int(internships.read())
print("You currently have applied to {} internships since last time...".format(internship_count)
new_internships = input("How many new internships have you applied for? ")
internships.write(internship_count + new_internships)
I think this should help? Haven't used files in a long time. Next time please phrase your question a bit better.

Related

why is the return of the program not good?

I'm new to python and there's a video on Youtube that I watched. I do the exact same code as he but mine doesn't work and I don' understand why.
Here's the code:
MAX_LINES = 3
def deposit():
while True:
amount = input("What would you like to deposit? $")
if amount.isdigit():
amount = int(amount)
if amount > 0:
break
else:
print("Amount must be greater than 0. ")
else:
print("Please enter a number. ")
return amount
def get_number_of_lines():
while True:
lines = input("Enter the number of lines to bet on (1-" + str(MAX_LINES) + ")? ")
if lines.isdigit():
lines = int(lines)
if 1 <= lines <= MAX_LINES:
break
else:
print("Please enter a valid number of lines. ")
else:
print("Please enter a number. ")
return lines
There are 3 problems.
Unindent amount does not match previous indent. I have no idea what does that mean
"return" can be used only within a function. As far as I'm concerned I'm using it in the function, copied the first function then pasted it into the second function and somehow it doesn't work
"lines" is not defined. What dou you mean it's not defined, I define it in the first line of the function
https://www.youtube.com/watch?v=th4OBktqK1I
This video's code what I'm trying to do
I appreciate any help!
I just simply don't understand why it works in one and not the other
You have one space too much in front of while True in function get_number_of_lines().
Yes used in functions to return value
Because function don't get inside while loop (because of indent problem), lines is never defined, probably this was the problem.
So try fix indent and run again

How do I use file handling to add create a txt file which saves the score of the player in a simple number guessing game on python?

So basically I have this number guessing game for my school project-
import random
import math
lower = int(input("Enter Lower bound:- "))
upper = int(input("Enter Upper bound:- "))
x = random.randint(lower, upper)
def num_of_chances(U,L):
return round(math.log(U - L + 1, 2))
print("You've only ",num_of_chances(upper,lower)," chances to guess the integer!")
count = 0
while count < num_of_chances(upper,lower):
count += 1
guess = int(input("\nGuess a number:- "))
if x == guess:
print("\nCongratulations you did it in ",count, " try")
break
elif x > guess:
print("You guessed too small!")
elif x < guess:
print("You Guessed too high!")
if count >= math.log(upper - lower + 1, 2):
print("\nThe number is %d"% x)
print("\tBetter Luck Next time!")
I had to somehow implement file handling into this code, so I though about doing something which allows the user to play multiple times and keep track of their wins/ losses and to save the username (which will have to ask for) and the wins/ losses in a file and allow the user to view the leaderboard pulled from that file.
Thing is the codes based on file handling which I have practiced were way simpler than this, and I do not really understand how do I go about to approach this. I have the deadline in 2 hours, and I have absolutely no idea what to do right now(I wasn't slacking off before this, I actually was studying the entire time for an extremely competitive entrance exam).
Please suggest me the approach that I should go about to code this, keeping it as simple as possible, and also if possible write the code, I'll be more than grateful !
It depends on how you want to do the filehandling; do you want to have it in a .txt file for each user, do you want a .csv file, are you allowed to use other libraries for the file-handling (e.g pandas). You write ".txt" file in the title, but do not mention if it has to be a .txt file in the question.
You can create a simple .csv file with the structure
#user_stats.csv
username,wins,loss
eg.
#user_stats.csv
user,wins,loss
user1,5,10
user2,3,100
user3,0,1
which you read/write using pandas.read_csv (docs) or df.to_csv("user_stats.csv",index=False") (docs).
Then you just load that in the beginning:
username = input("Enter username:")
df_stats = pd.read_csv("user_stats.csv") #load stats
df_stats = df_stats.loc[df_stats["user"]==username] #Get user with the provided username (if exists)
.
.
.
Then you can just increment df_stats["wins"] by 1 if they win or the loss by 1 if they loose.
Make sure to handle the difference between a new user and when the username is incorrect when you load the user_stats at the beginning (if you want to)

My function is too long. In order to pass class I need < 18 lines

So I am a total beginner yet this is 100% my code and I am proud of it. Now mind you I need a little cleaning up, however it does what I want it too. My issue is this: In order to turn this in for credit, one of the things is that procedures(functions) should not contain more than 18 lines. My function gameCont() has many more. Would anyone have suggestions on how I could shorten it up? Additionally I am obviously challenged when it comes to function parameters so any help is appreciated. Please be gentle as I am BRAND NEW! :)
game1 = "When dealing with SCUBA diving there are many dangers to consider. The very first one is _1_. \
I mean if you take water into your lungs, you are NOT SCUBA diving. Another is rising to the surface too quickly which could \
result in the _2_. Now this is a funny name, as I am sure when it happens, you dont feel 'bendy'. Let's also consider Nitrogen Narcosis.\
If you dont know what that is, well when you are very deep and your body is absorbing more nitrogen than it is used to, you can get \
feeling kinda _3_ feeling as though you just drank not one, but _4_ martinis"
game1_answers = ["drowning", "bends", "drunk", "2"]
game2 = "When you first learn to dive you are taught to do dives within a no DECOmpression limit(NDL). \n This means you do not want to \
stay that deep too long or you will rack up _1_. \n If you DO stay longer than what the NDL allows, you will have an obligation to \
take your time getting to the surface allowing that _2_ gas to leave your body. If you were taking IN gas you may call it \
in-gassing, but when you are decompressing, it may be called _3_-gassing. You are taught also, how to read _4_"
game2_answers = ["deco", "nitrogen", "off", "tables"]
game3 = "Equipment used by cold water divers such as myself are as such. On my head I would wear a _1_. To help regulate the breathing\
pressure from my SCUBA tank I would use a _2_. To help me propel through the water I would place_3_ on my feet. Considering \
we cannot see underwater I need to be wearing a _4_ on my face. Diving in the tropic, many people would use wetsuits, however it's\
very cold where I dive so we wear _5_ suits."
game3_answers = ["hood", "regulator", "fins", "mask", "dry"]
def howManyTries():
gameTries = raw_input("Thanks for giving my quiz a try, how many attempts do you want? ")
return int(gameTries)
def game_choice(): #this function is used to determin which difficulty the user wants and returns the proper game and answer list
user_input = raw_input("Greetings. This is my Udacity project for fill in the blanks. Which one of my options would you like?\
easy, hard, or hardest? Please take note of capitalization ")# this will define the user_input variable to raw input placed in by user
print ("\n" * 20)# just something to clean up the screen
print "Decided to choose " + user_input + '?' " Well " + user_input + " it is"# this confirms to the user which difficulty they chose.
print ""
print ""
if user_input == "easy": #easy returns game1 and game1 answers
return game1, game1_answers
elif user_input == "hard": # hard returns game2 and game2 answers
return game2, game2_answers
elif user_input == "hardest": #hardest returns game3 and game 3 answers
return game3, game3_answers
else:
print "It seems that " + user_input + " is not a valid response" #in case the user doesnt choose or spell choice correctly
def gameCont():
blanks = 1 #this assings blank to 1 which will tell the user which blank they are guessing in below prompt
attempts = howManyTries() #this calls the howManyTries function for a user choice integer
quiz, answers = game_choice() #this returns 2 values (game# and game# answers)
while attempts > 0: #while attempts (called from function) is greater than 0 we will loop this
print quiz #prints the chosen quiz for user updated each time the loop runs with correct answer
print("\n" * 10) #clears some more screen to loook better for the user
guess = raw_input("Reading the above paragraph, What would your guess be for _" + str(blanks) + "_") #asks for guess for current blank which always starts at 1
print("\n" * 10) #clears some more screen to loook better for the user
if guess == answers[blanks - 1]: #because indexing count starts at zero, and blanks start at 1 this will check if answer is equal to blanks - 1
print "As you can see your correct choice has replaced the variable, great job!!"#this will print if the guess is correct
quiz = quiz.replace("_" + str(blanks) +"_", answers[blanks - 1]) # here is the line of code that replaces the blank with the correct guess
blanks += 1 # this adds 1 to the blank which will prompt the user to move to the NEXT blank when loop begins again
if blanks > len(answers):
print ("\n" * 10)
print "YOU DID IT!! Here is the final paragraph with all the correct answers"
print ("\n" * 2)
print quiz
break
elif guess != answers[blanks -1]: #if the answer does not match the list index
attempts = attempts - 1 #then we will subtract 1 from the attempts
print ("\n" * 10)
print "Oops that is not correct, there should be hints in the paragraph" # lets user know they were wrong
print "You have " + str(attempts) + " attempts left." # lets the user know how many attempts they have left
print ""
if attempts < 1:
print "Well it looks like you are out of choices, Try again?"
break
print "Thanks for playing"
gameCont()
All of the printing that you're doing could be done in a separate function
def game_print(newlines_before, text, newlines_after)
print ("\n" * newlines_before + text + "\n" * newlines_after)
Two suggestions:
Delegate tasks that are accomplished by your function to smaller functions. So, for example, if you had a function that needed perform task A and performing that task could be divided into tasks B, C, and D, then create helper functions and call them inside of the function that does task A.
You have long strings, maybe store them somewhere else? Create a class just for constant strings of related functions and access that when you need a particular string. It'll make it less likely that you'll make a mistake when you need to use that string in multiple locations.
class Constants:
str1 = "..."
str2 = "..."
print(Constants.str1)
you can call a function from inside another function. inside an if statement you could call a small new function that just prints some stuff. this should make it easy to get the function size down.
something like this should work:
def correct(quiz, blanks):
print "As you can see your correct choice has replaced the variable, great job!!"
quiz = quiz.replace("_" + str(blanks) +"_", answers[blanks - 1]) # here is the line of code that replaces the blank with the correct guess
blanks += 1 # this adds 1 to the blank which will prompt the user to move to the NEXT blank when loop begins again
if blanks > len(answers):
print ("\n" * 10)
print "YOU DID IT!! Here is the final paragraph with all the correct answers"
print ("\n" * 2)
print quiz`
remember that you still want to break after calling that function in order to exit your loop.

How To Print Strings Between Integer Ranges - Python 3

I'm very new to Python and programming in general, so excuse me if the code is terrible and the problem rather easy to solve.
I have written code to allow a user to have employee data printed based on 3 different inputs, which they are allowed to choose from.
The options the user has available to them are to pick employees based on their payroll number; a minimum and maximum salary range; their job title.
I made two functions for the formatting. The first one turns the lines of the text file into lists, then the second function grabs those individual lists and formats them.
Then the code requests the user to input the file name. If the file cannot be found, they get to try again. If it is correct, the file is loaded and then runs through the functions to print out a neat table.
Then the user is asked what method they want to choose from to select specific employees. They are given 4 options, 3 are mentioned at the start and the fourth is to just end the program.
I managed to successfully get the first option to print out the employees without hassle, as is the same for the fourth option to end the program. I almost have the third one completed, I just need to find a way to print the name without a comma. My problem resides within the second option: how do I print the employees and their details if they fall between the minimum and maximum salary ranges entered by the user if the range isn't an integer since it has to include a '£' sign?
Here's the code. It's the biggest chunk in the program because I just have no clue how to make it work properly -
def detailsPrint(field) : #takes tuple and prints
print("{:30}" "{:6}" "{:15}" "{:7}".format(field[3] + ", " + field[4], field[0], field[2], "£" + field[1]))
if display == 2 :
maxSalary = "£1000000"
minpay = input("Enter the minimum pay : ")
maxpay = input("Enter the maximum pay : ")
if len(minpay) and len(maxpay) < maxSalary :
for s in employeeList :
if s[1] >= minpay :
detailsPrint(s)
The outcome should be something like (example) Simpson, Bart 12345 Consultant £55000 if the minpay were to be £50000 and maxpay £60000
edit: Managed to get it working. Here's the code
if display == 2 :
x = False
maxSalary = 1000000
minpay = int(input("Enter the minimum pay: "))
maxpay = int(input("Enter the maximum pay: "))
if int(minpay) > int(maxSalary) or int(maxpay) > int(maxSalary) :
x = False
print("No employees earn over £1000000. Try again.")
if int(minpay) or int(maxpay) < int(maxSalary) :
for s in employeeList :
if int(s[1]) >= minpay and int(s[1]) <= maxpay :
detailsPrint(s)
x = True
if x == False :
print("No employees could be found within that range. Try again")
print("\n")
Simplest solution: don't ask for the £ char ;-)
A solution that work with your requirement is to change the line
if len(minpay) or len(maxpay) > maxSalary :
with something like
if int(minpay[1:]) > int(maxSalary[1:]) or int(maxpay[1:]) > int(maxSalary[1:]) :
which check the numeric value of the strings (your condition seems wrong anyway to me)
You could replace all "£" signs to "" in a string.
YourString.replace("£", "")

I've created a recipe program for GCSE Computing, but I am missing one step [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is my first post here and I am quite unsure on how to implement a vital piece of code in my coursework. I have created a very crude and basic recipe program on Python 3.4. Below is the piece I am missing.
• The program should ask the user to input the number of people.
• The program should output:
• the recipe name
• the new number of people
• the revised quantities with units for this number of people.
I am a complete beginner to programming and our teacher hasn't been very helpful and only explained the basics of file handling which I have attempted to implement into this program.
I will attach the code I have so far, but I would really appreciate some tips or an explanation on how I could implement this into my code and finally finish this task off as it is becoming very irksome.
Thank you!
Code:
I apologise if the code is cluttered or doesn't make sense. I am a complete novice.
#!/usr/bin/env python
import time
def start():
while True:
User_input = input("\nWhat would you like to do? " "\n 1) - Enter N to enter a new recipe. \n 2 - Enter V to view an exisiting recipe, \n 3 - Enter E - to edit a recipe to your liking. \n 4 - Or enter quit to halt the program " "\n ")
if User_input == "N":
print("\nOkay, it looks like you want to create a new recipe. Give me a moment..." "\n")
time.sleep(1.5)
new_recipe()
elif User_input == "V":
print("\nOkay, Let's proceed to let you view an existing recipe stored on the computer")
time.sleep(1.5)
exist_recipe()
elif User_input == "E":
print("\nOkay, it looks like you want to edit a recipe's servings. Let's proceed ")
time.sleep(1.5)
modify_recipe()
elif User_input == "quit":
return
else:
print("\nThat is not a valid command, please try again with the commands allowed ")
def new_recipe():
New_Recipe = input("Please enter the name of the new recipe you wish to add! ")
Recipe_data = open(New_Recipe, 'w')
Ingredients = input("Enter the number of ingredients ")
Servings = input("Enter the servings required for this recipe ")
for n in range (1,int(Ingredients)+1):
Ingredient = input("Enter the name of the ingredient ")
Recipe_data.write("\nIngrendient # " +str(n)+": \n")
print("\n")
Recipe_data.write(Ingredient)
Recipe_data.write("\n")
Quantities = input("Enter the quantity needed for this ingredient ")
print("\n")
Recipe_data.write(Quantities)
Recipe_data.write("\n")
for n in range (1,int(Ingredients)+1):
Steps = input("\nEnter step " + str(n)+ ": ")
print("\n")
Recipe_data.write("\nStep " +str(n) + " is to: \n")
Recipe_data.write("\n")
Recipe_data.write(Steps)
Recipe_data.close()
def exist_recipe():
Choice_Exist= input("\nOkay, it looks like you want to view an existing recipe. Please enter the name of the recipe required. ")
Exist_Recipe = open(Choice_Exist, "r+")
print("\nThis recipe makes " + Choice_Exist)
print(Exist_Recipe.read())
time.sleep(1)
def modify_recipe():
Choice_Exist = input("\nOkaym it looks like you want to modify a recipe. Please enter the name of this recipe ")
Exist_Recipe = open(Choice_Exist, "r+")
time.sleep(2)
ServRequire = int(input("Please enter how many servings you would like "))
start()
EDIT: This is the new code, however I can still not figure out how to allow a user to multiply the original servings by entering how many servings are required, as the default servings are in a text file. Does anyone know how this can be done? I am new to file-handling and have been researching constantly but to no avail.
For the number of people, you can get that from user input similar to how you got any other input in your code, with num_people = input("How many people?").
Something a little more concerning you should look at. Your start() function calls its self. Unless you are using recursion, functions should not call themselves, it will build up on the stack. Use a while loop with something like
while ( 1 ):
userinput = input("what would you like to do?")
if( userinput == "n"):
#new recipe
....
if (user input == "quit"):
sys.exit(1) #this will halt the program
else:
print "not valid input"
You stored the whole data in a text file. This makes storage and retrieval easy, but makes changing values real hard. In these cases, you usually use ... well nevermind: you asked the same question again and got a useful answer.

Categories

Resources