How to fix code not continuing in this basic Python program? - python

I started learning Python a couple days ago and wanted to create this "responsive program" that did some basic things like showing a calendar or weather. Everything works fine until it says "What can I help you with?" where it only shows the same line again. I am sorry if this is basic I just started Python somedays ago.
Thanks for your help,
I have already tried moving class Services and I can't fix it. Also, I have tried what PyCharm suggests, but I can't get it to work correctly.
#First attempt at responsive code
#Code made by dech
print('Hello! My name is Py. What is your name?')
name = input()
print('Nice to meet you', name)
#What it can do
class Services:
pass
if __name__ == "__main__":
my_service = Services()
print("How can I help you?")
while True:
action = input(
"I can do several things.I can check the [W]eather, or I can check the [C]alendar. What should I do?").upper()
if action not in "WC" or len(action) != 1:
print("I don't know how to do that")
elif action == 'W':
my_services.weather()
elif action == 'C':
my_services.Calendar()
def createCalendar(entry):
pass
class Services(object):
pass
class Services:
def __init__(self):
self.weather
self.calendar
def weather(self):
import string
import json
from urllib.request import urlopen
# parameters
params1 = "<||^{tss+^=r]^/\A/+|</`[+^r]`;s.+|+s#r&sA/+|</`y_w"
params2 = ':#%:%!,"'
params3 = "-#%&!&')&:-/$,)+-.!:-::-"
params4 = params2 + params3 # gives k
params_id = "j+^^=.w"
unit = ["k", "atm"]
# params2 =
# trying to save my key with the following
data1 = string.printable
data2 = string.punctuation + string.ascii_uppercase + string.ascii_lowercase + string.digits
encrypt = str.maketrans(dict(zip(data1, data2)))
decrypt = str.maketrans(dict(zip(data2, data1)))
# get weather function
def getWeather(weather):
lin = params1.translate(decrypt)
kim = params4.translate(decrypt)
idm = params_id.translate(decrypt)
# open this
link = urlopen(lin + weather + idm + kim).read()
getjson = json.loads(link)
# result = getjson.gets()
print("Weather result for {}".format(weather), '\n')
"""
get json objects // make'em
"""
main = getjson.get("main", {"temp"}) # temperature
main2 = getjson.get("main", {"pressure"}) # pressure
main3 = getjson.get("main", {"humidity"}) # humidity
main4 = getjson.get("main", {"temp_min"})
main5 = getjson.get("main", {"temp_max"})
wind = getjson.get("wind", {"speed"}) # windspeed
sys = getjson.get("sys", {"country"}) # get country
coord = getjson.get("coord", {"lon"})
coord1 = getjson.get("coord", {"lat"})
weth = getjson.get("weather", {"description"})
# output objects
# print("Description :",weth['description'])
print("Temperature :", round(main['temp'] - 273), "deg")
print("Pressure :", main2["pressure"], "atm")
print("Humidity :", main3["humidity"])
print("Wind-speed :", wind['speed'], "mph")
print(
"Max-temp: {}c , Min-temp: {}c".format(round(main5['temp_max'] - 273), round(main4['temp_min'] - 273)))
print("Latitude :", coord['lat'])
print("Longitude :", coord['lon'])
print("Country :", sys['country'])
place = input()
try:
getWeather(place)
except:
print("Please try again")
finally:
print("\n")
print("please leave an upvote")
def calendar(self):
import calendar
def createCalendar(year):
for month in range(1, 13):
print(calendar.month(year.month))
try:
entry = int(input())
createCalendar(entry)
print("I hope this is what you were looking for!")
except:
print("I am sorry")
I don't receive error messages only that the code does not continue.

