Nothing executes in code [duplicate] - python

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Python Application does nothing
#Dash Shell
import os
import datetime
class LocalComputer:
pass
def InitInformation():
Home = LocalComputer()
#Acquires user information
if (os.name == "nt"):
Home.ComputerName = os.getenv("COMPUTERNAME")
Home.Username = os.getenv("USERNAME")
Home.Homedir = os.getenv("HOMEPATH")
else:
Home.ComputerName = os.getenv("HOSTNAME")
Home.Username = os.getenv("USER")
Home.Homedir = os.getenv("HOME")
return Home
def MainShellLoop():
print ("--- Dash Shell ---")
Home = InitInformation()
userinput = None
currentdir = Home.Homedir
while (userinput != "exit"):
rightnow = datetime.datetime.now()
try:
userinput = input(str(Home.ComputerName) + "\\" + str(Home.Username) + ":" + str(rightnow.month) + "/" + str(rightnow.day) + "/" + str(rightnow.year) + "#" + str(currentdir))
except:
print("Invalid Command specified, please try again")
MainShellLoop()
The input() is supposed to execute and it stopped working after changing something I dont remember
It's coded under Python 3.1.2 with Windows 7, I know the Unix Hostname global variable is wrong
I know userinput does nothing, I want to get this part working before I continue on
Thanks
It outputs nothing

You define a class and two functions, but you don't seem to call any of them anywhere. Are you missing a call to MainShellLoop() in the end?

I think you need a call to MainShellLoop.

Related

Python Loop Unable to interrupt

I'm making a curency converter, time converter and weather app for an year 12 computer sciences project. Im unable to interrupt the loop that is being used for the main menu/location selector.
Can anyone help?
The code is below.
##This program is intended to help travellers with date and currency conversions ##
##Changelog----->##
##V1 - Include code for Forex Converter, code modified from - https://www.w3schools.in/python/examples/real-time-currency-converter##
##V2 - Implement GUI##
##V2.1 - Implement Multiple Screens GUI##
##V3 - Remove all GUI aspects##
##V3.1 - Create initial loop##
##Import Modules##
from forex_python.converter import CurrencyRates
import time
import datetime
import python_weather
import asyncio
##Opening info##
##V3.1##
global enter
enter = 'GO'
while enter == 'GO':
print("========================================================================================================================================================================================")
print("")
print("Welcome to the Traveller Assisstant. This program is able to help you with currency conversions, date and time conversions and viewing weather details of your destination.")
print("")
print("========================================================================================================================================================================================")
time.sleep(2.5)
ori = str(input("Please enter your current country: "))
dest = str(input("Please enter your destination country: "))
time.sleep(5)
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
if check == 'YES':
enter = 'STOP'
elif check == 'NO':
print("Returning to Location Selector")
enter = 'GO'
##V1##
##Change Currency##
#cr = CurrencyRates()
#output = cr.convert(entry1, entry2, entry3)
#final = round(output, 2)
#print("THE FINAL AMOUNT IS:", final, c2)
A simple typo, that's all that was wrong.
In this line of code:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
You are attempting to use the method
.upper()
But your fatal flaw is that you forgot the parentheses.
I changed this:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
To this:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper()
And the code worked perfectly for me
EXPLANATION
In the original code, check could never be equal to 'YES' or 'NO', because of the typo;
.upper was never recognized as a strings' function and returned with this value:
<built-in method upper of str object at 0x105fec130>
.upper() on the other IS in fact a valid function for a string and returned with this value when it was supplied with the input of 'yes':
YES
If you need to exit from the loop when a condition is met you can achieve that easily by using break. So when your condition is met:
either add bellow enter = "STOP" the statement break or just replace enter = "STOP" for break
if check == 'YES':
enter = "STOP"
break
or
if check == 'YES':
break
both should work, I guess you could go with the first answer if you need to keep the state of the variable enter otherwise you could just use the second.
The problem with your original code is that you are missing a parenthesis on the declaration of the upper method in this line:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
instead it should be:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper()
if you don't add the parenthesis to upper() it means you are declaring the object method itself not triggering instead what the method actually does. (In this case making the string uppercase)

