Having a compiling error with Python using PyCharm 4.0.5 - python

The reason for me asking the question here is that I did not find a solution elsewhere. I'm having the following error with my PyCharm 4.0.5 program while trying to run a Python script. It was working fine the one day and when I tried using it this afternoon I got the following error after tying to run a program which I am 100% has no errors in it.
In the message box I got the following error:
Failed to import the site module
Traceback (most recent call last):
File "C:\Python34\lib\site.py", line 562, in <module>
main()
File "C:\Python34\lib\site.py", line 544, in main
known_paths = removeduppaths()
File "C:\Python34\lib\site.py", line 125, in removeduppaths
dir, dircase = makepath(dir)
File "C:\Python34\lib\site.py", line 90, in makepath
dir = os.path.join(*paths)
AttributeError: 'module' object has no attribute 'path'
Process finished with exit code 1
I have never seen an error of this kind and don't know where to start tackling this problem.
Any feedback will be greatly appreciated!
The code looks like the following, and I seem to have forgotten to mention that it gives me the exact same error for every single .py script on my computer.
import turtle
wn = turtle.Screen()
alex = turtle.Turtle()
def hexagon(var):
for i in range(6):
alex.right(60)
alex.forward(var)
def square(var):
for i in range(4):
alex.forward(var)
alex.left(90)
def triangle(var):
for i in range(3):
alex.forward(var)
alex.left(120)
def reset():
alex.clear()
alex.reset()
x = True
while x:
alex.hideturtle()
choice = input("""
Enter the shape of choice:
a. Triangle
b. Square
c. Hexagon
""")
if choice.lower() == "a":
length = input("Enter the desired length of the sides: ")
triangle(int(length))
restart = input("Do you wish to try again? Y/N ")
if restart.lower() == "n":
x = False
else:
reset()
if choice.lower() == "b":
length = input("Enter the desired length of the sides: ")
square(int(length))
restart = input("Do you wish to try again? Y/N ")
if restart.lower() == "n":
x = False
else:
reset()
if choice.lower() == "c":
length = input("Enter the desired length of the sides: ")
hexagon(int(length))
restart = input("Do you wish to try again? Y/N ")
if restart.lower() == "n":
x = False
else:
reset()
print("Thank you for using your local turtle services!")

You must have a python file named os.py which is being imported instead of the "real" os module.

Related

Adding and saving to list in external json file