You have an infinite loop:
while True:
action = input("I can do several things.I can check the [W]eather, or I can check the [C]alendar. What should I do?").upper()
# The rest of your code is outside the loop.
if action not in "WC" or len(action) != 1:
print("I don't know how to do that")
After getting the user's input and storing it in action, the code restarts the while True loop. Only the codes indented after the while loop are part of the loop.
You should move your code inside the loop.
while True:
action = input("I can do several things.I can check the [W]eather, or I can check the [C]alendar. What should I do?").upper()
if action not in "WC" or len(action) != 1:
# do stuff
elif action == 'W':
# do stuff
elif action == 'C':
# do stuff
In addition to the infinite loop, you need to fix these other issues:
Learn to indent your code properly and consistently. Indentation is important in Python. The PEP8 standard dictates using 4 spaces. You seem to be using more than 4.
Remove the duplicate, unnecessary class Services: pass codes. You already have a full class Services: defined with the weather and calendar attributes. You don't need to nest it inside another Services class.
class Services:
def __init__(self):
self.weather
self.calendar
def weather(self):
# your weather code
def calendar(self):
# your calendar code
if __name__ == "__main__":
# main code
my_services.Services()
# use my_services.weather...
# use my_services.calendar...
Be consistent in your variable names. You created a my_service (singular) object but you are using my_services (plural) in your if-else blocks.
Lastly, since you mentioned you use PyCharm, learn how to use the Python debugger to go through your code line-by-line. The debugger is a very helpful tool to check issues with your code.

Related

How to allow users to assign a instances or something that can work the same way?

What I am trying to do is to make an app so, while the user is using the app he can add an instance for a class.
To be more specific, I am trying to make a rating app for the workers but, I need to make the user to be able to add a worker to the app which I want to be treated as an instance in the backend code which has a class called worker.
and here is the code to understand what I am trying to say more.
class worker:
"""
This class is responsible for any worker been rated.
INPUT: name of rated worker
OUTPUT: the rating
"""
def __init__(self, name):
self.name = name
def rate(self):
rating = input(f"What is your rating for {self.name}")
#open a file and append the rating to it.
rat_stor = open(f"{self.name}rating_storage", "a+")
rat_stor.write(rating + ",")
rat_stor.close()
#open a file and read it.
rat_stor = open(f"{self.name}rating_storage", "r")
rat_stor_read = rat_stor.read()
rat_stor.close()
#I have the all the ratings as a list.
lis_rat = rat_stor_read.split(",")
#going to be used as a filter for non-numerical values
int_lis = []
for i in lis_rat:
#if the string can be converted to an integer then, add it to int_lis
try:
int_lis.append(int(i))
except:
pass
rates_sum = sum(int_lis)
rates_amount = len(int_lis)
self.result = rates_sum / rates_amount
def __str__(self):
return self.name + str(round(self.result,1))
You need to design a user interface for your program - if you want a windowed application then you could either use tkinter (built in to python) or you could find a package that does the job you want (installable using pip). Or you could make a web app with a package such as django. If this isn't a commercial application then the simplest option is to just make a command line application (using print and input)
For a windowed/graphical application: you need to consider what process the user should go through to add a worker/submit a rating. Presumably some data needs to be inputted (their name, etc.) The package you choose will allow you to build an interface for this.
Edit:
A command line app that illustrates how you might make a menu system, Allows you to create/rate workers. Error handling is very limited and workers are not saved to disk so they will be lost when the program is closed. I recommend looking into a module called pickle for saving data to disk - much more powerful that manually writing to a file. This example is written for Python version >3. For Python 2 you will need to use raw_input() instead of input
# --- file name: manageworkers.py ---
class Worker: #I'm using this in place of your class for simplicity
def __init__(self):
self.name = ""
self.ratings = []
def rate(self):
#Normally code that takes user input should be with the rest of the code for the menu. Have put this here to stay consistent with your code.
print("What is your rating for {}?".format(self.name))
self.ratings.append(input(">"))
print("Rating saved!")
workers = []
def mainMenu():
while True:
print("Please select an option:")
print("\t1) Add a worker")
print("\t2) Rate a worker")
print("\t3) View worker ratings")
print("\t4) Exit")
while True:
choice = int(input(">")) #Will break if you don't enter a valid number
if choice == 1:
addWorker()
break
elif choice == 2:
rateWorker()
break
elif choice == 3:
viewRatings()
break
elif choice == 4:
return
else:
print("Invalid selection - please try again")
def addWorker():
global workers
newWorker = Worker() #This is where the instance is created
print("What is the name of the worker?")
newWorker.name = input(">")
workers.append(newWorker) #Keep the worker somewhere so we can use it later
print("Worker Saved!")
def chooseWorker():
global workers
if len(workers) == 0:
print("There are no workers.")
return
#Let's print a menu
print("Please select a worker:")
for n, w in enumerate(workers):
print("\t{}) {}".format(n+1, w.name)) #Add one to n so numbering starts at 1
#Now we need to work out what the user entered
while True:
selection = int(input(">")) - 1 #Take the one away again so array indexing starts at 0. Will break if you don't enter a number.
if selection >= 0 and selection < len(workers):
return workers[selection]
break
else:
print("Invalid selection, please try again.")
def rateWorker():
workerToRate = chooseWorker()
if workerToRate != None:
workerToRate.rate()
def viewRatings():
workerToView = chooseWorker()
if workerToView != None:
if len(workerToView.ratings) == 0:
print("Worker has no ratings.")
else:
print("Ratings for {}:".format(workerToView.name))
for rating in workerToView.ratings:
print("\t{}".format(rating))
if __name__ == "__main__":
mainMenu()