Is there a way I could insert a link in an 'if' statement?

So I'm new to coding and I need some help with this assignment, this is
my code
I can't get the 'import webbrowser' to work (SyntaxError) under an if statement since it's not made for that. I was wondering if there's any way I could either modify it or change it while still being able to open a link. This assignment is due friday, so I'd really appreciate any help
You cannot use "is" with a literal; if x is 'yes': throws the the SyntaxError.
You have to use if x == 'yes': instead. Your code should be like
def album_link():
print('Check them out')
x = input('yes or no: ')
if x == 'yes':
import webbrowser
webbrowser.open('http://stackovefflow.com', new=2)
else:
x == 'no' # does nothing
print('OK')
This is a Python 3 sample which hasn't raw_input anymore.
With a few exceptions, Python expects import statements at the toplevel of your program, not within an if statement:
import webbrowser
def album_link(self):
# ...
Thank you so much to everyone who helped!! The '==' answer and adding the import webbrowser at the beginning made the code work! This is how it turned out
`
import webbrowser
class Albums:
def __init__(self, name, artist, genre, release, spotify):
self.name = name
self.artist = artist
self.genre = genre
self.release = release
self.spotify = spotify
def album_desc(self):
# other way return'The album ' + "{}".format(self.name) + ' was made by ' + "{}".format(self.artist)
return('The album ' + self.name + ' made by ' + self.artist + ', is a(n) ' + self.genre + ' album released in ' + "{}".format(self.release) + ' with over ' + "{}".format(self.spotify) + ' spotify listeners!')
def album_link(self):
print('You can check them out here!')
x = str(raw_input("yes or no: "))
if x == 'no':
print('Ok :)! Thank you for checking it out')
else:
x == 'yes'
webbrowser.open('http://themuffinmanbops.carrd.com', new=2)
`

need help in simple multiple login in python

i am trying to make a simple login system for python. i tried several things using break,return. but i cant get pass the login system using the second line in the text file onwards. i can only login through the first line of the text file, i took the code fro an other question but didnt know how to get it to work so i tried to change it so i could understand how it can work. I am extremely new to python. please let me know where i got wrong and how i can change it to get it to work!
format for user.txt is
first name|last name|occupation|id|username|password
John|goh|worker|1|admin|1234
import datetime
def check():
x = 0
users = open("users.txt").read().split("\n")
for i in range(len(users)): users[i] = users[i].split("|")
while (x < 3):
username = str(input("Username: \n"))
password = str(input("Password: \n"))
f = open('project_AI.txt', 'a')
f.write(str(datetime.now()))
f.write('\n' + username + '\n')
f.write(password + '\n')
f.close()
for user in users:
uname = user[4]
pword = user[5]
if uname == username and pword == password:
print("Hello " + user[1] + ".")
print("You are logged in as: " + user[2] + '.')
x += 3
else:
print('error')
check()
x += 1
return
check()
many thanks!!
I think the "return" in the penultimate line is at the wrong indentation, and isn't really needed at all.
As soon as python touches a return, it instantly destroys the function. In your code, after every user it checks, it hits the return. Meaning it will never even reach the second user.
You also want to not use check() within the function, as it will create a clone of itself within itself. The while x < 3 will go through the logic multiple times for you.
import datetime
def check():
x = 0
users = open("users.txt").read().split("\n")
for i in range(len(users)): users[i] = users[i].split("|")
while (x < 3):
username = str(input("Username: \n"))
password = str(input("Password: \n"))
f = open('project_AI.txt', 'a')
f.write(str(datetime.now()))
f.write('\n' + username + '\n')
f.write(password + '\n')
f.close()
for user in users:
uname = user[4]
pword = user[5]
if uname == username and pword == password:
print("Hello " + user[1] + ".")
print("You are logged in as: " + user[2] + '.')
x += 3
return
print('error')
x += 1
check()

Why is my python global variable not changing? [duplicate]