I'm very new to Python and I'm struggling when it comes to saving the data that the user has entered to a json file when quitting the application. Also every time I run my code all the data inside the json file is wiped. When I enter the input to save and exit I get this error code:
Traceback (most recent call last):
File "C:\Users\User\Downloads\sit_resources\sit_resources\sit_admin_application.py", line 86, in <module>
main_menu()
File "C:\Users\User\Downloads\sit_resources\sit_resources\sit_admin_application.py", line 23, in main_menu
save()
File "C:\Users\User\Downloads\sit_resources\sit_resources\sit_admin_application.py", line 82, in save
patients_file.write(finallist)
io.UnsupportedOperation: not writable
Here is my code below:
import json
patients_file = open("patients.json", "r")
loaded_patients = json.load(patients_file)
def main_menu():
'''Function docstring documentation here'''
print("\nSIT Data Entry Menu")
print("==========================")
print("1: Print Patients' List\n2: Add Patient\n3: Delete Patient\n4: Exit")
print("==========================")
input1 = input("Enter your menu selection:")
if input1 == "1":
patients_list()
elif input1 == "2":
add_patient()
elif input1 == "3":
remove_patient()
elif input1 == "4":
save()
else:
print ("Please enter a valid input")
main_menu()
def patients_list():
print("\nSIT current patients:\n")
loaded_patients.sort(key=str.casefold)
for number, item in enumerate(loaded_patients, start=1):
print(number, item)
print("\nTotal number of registered patients is", len(loaded_patients))
main_menu()
def add_patient():
newpatient = input("\nEnter new Patient -> Lastname Firstname:")
print ("Do the details you have entered look correct? y/n")
confirm = input()
if confirm == "y":
loaded_patients.append(newpatient)
print ("Patient successfully added to list")
main_menu()
elif confirm == "n":
print ("Patient import cancelled")
add_patient()
else:
print ("Please enter a valid input")
add_patient()
def remove_patient():
print ("Which of the following patients would you like to remove?")
loaded_patients.sort(key=str.casefold)
for number, item in enumerate(loaded_patients, start=1):
print(number, item)
try:
removepatient = int(input("\nEnter the number of the patient you would like to remove"))
print ("Does the patient number you have entered look correct? y/n")
delconfirm = input()
if delconfirm == "y":
try:
removepatient = (removepatient - 1)
loaded_patients.pop(removepatient)
print ("Patient was successfully removed from the list")
main_menu()
except IndexError:
print("Please enter a valid input")
remove_patient()
elif delconfirm == "n":
print ("Deletion cancelled")
remove_patient()
else:
print ("Please enter a valid input")
remove_patient()
except ValueError:
print ("Please enter a valid input")
remove_patient()
def save():
open("patients.json", "w")
finallist = json.dumps(loaded_patients)
patients_file.write(finallist)
print("Patient List successfully saved")
quit()
main_menu()
I store the json file in the same directory and all it contains is a list:
["Soreback Leigh", "Neckache Annette", "Sorefoot Jo", "Kaputknee Matt", "Brokentoe Susan", "Tornligament Alex"]
If anyone could help me out and let me know what I'm doing wrong or any simpler method I could use, it would be greatly appreciated.
Thanks
Your code has several issues, including the one you're asking about.
The main thing is the overall structure: your code keeps calling functions from functions, never really returning - that can work for a very long time, but in the end it will fail, and it's not the correct way to go about this.
Take for example your main_menu() - once an option is selected, you call the function matching it, and when the work there is done, you call main_menu() again. However, a better way to do the same:
def main_menu():
choice = ''
while choice != '4':
print('some options, 4 being "save and quit"')
if choice == 1:
patients_list()
...
# no if choice == 4: save() here, we'll save at the end
save()
This way, the menu will keep getting printed when you return to it, but every function that is executed, is allowed to return and then the loop restarts, unless option 4 was entered. And since you can allow the functions to return, no need to call main_menu() at the end of them.
Your save() function has some issues: it doesn't need quit() any more, but you also didn't do anything with the file you opened. A nice way to do this in Python is to use a 'context manager', which boils down to using with, like this:
def save():
with open("patients.json", "w") as patients_file:
finallist = json.dumps(loaded_patients)
patients_file.write(finallist)
That's assuming your loaded_patients always contains all the current patients of course. Given that's what it is for, you should consider just calling it patients.
Your file only contains a list, because a list is what you are creating in those functions and a list is a valid content for a json file. If you expected a dictionary, you should construct one in the rest of the code, but from your example it's unclear what exactly you would expect that dictionary to look like.
The conventional way to load and save json:
with open('patients.json', 'r') as f:
loaded_patients = json.load(f)
with open('patients.json', 'w') as f:
json.dump(loaded_patients, f)
You are trying to write to patients_file, which you opened in read-only mode.

Why am I getting "NameError" from input()?

I am new and trying to create a simple "guess the number game":
import random
class Randgame :
def __init__(self):
pass
def restart(self):
response = input("Type Yes To Play Again!").lower()
if response == "yes":
self.play()
else:
print("Thanks for playing!")
pass
def play(self):
guess = int(input("What's your guess?"))
num = random.randint(0, 10)
if guess == num:
print("Correct!")
else:
print("Nope!")
self.restart()
fun = Randgame()
fun.play()
All is well until I get to the restart() method. If I type "yes" into the console I get this response:
NameError: name 'yes' is not defined
I cannot figure this out to save my life and I don't know what to look up. Please help!
In Python 2, getting input as plain text is done via raw_input instead of input. Python 3 changed the name of the function to input. The Python 2 version of input does eval(raw_input(prompt)), so it is trying to actually access a variable called yes, when you just want to get the string "yes".
Python 2 Docs

My python script works in IDLE but not in console

