I am currently working on a coding project where I have set several functions. I am trying to figure out how to use variables from different function. I have tried using 'self' but it hasn't worked. Can anyone help me sort out my code?
class A(object):
def intro1(self):
print("Welcome to the XXCI forum!")
self.intro2()
def intro2(self):
print("Press 'L' to log in and 'S to sign up.")
ch1 = input()
if ch1 == 'l' or 'L':
self.log_in()
elif ch1 == 'S' or 's':
self.sign_up1()
else:
print("Your input was invalid")
self.intro2()
def sign_up1(self):
print("Please enter your first name:")
fn1 = input()
if len(fn1) >= 3:
self.sign_up2()
elif len(fn1) <3:
print("Please enter a name that is equal to or over three characters!")
self.sign_up1()
def sign_up2(self):
print("Please enter your last name.")
ln1 = input()
if ln1 == ln1:
with open(ln1.txt, "a") as ln1:
ln1.write("Age: " + ag1 + ".")
sign_up3()
def sign_up3():
print("Please enter your age.")
ag1 = input()
if ag1 > 90:
print("Please enter an age under 90 and equal to 16 or over.")
elif ag1 <16:
print("Please enter an age under 90 and equal to 16 or over.")
else:
user_g()
def user_g():
username = (fn1[3], str[ag1])
username.join''
print("Here is your username:")
print(username)
p_creator()
It's obviously not finished yet, but I would really appreciate guidance with how to correct my errors and use variables in different functions. Thank you very much!!
you can find everything in the Python documentation: https://docs.python.org/3/tutorial/classes.html?highlight=class%20attributes%20access#class-objects
So you need just create and then call class's attributes.
Also you could use the best python practice DRY (don't repeat yourself) and merge two 'if' statements in def sign_up3 like this: 'if ag1 > 90 and ag1 < 16' (another and shorter way is 'if 16 < ag1 < 90')
Hope it helped anyhow.
best regards and good luck.
P.S.: please, use the indentations.
You can use global variable. Assign the variable outside the function. Then inside the function called the variable with global in front of it. For example:
def f():
global s
print(s)
s = "Demo of global variable"
f()
Related
import time
name=input("Enter your name:")
currentTime = int(time.strftime('%H'))
if currentTime < 12 :
print('Good morning,'+name)
elif currentTime > 12 :
print('Good afternoon,'+name)
else :
print('Good evening,'+name)
def main():
import random
guess: int = input('Enter a number the between 1 and 2 :')
if guess <= "2":
num: int = random.randint(1, 2)
print("the number is ", num)
if num == guess: #### this if statement is not working
print('you won'
'your promote to level 2')
else:
print("You lost", ",Lets try again")
repeat = input('Do you want to try again:')
if repeat == "yes":
main()
else:
print("Good bye")
exit()
else:
print("the number you entered is grater than 5,Please enter a number between 1 and 2")
main()
main()
The if statement in this code not working (I have highlighted that if statement in code) But else statement is working to both conditions.
In your code guess is of type str, read the docs of input:
The function then reads a line from input, converts it to a string
(stripping a trailing newline), and returns that
When you do guess: int you are using a type hint. The docs say:
The Python runtime does not enforce function and variable type
annotations. They can be used by third party tools such as type
checkers, IDEs, linters, etc.
In your if you are trying to compare a int to a str. Run this in the Python console to see:
print(1 == '1') # --> False
print(1 == 1) # --> True
So what you need to do is explicitly convert it to int:
guess = int(input('Enter a number the between 1 and 2 :'))
And change the first if to:
if guess <= 2:
...
(removing the quotes in "2").
With these changes, your if statements will work.
I have a menu function and choice function that both worked. There are 3 menu choices. 1 and 3 worked properly at one point. 2 never has. I don't know what I did to mess it up, but when I run the module to test through IDLE, it doesn't ever work past the first prompting to enter my menu choice number. It should complete an if statement, then restart.
I don't know what else to try. I wish I knew what I changed to mess it up.
tribbles = 1
modulus = 2
closer= 3
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
menu()
def choice():
choice = int(input('\n Enter the number of your menu choice: ')
if choice == tribbles:
bars = int(input('\n How many bars of gold-pressed latinum do you have? '))
print('\n You can buy ',bars * 5000 / 1000,' Tribbles.')
menu()
choice()
elif choice == modulus:
num = int(input('\n Enter any number:'))
o_e = num % 2
if num == 0:
print(num,' is an even number')
elif num == 1:
print(num,' is an odd number')
menu()
choice()
elif choice == closer:
print('\n Thanks for playing!')
exit()
else:
print('Invalid entry. Please try again...')
menu()
choice()
print(' ')
choice = int(input('\n Enter the number of your menu choice: '))
I expect it to return with the string plus all formula results, then asking again, unless option 3 was selected and exit() is performed. However it returns with "Enter the number of your menu choice: " after the first input, then it returns blank after choosing any other choice on the second prompt.f
First things first!
It's good practice to define all functions at the top of the file, and call those functions at the bottom! Second your indenting is incorrect, i'm going to assume that happened after you pasted it here. Finally, you never actually call the function choice() you instead overwrite it with the result of a prompt.
Below i'm going to correct these issues.
tribbles = 1
modulus = 2
closer= 3
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
choice() #added call to choice here because you always call choice after menu
def choice():
my_choice = int(raw_input('\nEnter the number of your menu choice: ')) #you were missing a ) here! and you were overwriting the function choice again
#changed choice var to my_choice everywhere
if my_choice == tribbles:
bars = int(raw_input('\nHow many bars of gold-pressed latinum do you have? '))
print('\n You can buy ',bars * 5000 / 1000,' Tribbles.')
menu()
elif my_choice == modulus:
num = int(raw_input('\n Enter any number:'))
o_e = num % 2
if num == 0:
print(num,' is an even number')
elif num == 1:
print(num,' is an odd number')
menu()
elif choice == closer:
print('\n Thanks for playing!')
exit()
else:
print('Invalid entry. Please try again...')
menu()
print(' ')
if __name__ == "__main__": #standard way to begin. This makes sure this is being called from this file and not when being imported. And it looks pretty!
menu()
Before you check the value of choice, the variable choice is not declared. You have to catch your input before the line: if choice == tribbles:. Your are only defining a function which even don't return the value of your choice or set a global variable.
Try this:
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
menu()
choice = int(input('\n Enter the number of your menu choice: '))
if choice == tribbles:
...
I am very new to coding and just getting the jist of basic code.
I have done an if statement before but haven't come across this issue, could anyone help?
My code:
print("Hello User")
myName = input("What is your name?")
print("Hello" + myName)
myAge = input("What is your age?")
if input < 17:
print("Not quite an adult!")
elif:
print("So you're an adult!")
https://gyazo.com/15eef7751886747f4ce572641b9398fc
You need else:.
elif means else if and needs expression.
if expression:
pass
elif expression:
pass
else:
pass
Just change the 'elif' to 'else'. And there you go!
print("Hello User")
myName = input("What is your name?")
print("Hello" + myName)
myAge = int(input("What is your age?"))
if myAge < 17:
print("Not quite an adult!")
elif myAge >17:
print("So you're an adult!")
TypeError: '<' not supported between instances of 'str' and 'int'>>must castingtype into int for input>>>so when use elif he Suppose you complete the condition
I am having trouble with my monster_room function. No matter what the input is, it will always choose the elif choice (elif choice > 5:...). Here is the function:
def monster_room():
print "This is the monster room! How many monsters do you see?"
choice = raw_input("> ")
if choice < 5:
dead("More than that idiot!")
elif choice > 5:
print "More than you thought right?!"
print "Do you go to the Alien room or Frankenstien room?"
choice_one = raw_input("> ")
if choice_one == "alien":
alien_room()
elif choice_one == "frankenstien":
frankenstien_room()
else:
print "Type alien or frankenstien, DUMMY!"
monster_room()
else:
print "Type a number!"
monster_room()
How do I get it to read the input? Also this is my first project and I know it's very basic and probably looks rough so other tips I am open to as well. If you need the full code (99 lines) just let me know! Thanks!
You need to parse your input data to a number type using int() because raw_input() returns a string.
choice = int(raw_input("> "))
As #Joran Beasley metniioned to be on the save side you shuld use a try except block:
try:
choice = int(raw_input("> "))
except ValueError:
print "Type a number!"
monster_room()
you'll get to the "type a number!" section even if you input 5 since you're not allowing a >= or <= scenario.
I do agree, though, you have to convert the input to an int or float.
Casting the input to int will solve it (it's a string when you use it). Do this:
choice = int(raw_input("> "))
Ok, I am creating a memory game. I have developed where the programme asks the user what word was removed, and have successfully developed the part that moves on if they get it right. However, I am struggling to find how to get it to only fail the user if they get it wrong three times. Here's what I have so far:
def q1():
qone + 1
print("\n"*2)
while qone <= 3:
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\n"*1)
print("Correct")
print("\n"*2)
q2()
else:
print("Incorrect")
q1()
else:
print("You're all out of guesses!")
input("Press enter to return to the menu")
menu()
return
`
My approach is to remove recursion and simply increase the counter of failed tries.
def q1():
qone = 0
print("\n"*2)
while qone < 3:
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\n"*1)
print("Correct")
print("\n"*2)
q2()
return
else:
print("Incorrect")
qone += 1
print("You're all out of guesses!")
input("Press enter to return to the menu")
menu()
return
When you do qone + 1, you need to assign it to something (so perhaps qone += 1)
What is the else outside the while loop linked to?
You seem to have a recursive definition going. Think carefully about the chain of calls that would be made and what your base case should be. Once you know these things, it would be easier for you to write the code. Also, think about whether you need recursion at all: in this case, it doesn't seem like you would.
You should not have the function calling itself, use range for the loop, if the user gets the question correct go to the next question, if they get it wrong print the output:
def q1(removed):
print("\n"*2)
for i in range(3):
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\nCorrect")
return q2()
print("\n\nIncorrect")
input("You're all out of guesses!\nPress enter to return to the menu")
return menu()
If the user has three bad guesses the loop will end and you will hit the "You're all out of guesses!\nPress enter to return to the menu"