This question already has answers here:
Using global variables in a function
(25 answers)
Closed 3 years ago.
I need help to understand why my python variable is not changing?
Here is the code:
from tkinter import filedialog
from tkinter import *
selectedRootFolder = "" #<-------------------------------------here is the variable declared
# get any folder to be a root folder
def add_dir():
root = Tk()
root.withdraw()
dirname = filedialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')
selectedRootFolder = dirname
print("Here: " + selectedRootFolder)#<-----------------------here is the variable changed
# print the root folder
def print_root_dir_path():
print (selectedRootFolder) #<-----------------------------here is the variable empty -> =""
# in case a wrong number is taken
def invalid():
print("---------------------")
print ("INVALID CHOICE!")
print("---------------------")
# exit program
def exit_prog():
print ("Thank you, come back soon!")
exit()
# define the menu options
menu = {"1":("Choose Directory:", add_dir),
"2":("Print Root Directory Path",print_root_dir_path),
"9":("Exit",exit_prog)
}
while True:
# list the menu
for key in sorted(menu.keys()):
print (key + ":" + menu[key][0])
# pick a number
print("---------------------")
ans = input("Make A Choice: ")
print("---------------------")
#get the number, if none, call invalid function
menu.get(ans,[None,invalid])[1]()
This is just a part of the script, but it should be able to show my problem, which is that when I pick option 1, to choose a directory, it is successful, and it prints the selectedRootFolder, but when I choose option 2 after that, the printed value is just as declared in the beginning, empty.
I do not understand why is that, can u help me?
Thank you.
Edit 1:
Changed:
selectedRootFolder = print(dirname)
To:
selectedRootFolder = dirname
print("Here: " + selectedRootFolder)
Use global
Ex:
selectedRootFolder = ""
def add_dir():
global selectedRootFolder
selectedRootFolder = "Update"
add_dir()
print(selectedRootFolder)
Repl: https://repl.it/repls/SoreLankyAttributes

How do I get a python program to rerun itself [duplicate]

This question already has answers here:
How do I re-run code in Python?
(9 answers)
Closed 6 years ago.
I want the code below to automatically rerun itself any ideas hwo to do this? Btw I am new to stack overflow and python itself so If I am doing anything wrong on either please let me know, Thanks
import sys
import os
import random
answer_correct_message = random.choice(['Well done', 'Correct answer','Nice one','Thats correct!'])
answer_wrong_message = random.choice(['Unlucky','Thats wrong','Nope'])
random_num_1 = random.randint(1,10)
random_num_2 = random.randint(1,10)
def question_asker_and_answerer():
q2 = input("What is " + str(random_num_1) + " + " + str(random_num_2) + "?")
if q2 == random_num_1 + random_num_2:
the_questions = True
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
else:
the_questions = False
if the_questions == True:
return (answer_correct_message)
else:
print(answer_wrong_message)
print question_asker_and_answerer()
This is not a situation where you are need a program to rerun itself. That sort of requirement is when you want a script to run as a daemon. This is simply a matter of creating a loop
while True:
print question_asker_and_answerer()
There are two problems here:
how to iterate;
how to make sure that the various randomly-chosen variables are different each pass through.
Just looping over the existing function, or getting it to recurse (as in a couple of other answers) solves the first of these problems (actually, recursing really doesn't, since Python doesn't have tail-call elimination, so it will run out of stack eventually).
To solve both of them you need to make the randomly-chosen variables local to the function, and then loop. I have also modified it so it returns the string to print rather than printing it, in the case of a wrong answer (last line of function).
import sys
import os
import random
def question_asker_and_answerer():
answer_correct_message = random.choice(['Well done', 'Correct answer',
'Nice one','Thats correct!'])
answer_wrong_message = random.choice(['Unlucky','Thats wrong','Nope'])
random_num_1 = random.randint(1,10)
random_num_2 = random.randint(1,10)
q2 = input("What is " + str(random_num_1) + " + " + str(random_num_2) + "?")
if q2 == random_num_1 + random_num_2:
the_questions = True
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
else:
the_questions = False
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
while True:
print question_asker_and_answerer()

Categories