The following code executes properly in IDLE but return an error in console.
import sys, math, string, time, os
from time import *
restart0 = True
while restart0:
def addDecimal():
print(".", end="\r")
breakout0 = False
invalidcommand0 = True
while invalidcommand0:
file = open("HighScores.txt","r+")
sleep(0.5)
print("\nWelcome to VACSecureServers™\n")
start = input("Would you like to start the program? ")
if start.lower() == "yes":
print("\n1. Display high scores\n2. Add a new high score\n3. Clear all high scores\n4. Quit")
option = input()
if option == "1":
print (file.read())
if os.stat("highscores.txt").st_size==0:
print("There are no highscores currently in the system, please return and input some.")
elif option == "2":
numberAppend = int(input("How many scores would you likes to add to the program? "))
for loop in range(numberAppend):
name = input("Enter the name of the user:" )
score = input("Enter a score: ")
file.write(name+","+score+","+strftime("%d/%m/%y %H:%M:%S\n"))
elif option == "3":
open("HighScores.txt", 'w').close()
print("Highscores resetting")
sleep(0.4)
addDecimal()
sleep(0.6)
addDecimal()
sleep(0.9)
addDecimal()
sleep(1.2)
print("Successfully reset!")
sleep(2)
elif option == "4":
sys.exit()
file.close()
This is the error I get:
Traceback (most recent call last):
File "E:\script.py", line 12, in <module>
print("\nWelcome to VACSecureServers™\n")
File: "C:\Python3\lib\encodings\cp437.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2122' in position 29: character maps to <undefined>
What could be the problem?
It is because of this line
print("\nWelcome to VACSecureServers™\n")
You have a ™ symbol in it. Your console probably can't display it, but IDLE supports unicode characters. Remove it and your code should work just fine.

Python - Why does my .read() not work on my .txt file? Nothing is outputted to the cmd line

Running
I am running Python version 3.5, from the cmd prompt on Windows 7
What is in the .txt file and what the cmd outputs
What the cmd prompt outputs
What the .txt contains
My current code
"""Opens a file and let\'s you read it and write to it"""
open_pls = open("text.txt", "a+")
#Main function
def read_write():
program_running = True
while program_running == True:
choice = input("Write R for read, write W for write or write X for exit:")
choice = choice.upper()
if choice == "W":
what_write = input("What do you want to write to the end of the file?:")
open_pls.write(what_write)
print("Succesfully written!")
print("Running program again...")
continue
elif choice == "R":
print("This file contains:")
read_pls = open_pls.read()
print(read_pls)
print("Running program again...")
continue
elif choice == "X":
program_running = False
open_pls.close()
else:
print("That was not a valid command!")
print("Running program again...")
continue
run = input("Run the program? (Y/N):")
run = run.upper()
if run == "Y":
read_write()
elif run == "N":
input("Exit program? Press enter:")
else:
input("Exit program? Press enter:")
I think the problem lies somewhere in here
elif choice == "R":
print("This file contains:")
read_pls = open_pls.read()
print(read_pls)
print("Running program again...")
continue
When you open the file with the 'a' append mode, the OS gives you a file with the file position at the end of the file.
You could try to seek back to the start first, but it depends on your OS if that'll actually be permitted:
open_pls.seek(0)
read_pls = open_pls.read()
You may want to open the file in 'r+' mode instead, and seek to the end when writing.
When you open a file with 'a' mode, the file is seeks to the end. To get the contents of the file, you have to seek back to the beginning: open_pls.seek(0).

Using .readlines() and struggling to access the list

I am struggling to access the list created by using .readlines() when opening the text file. The file opens correctly, but I am not sure how I can access the list in the function 'display_clues()'.
def clues_open():
try:
cluesfile = open("clues.txt","r")
clue_list = cluesfile.readlines()
except:
print("Oops! Something went wrong (Error Code 3)")
exit()
def display_clues():
clues_yes_or_no = input("Would you like to see the clues? Enter Y/N: ")
clues_yes_or_no = clues_yes_or_no.lower()
if clues_yes_or_no == "y":
clues_open()
print(clue_list)
Error:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
display_clues()
File "N:\Personal Projecs\game\game.py", line 35, in display_clues
print(clue_list)
NameError: name 'clue_list' is not defined
Thanks!
def clues_open():
try:
cluesfile = open("clues.txt","r")
clue_list = cluesfile.readlines()
#print clue_list #either print the list here
return clue_list # or return the list
except:
print("Oops! Something went wrong (Error Code 3)")
exit()
def display_clues():
clues_yes_or_no = raw_input("Would you like to see the clues? Enter Y/N: ")
clues_yes_or_no = clues_yes_or_no.lower()
if clues_yes_or_no == "y":
clue_list = clues_open() # catch list here
print clue_list
display_clues()
You have to return the list from clues_open() to display_clues():
def clues_open():
with open("clues.txt","r") as cluesfile:
return cluesfile.readlines()
def display_clues():
clues_yes_or_no = input("Would you like to see the clues? Enter Y/N: ")
if clues_yes_or_no.lower() == "y":
clues_list = clues_open()
print(clue_list)
As a side note: I removed your worse than useless except block. Never use a bare except clause, never assume what actually went wrong, and only catch exception you can really handle.

Categories

Resources