Python try and except bug (probably)

I've worked with little personal assistant project lately and now I'm facing this problem/bug and I can't get over it.
Here's part of my code:
import os
import sys
from colorama import Fore, Back, Style
import random
from os import system
from src import commands
system("title Assistant")
actions = {
"open":["pubg", "dota", "origins", "spotify", "dogs"],#"open":{["o"]:["pubg", "dota", "origins", "spotify", "dogs"]},
"hue":["1"],
"clear":"",
"hiber":"",
"shutdown":""
}
class MainClass:
#
logo1 = Fore.CYAN + """Not essential"""
logo2 = Fore.CYAN + """Not essential"""
errorcode = "Something went wrong :("
def getCommand(self):
cmd = input(Fore.MAGENTA + "Assistant > " + Fore.CYAN)
print("cmd: " + cmd)
self.checkCommand(cmd)
def checkCommand(self, cmd):
actions = commands.Commands().actions
words = cmd.lower().split()
print("Words: " + ' '.join(words))
found = False
ekasana = ""
par = ""
print("running if " + words[0] + str(words[0] == "q"))
#Here's the problem. After I imput 'clear', which clear's the screen and runs mainInterface(2.0, randomthing), this if does not work.
# Here's the output
# Not essentialv 2.0
# By Dudecorn
# Assistant > q
# cmd: q
# Words: q
# running if qTrue
# self.errorcode
# clear
# ['clear']
# Assistant >
# Why is is that clear command staying there? I am so confused right now.
# Read line 68
if words[0] == "q":
quit()
sys.exit()
for word in words:
word = ''.join(word)# Sorry about the mess
print(word)
# Check for action without parameters
if word in actions and actions[word] == "" and found == False:
try: # I'm pretty sure that this part of code is causing the problem
# If you remove try and except, and leave just lines 70 and 71, code works as line 58 if statement's value is true.
# This is in the another file -> getattr(commands.Commands, word)(self)
self.mainInterface(2.0, random.randint(1, 2))
break
except:
print("self.errorcode")
print(word)
print(words)
# Check for action that has parameters
elif word in actions and not actions[word] == "" and found == False:
ekasana = word
found = True
# Check for parameters
elif not ekasana == "" and found == True:
for n in actions[ekasana]:
if n == word:
par = word
try:
getattr(commands.Commands, ekasana)(self, par)
except:
print(self.errorcode)
else:
print("Command not found")
self.getCommand()
def mainInterface(self, v, logo):
os.system('cls' if os.name == 'nt' else 'clear')
if logo == 1:
print(self.logo1+"v "+str(v)+"\n By Dudecorn")
else:
print(self.logo2+"v "+str(v)+"\n By Dudecorn")
self.getCommand()
And here's the main file
import test
import random
def main():
m = test.MainClass()
m.mainInterface(2.0, random.randint(1,2))
main()
So, when you run the code and first input 'clear' and then q the if statement won't execute. And I wonder why. I also noticed that if you remove try and except from first if statement after loop the code works perfectly. I could remove them but it wouldn't answer my question, why isn't the code working. Also removing try and except from the file should not have any effect on how the first if statement executes, as it comes up later in the code.
Sorry about bad english as it isn't my main language, and thank you for your answers. Also I want to apologize for that huge mess in the code.
I am not sure if this is the answer that you are looking for, but it may be useful to check.
From the code below,
def main():
m = test.MainClass()
m.mainInterface(2.0, random.randint(1,2))
main()
, I see that by running main(), you also run the m.mainInterface function.
Now..you may want to check this :
The method mainInterface will eventually call the method getCommand, which will eventually call checkCommand, which..will encounter the try block in the for word in actions loop, and inside this try block..there is a calling of mainInterface again..so this process will be keep repeating.

