how to better organize your code in python? [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I've been wonder how to clean up code to make my code easier and more readable for others reviewing my code. I'm fairly new to python, so I write everything into functions instead of using classes. Should I use more classes to better understand python more? I know that if the code works then it doesn't matter the way you did it but I just want to learn how to decrease my lines of code.
def paymentData():
calculateTotal = {}
remainingAmount = []
balance = int(raw_input('What is the balance of your bank account? \n'))
amount = int(raw_input('What is the amount you would like to subtract? \n'))
calculateTotal[balance]=amount
total = balance - amount
print('your total is: ' + str(total))
remainingAmount.append(total)
while True:
choice = raw_input('To continue press "Enter" or type "q" to exit (For options type "o"). \n')
if choice == '':
clearScreen()
paymentData()
break
elif choice.lower() == 'q':
clearScreen()
menuBudget()
break
elif choice.lower() == 'o':
return calculateTotal, remainingAmount
clearScreen()
options_menu()
break
else:
print('Invalid value.')
continue
This is a function from one of my programs that is a budget program that takes the value balance that the user puts in and subtracts it from the amount value.
This function calls three different functions, one of them being clearScreen() that clears the terminal:
def clearScreen(numlines=100):
if os.name == "posix":
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
os.system('CLS')
else:
print('\n' * numlines)
The options_menu() function that tells you the results of all the amount you put in (This is not completed nor do I plan to complete this project).
def options_menu():
print('Do you want to see all of you total amounts?\n(Enter 1 for Yes, 2 for no.)')
choice = int(raw_input())
if choice == 1:
time.sleep(3)
elif choice == 2:
menuBudget()
else:
print('Invalid Response.')
and the `menuBudget()` function that is the main menu for this script:
def menuBudget(): # this is a menu for budget fast.
menuRunning = True
while menuRunning:
print("""
1. payment calculator.
2. Comming Soon.
3. Comming Soon.
4. Exit/Quit.
""")
ans = input('Pick on the options above.\n')
if ans == 1:
clearScreen()
paymentData()
break
elif ans == 2:
print('Comming soon!')
continue
elif ans == 3:
print('Comming soon!')
continue
elif ans == 4:
break
else:
print('Unknown Option Seleted!')
continue

The use of classes means the use of OOP (Oriented Object Programmation). Sometimes your code will be very simple and doesn't need the use of classes. This paradigm depends of the type of project you want to build.
If you use imperative programmation, the best practice is to use functions as you're doing. If you want to improve your code, here are some tips :
Use meanful variable names
Use meanful function names
Sort your code into many files, feel free to have as much as you need. Try to call them once more with meanful names.
Simplify your code as much as needed, and use python libraries functions (this comes with experience). For example, use the max() function instead for re-write other functions.
Add comments to your code to make it re-usable even after month
Feel free to update this answer with other good-programmation pattern !

Related

python quiz with subject options [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
print("plese choose a topic of your liking")
History = ('History')
Music = ('Music')
Computer_science = ('Computer science')
print (History, Music, Computer_science)
History = print("when did the Reichstag fires begin?")
one = ("1) 1937")
two = ("2) 1933")
three = ("3) 1935")
print (one, two, three)
guess = int(input())
if guess == 2: #this makes it so any option appart from 2 is outputed as 'wrong'
print ("well done")
else:
print("wrong")
I have created the first part of my python quiz, It took me a while to figure out, I have also created a list that contains 3 different subjects, Do any of you know how to assign a button to each element within my subject list? If this does not make any sense, please let me know (I'm new to this site)
to get this sort of behaviour you can make an input before everything else which determines what subject you choose based on user input. so something REAL simple like:
subject = int(input("Please choose what subject you would like
(number):\n[1]History\n[2]Maths\n[3]Geography\n"))
if subject == 1:
print("You have chosen History")
elif subject == 2:
print("You have chosen Maths")
elif subject == 3:
print("You have chosen Geography")
else:
print("that is not an available option")
This is probably the simplest it can get with menus... If you type 1 and press enter you get history and so on. i dont know how your program works but do what fits in.
There are probably better ways too this is just what I remember doing back in the day. Very simple stuff

How can I return with a local variable in definition in Python? [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 5 years ago.
Improve this question
I am trying to create a simple AI program which plays stick game. The problem is that I would like to subtract chosen stick from the total stick number. This simple code shows some error such as nonexisting value. I could not assign returning value for my values. Is there another way to subtracts value with functions?
import random
msg = input('Determine stick numbers:')
print('Stick number is determined as:', msg)
# First player move
def robot(stick):
y = stick % 4
if y==0:
y=randint(1,3)
mov=int(y)
print('machine chose:', mov)
total = stick-mov
return total
def human(stick2):
mov2= int(input('your turn:'))
print('human chose:', mov2)
total = stick2-mov2
return total
players= {
'1': robot,
'2': human
}
number1= input('Determine first player machine(1) or human(2):')
number2= input('Determine second player (1) or (2):')
player1=players[number1]
player2=players[number2]
print(player1, player2)
print('the game begins')
while True:
player1(int(msg))
if msg == 0: break
print('remained sticks:', msg)
player2(int(msg))
print('remained sticks:', msg)
if msg == 0: break
Your players are references functions:
players= {
'1': robot,
'2': human
}
Later you call them player1 and player2:
player1=players[number1]
player2=players[number2]
But when you use these functions you don't do anything with the return value:
player1(int(msg))
...
player2(int(msg))
So those functions return something, but you ignore the value. You need to either print that return value or assign it to a variable so you can do something with the value later.
Since your return values are called total perhaps you want:
total = player1(int(msg))
print('new total:', total)
return does work, of course; it returns a value. However in your code you are not capturing that value and it is immediately thrown away.
It's really not clear what you want, but perhaps you want something like this:
msg = player1(int(msg))

Achievement system in and IDLE python game using pycharm [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 5 years ago.
Improve this question
I am trying to use an achievement system in my game. The game is like cookie clicker except you type and enter the letter "L" over and over and can upgrade the effect done by each type. I am trying to make it so when you get a certain amount of coins, like 1000, it will display that you have achieved the 1000 coins achievement, however it doesn't seem to work. Here is the code:
if coins == 1000:
print("")
print("You have a new achievement!")
print("[✔] - Earn 1,000 points")
print("You have 1/6 coin achievements")
print("")
if coins == 10000:
print("")
print("You have a new achievement!")
print("[✔] - Earn 10,000 points")
print("You have 2/6 coin achievements")
print("")
Your specific problem is that you're using the wrong comparator. If you use ==. you're checking if the value exactly equals. You're interested in when a player "achieves" the value, so switch your comparators out for >=. That way, when a player goes from 980 to 1001 points, 1001 >= 1000 evaluates to True.
Note this will print the text every time you check, even if they've already got the achievement, so perhaps something like the following would be useful:
has_1000_achievement = False
has_10000_achievement = False
if coins >= 1000 and not has_1000_achievement:
has_1000_achievement = True
print("")
...
The solution provided by P i would undoubtedly work, but I believe it's not something you're ready to fluently understand at your current level.
Edit: After the OP added a comment the question got a little more clear to me. Maybe you could try the following (which is of course just an example as the OP did not provide a minimal running peace of code):
# -*- coding: utf-8 -*-
numCoinAchievements = 0
nextCoinLevel = 1000
for coins in range(0, 100000, 33):
if coins >= nextCoinLevel:
numCoinAchievements += 1
if numCoinAchievements == 1:
nextCoinLevel = 10000
elif numCoinAchievements == 2:
nextCoinLevel = 15000
else:
break
print("")
print("You have a new achievement!")
print("[✔] - Earn %d points" % nextCoinLevel)
print("You have %d/6 coin achievements" % numCoinAchievements)
print("")
Of course you have to adept the code to your needs, but it should make the problem clear!

Hey beginner still learning python

def firstdecision():
decision1 = ""
while decision1 != "Y" and decision1 != "N":
decision1 = input(" Do you belive the old man's story ? ( Y / N ) ")
if decision1 == "Y" :
print ("You take a bite of from the apple")
elif decision1 == "N" :
print ("You unsheath your hidden dagger and hold it to the old man's throat")
elif decision1 != "Y" and "N" :
return decision1
firstdecision()
So trying to make a text based game as a project to help me understand functions, loops better and what better way to actually learn than to get involved. Anyways kind of stuck here after the user inputs Y or N how would I code it where I can make a new def function() where depending on their answer (Y / N ) a different outcome happens?
What you should do is define the functions you want to call for each part of the dialogue and have a main function to call each one on answer, like:
def main():
if (decision1()):
decision2()
else:
decision3()
Where decision1() will return true or false depending on the user's answer.
By the way that is not a very smart way to make such game as you will soon run into a lot of function and if/elses, good exercise for beginners tough.
You don't define a new function at that point. Instead, you define both functions above this point in the code. Based on the user's response, you call one function or the other.

importing 'games' and window closes [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
I am attempting to make a program that opens up other programs (games that i have made previously) and the window closes instantly.
#Program that runs game i have made
import subprocess
choice = input("What would you like to do? \nGuess my number game (1) \nCalorie counter (2) \nWord jumble game (3) \nInsert your decision here - ")
while choice == "1":
print("Let us begin")
def start_guess_my_number():
subprocess.call(['python', 'Guess my number game2.py'])
start_guess_my_number()
choice = input("What would you like to do now? 1 2 or 3 ? - ")
while choice == "2":
print("Let us begin")
def start_calorie_counter():
subprocess.call(['python', 'Calorie counter.py'])
start_calorie_counter()
choice = input("What would you like to do now? 1 2 or 3 ? - ")
while choice == "3":
print("Let us begin")
def start_guess_my_number():
subprocess.call(['python', 'Word jumble game.py'])
start_guess_my_number()
choice = input("What would you like to do now? 1 2 or 3 ? - ")
input("Press enter to exit")
note: I have made sure that the programs I am calling upon are working, and when opened in the black command window, they stay open, unlike when I open them via this program.
You had the following problems:
You need to compare the input to an int, not a string
You need to open the game in the right folder, by default the new process runs in the folder that contains the python executable.
You were using while loops instead of if statements, your code would have been caught in an infinite loop.
There was no way to get out of the main loop, you need a break statement to achieve that.
I also separated the code into functions.
#Program that runs a game I have made
import os
import subprocess
def play_game(name):
print("Let us begin")
subprocess.call(['python', os.path.dirname(os.path.realpath(__file__))+os.path.sep+name])
choice = input("What would you like to do? \nGuess my number game (1) \nCalorie counter (2) \nWord jumble game (3) \nInsert your decision here - ")
while True:
if choice == 1:
play_game('Guess my number game2.py')
elif choice == 2:
play_game('Calorie counter.py')
elif choice == 3:
play_game('Word jumble game.py')
else:
break
choice = input("What would you like to do now? 1 2 or 3 ? - ")
print("Goodbye")

Categories

Resources