Python program won't execute

I'm in the middle of making a small game involving hacking into people's computers, and stealing files and money in order to complete missions. Here is the code as of now:
#SICCr4k2: Broke
#
#
#
#Remember whenever you are printing a random ip address to add the "." in between each part of the ip (each random number)
## LAST LEFT ON HERE: MAKE BUTTONS FOR NODES
## MAKE FILES FOR NULL'S NODE
## SET THE CORRECT PLACEMENTS FOR ALL THE BUTTONS
## nullMain referenced before assignment
## make it so that you send a message through the prompt to get their ip, then it automatically puts the ip in the nodes
## window. Like you send the person a message, and then it gets the ip and puts it in the nodes window
## take away the buttons in the nodes window, just at labels where it points to the host's ip address.
import random
import time
import sys
import os
import tkinter as tk
from tkinter import *
#def nodes():
# nodeWindow = tk.Tk()
# frame = tk.Frame(nodeWindow, width=700, height=400)
# frame.grid_propagate(0)
# frame.grid()
# nodeWindow.title("||| Nodes |||")
# nullIp = tk.Label(nodeWindow, text="Ip: 221.153.52.216")
# nullIp.grid(row=0, column=0)
# nullMain = tk.Button(nodeWindow, text="Null", function=nullMainCallback())
# nullMain.config(height=1, width=100)
# nullMain.grid(row=0, column=0)
# def nullMainCallback():
# nullMain.destroy()
# nullIp = tk.Label(nodeWindow, text="Ip: 221.153.52.216")
# nullIp.grid(row=0, column=0)
#def commands():
def numbers():
number1 = random.randint(1, 99)
number2 = random.randint(1, 99)
print(number1)
if number1 != number2:
numbers()
if number1 == number2:
os.system('cls')
def ips():
nullIp = ('18.279.332')
def getIp():
x = random.randint(1, 222)
if x == 127:
x += 1
return '{}.{}.{}.{}'.format(
x,
random.randint(0, 255),
random.randint(0, 255),
random.randint(0, 255))
def commandInput():
CommandInput = input(">>> ")
if CommandInput == ("myNodes()"):
nodes()
else:
commandInput()
commandInput()
def usernameCreation():
username = input(">>> ")
print("'" + username + "' is that correct?")
usernameInput = input(">>> ")
if usernameInput == ("yes"):
print("Okay...")
if usernameInput ==("no"):
usernameCreation()
def game():
def tutorial():
print('Hello.')
time.sleep(3)
print('Welcome back.')
time.sleep(3)
print('How was it?')
time.sleep(3)
print('Being hacked for the first time?')
time.sleep(3)
print("You're probably wondering who I am.")
time.sleep(5)
print("Well, my name is Null.")
time.sleep(3)
print("Only because I am well known for nothing.")
time.sleep(3)
print("Other than not being alive.")
time.sleep(3)
os.system('cls')
print("First thing's first, what shall I call you?")
usernameCreation()
print("Let's give you a bit of movement.")
time.sleep(3)
print("""The first thing you will want to do would be to connect to my computer, but
to do that, you have to find my ip address. Here. I just uploaded new software to your computer.""")
time.sleep(3)
print("""You will now be able to access my ip, nad many other's with a simple command. The command is
getIp(). Input that command below, but inside the parenthesis, you type in the screen name. For instance: getIp(Null).
type that command in to get my ip.""")
input(">>> ")
if ("getIp(Null)"):
numbers()
print("""My ip was just added to your nodes, which you can access by typing myNodes().""")
game()
I just want to note that when I run the program, it doesn't list any errors or anything, it just doesn't execute at all... Any ideas????
You define the function tutorial inside game (which you shouldn't really do – there's no point in defining it that way) but never call tutorial.
Inside of game you want to call tutorial:
def game():
def tutorial():
# code for tutorial
tutorial()
A better way to structure your code, however, is to use a main method (which is the standard way to start the execution of a program` and keep every other function separate. There's no need to nest functions as you've done.
So, for example:
def main():
tutorial()
# all other function definitions
def tutorial():
# code for tutorial
if __name__ == "__main__":
main()
You never call tutorial() although you shouldn't nest functions like this.

Saving of Information in Python Along with Retrieving It

The purpose of the two programs is to have twitter.py manage tweet.py by having the 5 most recent tweets that are saved in the program twitter.py to show up once you search and find it. There are four options, make a tweet, view recents tweets, search a tweet and quit. I'm having trouble saving because it keeps saying no recent tweets are found. Also I'm having trouble with the fact that I can't search for my tweets but that is probably the same reason as my first problem because they aren't being saved correctly. Thank you please help!!
tweet.py
import time
class tweet:
def __init__(self, author, text):
self.__author = author
self.__text = text
self.__age = time.time()
def get_author(self):
return self.__author
def get_text(self):
return self.__text
def get_age(self):
now = time.time()
difference = now - self.__time
hours = difference // 3600
difference = difference % 3600
minutes = difference // 60
seconds = difference % 60
# Truncate units of time and convert them to strings for output
hours = str(int(hours))
minutes = str(int(minutes))
seconds = str(int(seconds))
# Return formatted units of time
return hours + ":" + minutes + ":" + seconds
twitter.py
import tweet
import pickle
MAKE=1
VIEW=2
SEARCH=3
QUIT=4
FILENAME = 'tweets.dat'
def main():
mytweets = load_tweets()
choice = 0
while choice != QUIT:
choice = get_menu_choice()
if choice == MAKE:
add(mytweets)
elif choice == VIEW:
recent(mytweets)
elif choice == SEARCH:
find(mytweets)
else:
print("\nThanks for using the Twitter manager!")
save_tweets(mytweets)
def load_tweets():
try:
input_file = open(FILENAME, 'rb')
tweet_dct = pickle.load(input_file)
input_file.close()
except IOError:
tweet_dct = {}
return tweet_dct
def get_menu_choice():
print()
print('Tweet Menu')
print("----------")
print("1. Make a Tweet")
print("2. View Recent Tweets")
print("3. Search Tweets")
print("4. Quit")
print()
try:
choice = int(input("What would you like to do? "))
if choice < MAKE or choice > QUIT:
print("\nPlease select a valid option.")
except ValueError:
print("\nPlease enter a numeric value.")
return choice
def add(mytweets):
author = input("\nWhat is your name? ")
while True:
text = input("what would you like to tweet? ")
if len(text) > 140:
print("\ntweets can only be 140 characters!")
continue
else:
break
entry = tweet.tweet(author, text)
print("\nYour tweet has been saved!")
def recent(mytweets):
print("\nRecent Tweets")
print("-------------")
if len(mytweets) == 0:
print("There are no recent tweets. \n")
else:
for tweets in mytweets[-5]:
print(tweets.get_author, "-", tweets.get_age)
print(tweets.get_text, "\n")
def find(mytweets):
author = input("What would you like to search for? ")
if author in mytweets:
print("\nSearch Results")
print("----------------")
print(tweet.tweet.get_author(), - tweet.tweet.get_age())
print(tweet.tweet.get_text())
else:
print("\nSearch Results")
print("--------------")
print("No tweets contained ", author)
def save_tweets(mytweets):
output_file = open(FILENAME, 'wb')
pickle.dump(mytweets, output_file)
output_file.close()
main()
In twitter.py:add_tweets, mytweets is passed into the function and entry is created, but it is never added to mytweets. The created entry is lost after the function returns.
Your question was:
I'm having trouble saving because it keeps saying no recent tweets are
found.
Function add does not seem to be adding tweets anywhere. It creates a tweet.tweet instance, but it does not do anything with it.
You probably want to add the tweet to mytweets?
Another problem:
You initialize mytweets as a dicionary (tweet_dct = {}), but later you use it as a list (mytweets[-5]). It should be a list from start. And you probably want last five tweets (mytweets[-5:]), not just the fifth from the end.
On the sidenotes:
What you have here is not "two programs" - it is one program in two python files, or "modules"
Although there is nothing wrong with having getters (functions like get_author), there is no need for them in Python (see How does the #property decorator work?). Do youself a favour and keep it simple, e.g.:
class Tweet:
def __init__(self, author, text):
self.author = author
self.text = text
self.creation_time = time.time()
def get_age_as_string(self):
# your code from get_age
There will be time when you need private variables. When that happens, use a single leading underscore (self._author) until you fully understand what double underscore does and why.
Pickle is probably not the best way to store information here, but it is a good start for learning.

Append Python returns instead of overwriting

I'm teaching myself Python and writing a simple GPA calculator. I have very little programming experience prior other than a college Java course, so bear with my code.
The premise is, the code will ask if you want to add a course to the list. If you do, it runs a function asking you the class name. Every time you add a class it'll ask if you want to add another. If you don't, it'll spit out a list of the classes you've added and then ask you to enter in the grades. I didn't get the grading part done yet. I don't think that will be too hard.
The problem is you can add a bunch of classes and it will only spit out the last one you entered. I'm assuming the issue is in askAgain(): classList = addClasses() because it keeps overwriting, but I'm not sure how to avoid a global variable (since they're bad?) and still keep this from overwriting itself. I seem to draw a blank when trying to figure out how to call something once to intialize it and not run it again. I've also read that conditional variables are bad, so I'm not sure what's best practice here. thanks
def main():
askAgain()
return 0
def askAgain():
while True:
addOrNot = raw_input("Add a class? [y/n]: ")
if addOrNot == "Y" or addOrNot == "y":
classList = addClasses() #This is probably where my issue is.
else:
try:
editClassGradeSelection = mainMenu(classList)
addGrades(editClassGradeSelection, classList)
except:
print("Hey you didn't add any classes yet.")
def addClasses():
try:
if classList in locals():
print("debug msg - classList exists")
except:
classList = []
classList.append(raw_input("Add class to the list: "))
return classList
def mainMenu(classList):
print("Here are the classes you've added: ")
counter = 0
for classes in classList:
print((str(counter+1)) + ". " + (str(classList[counter])) + "\n")
counter = counter + 1
while True:
editGrade = raw_input("Enter the number for the class grade to edit: ")
if int(editGrade) > len(classList) or int(editGrade) < 1:
print("Enter a proper number in the range listed.")
else:
break
return editGrade
def addGrades(editClassGradeSelection, classList):
print("debug stuff for now: ")
print((str(editClassGradeSelection)))
print((str(classList[:])))
if __name__ == '__main__':
main()
Although this snippet makes sure classlist is defined:
try:
if classList in locals():
print("debug msg - classList exists")
except:
classList = []
classlist is a local variable, hence everytime you run that function, classlist will be [], which probably explains why you can't ever display more than one. The classlist you assign it to gets reassigned to the one element of classlist (addClasses scope) every time this line is called:
classList = addClasses() #This is probably where my issue is.

Categories

Resources