I am working on an omegle simulator for fun, where it asks your age and if you're old enough asks you if you have kik. It works fine if your age is 16 or more but if you say any less than that, it comes up with an error. This is the code:
age = input("age?\n")
if age == "1":
print ("Too young bby")
elif age == "2":
print ("Too young bby")
elif age == "3":
print ("Too young bby")
elif age == "4":
print ("Too young bby")
elif age == "5":
print ("Too young bby")
elif age == "6":
print ("Too young bby")
elif age == "7":
print ("Too young bby")
elif age == "8":
print ("Too young bby")
elif age == "9":
print ("Too young bby")
elif age == "10":
print ("Too young bby")
elif age == "11":
print ("Too young bby")
elif age == "12":
print ("Too young bby")
elif age == "13":
print ("Too young bby")
elif age == "14":
print ("Too young bby")
elif age == "15":
print ("Too young bby")
else:
kik = input("Do you have kik?\n")
yes = "yes"
if kik == yes:
print ("add me bby")
else:
print ("bye")
The error that comes up is:
Traceback (most recent call last):
File "C:/Users/Public/Documents/python/omegle.py", line 36, in <module>
if kik == yes:
NameError: name 'kik' is not defined
Does anyone know how to fix it?
The problem is that you only set kik in this block:
else:
kik = input("Do you have kik?\n")
If this block isn't reached, kik doesn't exist. An option is to set it before your if/elif blocks.
Additionally, you can make this much shorter:
kik = "no"
age = input("age?\n")
if int(age) < 16:
print ("Too young bby")
else:
kik = input("Do you have kik?\n")
yes = "yes"
if kik == yes:
print ("add me bby")
else:
print ("bye")
There are a couple of things you should fix here. FIrst, store the age as a number using int():
age = int(input("age?\n"))
And then do a less than:
if(age < 16):
print ("Too young bby")
else:
kik = input("Do you have kik?\n")
if kik == "yes":
print ("add me bby")
else:
print ("bye")
Set kik to the default it should be outside your chain.
age = input("age?\n")
kik = "no" #assuming no is default
...
As it is in your code, it will only be defined if you hit else
The short answer is that kik is out of scope, and putting kik = "no" at the beginning of your program should get rid of that error.
But, here's a better way to do the whole thing:
age = int(input("age?\n"))
kik = "no"
if age < 16:
print ("Too young bby")
else:
kik = input("Do you have kik?\n")
if kik == yes:
print ("add me bby")
else:
print ("bye")
Andy's post was very helpful to me. There is one thing I would add. If you enter an integer less than 16 to the first question, you get both print ("Too young bby") and print ("bye"). The first output only is sufficient for my use, not print ("bye").
To achieve this you indent the second 'if' statement to the first 'else' statement.
If you do not indent my code, you get "You are not eligible to vote in Ireland." twice. Here is my example;
Citizen = "No"
Yes = "Yes"
Age = int(input("What is your age?: \n"))
if (Age) < 18:
print("You are not eligible to vote in Ireland.\n")
else:
Citizen = input("Do you hold Irish Citizenship? Yes/No: \n")
if Citizen == Yes:
print("You are eligible to vote in Ireland.\n")
else:
print("You are not eligible to vote in Ireland.\n")
Related
I am trying to create a IPL/Fanstasy cricket simulators in which you create your team and play. You auction the players. In the auction function, I have added a turn feature, which means if the turn variable is even, then its your turn, if its odd, then its other bidders turn.
def auction(money, turn, choice):
if turn % 2 == 0:
while True:
print("It is your turn to choose a player.")
while True:
selected_player = str(
input("Enter the name of the player you wish to choose(leave empty to skip):"))
if selected_player in players:
break
elif selected_player == "":
print("Turn Skipped")
else:
print("That player is not in your players")
selected_player_bid = int(input("Enter the amount of money for which you wish to buy the player(leave "
"empty to skip):"))
if selected_player_bid > money:
print("You dont have enough money to buy the player.")
else:
your_players.append(selected_player)
print("Player bought")
break
break
else:
selected_player = random.choice(players)
selected_player_bid = random.randint(1, 100000)
print(
f"{random.choice(bidders)} chooses {selected_player} for {selected_player_bid}.")
print(
"You can either type [p]ass let them take the player or type [c]hallenge to challenge them.")
while True:
choice = input("Challenge or pass: ")
if choice.lower() == "challenge":
break
elif choice.lower() == "pass":
break
elif choice.lower() == "p":
break
elif choice.lower() == "c":
break
else:
print("Not a valid command, please type again.")
while choice.lower() == "challenge" or choice.lower() == 'c':
bid = int(input("Enter your bid: "))
if bid > money:
print("You do not have enough money.")
elif bid < selected_player_bid:
print("That is lower than the starting bid.")
else:
print(f"{selected_player} bought for {bid}")
money = money - bid
print("You have enough money.")
your_players.append(selected_player)
break
if choice.lower() == "p" or choice.lower() == "pass":
pass
players.remove(selected_player)
The usage of the function(This is where I was trying to fix the code).
while True:
if random_choice:
turn = turn + 1
random_choice = bool(random.choice(binary_numbers))
auction(your_money, turn, choice)
else:
random_choice = bool(random.choice(binary_numbers))
auction(your_money, turn, choice)
pass
if len(players) == 0:
break
else:
continue
GitHub repo
You can comment the fix or create a pull request.
Thanking you in advance.
I expected the code to randomly choose the bidder, either the player or the bots, but when I was fixing it, it was not doing so.
money = 0
day = 1
items = []
def gameplay():
global items
global money
global day
energy = 10
work = 0
while True:
print("Type 'help' for assistance")
play = str(input("-> ")).strip()
if play.lower() == "help":
print("""
Type : To : Cost:
'Work' Get Money (only once then next day) 5 Energy
'Mall' Buy Stuff 5 Energy
'Items' Check Inventory N/A
'Money' Check Balance Of Money N/A
'Energy' Check Balance Of Energy N/A
'Day' Check your day, day 1 , day 2 etc. N/A
'Done' End Your Day N/A """)
elif play.lower() == "work":
if work == 1:
print("You have already worked!")
else:
energy -= 5
print("Working......")
money += 5
work += 1
print("You now have $%s and %s Energy" % (money, energy))
elif play.lower() == "mall":
energy -= 5
while True:
print("What do you want to do?")
print("""
Type : To: Cost:
Coffee Buy Normal Coffee : +2 energy next day $4
Lottery Buy A Lottery Ticket (per day) $10
Money Check Balance Of Money N/A
Energy Check Balance Of Energy N/A
Items Check Your Inventory N/A
Exit Exit the shopping mall N/A
""")
mall = input("-> ").strip()
if mall.lower() == "coffee":
if "coffee" in list:
print("You have already bought a cup of coffee!")
elif money < 4:
print("You don't have enough money!")
else:
print("You bought a coffee")
items.append("coffee")
print(items)
if mall.lower() == "lottery":
if "Lottery Ticket" in list:
print("You have already bought a ticket! Try again next day!")
lot = random.randint(1, 20)
jack = random.randint(100, 1000)
while True:
if money < 10:
print("You don't have enough money!")
break
else:
list.append("Lottery Ticket")
money -= 10
print("Choose a number between 1 to 20")
try:
lotg = int(input("-> "))
if lotg == lot:
print("Congratulations you have won $%s" % (jack))
money += jack
break
elif lotg != lot:
print("Sorry but you lost! Good luck Next Time")
break
except ValueError:
print("Please Type A Number")
elif mall.lower() == "money":
print("You currently have $%s" % (money))
elif mall.lower() == "energy":
print("You currently have %s" % (energy))
elif mall.lower() == "items":
print("These are your following items:")
print(items)
elif mall.lower() == "exit":
print("Exiting mall......")
break
elif play.lower() == "items":
print("These are your following items:")
print(items)
elif play.lower() == "money":
print("You currently have $%s" % (money))
elif play.lower() == "energy":
print("You currently have %s" % (energy))
elif play.lower() == "day" :
print("Its Day %s " % (day))
elif play.lower() == "done":
while True:
print("Are You Sure?")
sure = str(input("-> "))
if sure.lower() not in ["yes","no"]:
print("Please Type Yes Or No ")
elif sure.lower() == "yes":
print("Going Home For Next Day........")
home()
elif sure.lower() == "no":
print("Okay!")
break
def noenergy():
print("You don't have enough energy to do that")
def home():
print("You are at home..")
gameplay()
It sometimes shows:
Traceback (most recent call last):
File "/home/alex/.config/JetBrains/PyCharm2020.1/scratches/scratch_718.py", line 120, in <module>
gameplay()
File "/home/alex/.config/JetBrains/PyCharm2020.1/scratches/scratch_718.py", line 50, in gameplay
if "coffee" in list:
TypeError: argument of type 'type' is not iterable
when i test it in this order
input -> mall
input -> coffee
The error message should pop up
Tried to change the while loop part to a for loop but , still the same and I can't find any answers on a single website
Why is this happening? The loop? The list? The input?
list is not a variable containing a list, it's the type (hence the error message) of list objects.
It looks like you meant to use the variable items which is a list and forgot or got confused.
I am learning python programming and was going through If Else conditions. Even if the If statement is true, my code executes else condition.
Please check the code below:
age = int(input("Enter your Age (in years)"))
sex = input("Enter you Sex(M/F)")
if(sex == 'M'):
if(age < 20):
print("You are just a teen.")
if(age >= 20 and age < 25):
print("You are a young man now.")
elif(age >=25 and age < 30):
print("You are a mature man now")
else:
print("You are getting old")
if(sex == 'F'):
if(age < 20):
print("You are just a teen.")
if(age >= 20 and age < 25):
print("You are a young woman now.")
elif(age >=25 and age < 30):
print("You are a lady now")
Over here, if i enter the age as 2 and sex as M, the code goes in first condition and prints the message
"You are just a team"
Along with it, the code also run the else condition and prints
You are getting old
I don't understand this behaviour. I checked for indentation and all indentations are correct.
You accidentally made it a double if which would cause both statements to execute.
age = int(input("Enter your Age (in years)"))
sex = input("Enter you Sex(M/F)")
if(sex == 'M'):
if(age < 20):
print("You are just a teen.")
elif(age >= 20 and age < 25): # notice now it is one if-elif block
print("You are a young man now.")
elif(age >=25 and age < 30):
print("You are a mature man now")
else:
print("You are getting old")
if(sex == 'F'):
if(age < 20):
print("You are just a teen.")
elif(age >= 20 and age < 25): # same here
print("You are a young woman now.")
elif(age >=25 and age < 30):
print("You are a lady now")
Switch
if(age < 20):
print("You are just a teen.")
if(age >= 20 and age < 25):
print("You are a young man now.")
with
if(age < 20):
print("You are just a teen.")
elif(age >= 20 and age < 25):
print("You are a young man now.")
What's happening is that your second if statement inside of if sex == 'M' isn't getting fulfilled because the age is not between 20 and 25. Since the elif isn't fulfilled either, whats inside the else block runs.
In the code snippet you've given, the else is connected to the second if statement: if(age >= 20 and age < 25):. The first "if" executes fine, but then when the second "if" fails it executes the "else". This can be fixed by changing the second "if" to an "elif":
if(sex == 'M'):
if(age < 20):
print("You are just a teen.")
elif(age >= 20 and age < 25):
print("You are a young man now.")
elif(age >=25 and age < 30):
print("You are a mature man now")
else:
print("You are getting old")
It is printing correct output. First, it is checking that age is less than 20 years, which is correct, it then print "You are just a teen.".
if(sex == 'M'):
if(age < 20):
print("You are just a teen.")
After that it checks second 'if' statement, then 'elif' and then it goes to 'else' and print that statement as there was no match previously.
if(age >= 20 and age < 25):
print("You are a young man now.")
elif(age >=25 and age < 30):
print("You are a mature man now")
else:
print("You are getting old")
You may have made a typo here:
if(age >= 20 and age < 25):
print("You are a young man now.")
Possibly, you are trying to use 'if' instead of 'elif' here.
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
This is Sheldon Cooper's Friendship Algorithm.
Python code.
Please help me find the mistake.
I doubled checked it x200 times but can't seem to find it.
I'm in high school so this would be pretty easy for all of you.
.
print("The Friendship Algorithm \n By Dr. Sheldon Cooper Ph.D")
print("Place a phone call")
home = input("Are they home?")
if home == "yes":
print("Ask, would you like to share a meal?")
meal = input("What is their response?")
.
if meal == "yes":
print("Dine together")
print("Begin friendship!")
elif meal == "no":
print("Ask, do you enjoy a hot beverage?")
.
hot_beverage = input("What is their response?")
if hot_beverage == "yes":
beverage = input("Tea, coffee or cocoa?")
if beverage == "tea":
print("Have tea")
print("Begin friendship!")
elif beverage == "coffee":
print("Have coffee")
print("Begin friendship!")
elif beverage == "cocoa":
print("Have cocoa")
print("Begin friendship!")
else:
print("That is not an option")
.
elif hot_beverage == "no":
while interest_cycle:
print("Recreational activities: \n Tell me one of your interests.")
interest = input("Do you share that interest?")
if n > 6:
print("Choose least objectional interest")
interest_cycle = False
elif interest == "no":
print("Ask for another")
n = n + 1
elif interest == "yes":
interest_cycle = False
print("Ask, why don't we do that together?")
print("Partake in interest")
print("Begin friendship!")
.
else:
print("That is not an option")
.
elif home == "no":
print("Leave message")
print("Wait for callback")
else:
print("That is not an option")
Very nicely written ! I made a few modifications to make it work on my computer.
Firstly I replaced all the input() with raw_input, this way you won't have to enter your answer with quotions.
Secondly, I had to rework the indentations on my side.
And lastly, I edited your while loop to hopefully make it look more like the actual flow chart.
If I were you, I would also add some conditions to prevent the program from ending if the user enters a bad value.
I hope it works for you !
print("The Friendship Algorithm \n By Dr. Sheldon Cooper Ph.D")
print("Place a phone call")
home = raw_input("Are they home?")
if home == "yes":
print("Ask, would you like to share a meal?")
meal = raw_input("What is their response?")
if meal == "yes":
print("Dine together")
print("Begin friendship!")
elif meal == "no":
print("Ask, do you enjoy a hot beverage?")
hot_beverage = raw_input("What is their response?")
if hot_beverage == "yes":
beverage = raw_input("Tea, coffee or cocoa?")
if beverage == "tea":
print("Have tea")
print("Begin friendship!")
elif beverage == "coffee":
print("Have coffee")
print("Begin friendship!")
elif beverage == "cocoa":
print("Have cocoa")
print("Begin friendship!")
else:
print("That is not an option")
elif hot_beverage == "no":
n = 0
while n<= 6:
print("Recreational activities: \n Tell me one of your interests.")
interest = raw_input("Do you share that interest?")
if interest == "no":
print("Ask for another")
n = n + 1
elif interest == "yes":
print("Ask, why don't we do that together?")
print("Partake in interest")
print("Begin friendship!")
break
else:
print("That is not an option")
elif home == "no":
print("Leave message")
print("Wait for callback")
else:
print("That is not an option")
For starters, the while loop will not execute because you have not set the value for interest_cycle hence it will return None whereas in python None is equivalent to False when converted to boolean.
Please refer to this for more info: https://www.digitalocean.com/community/tutorials/how-to-construct-while-loops-in-python-3
And also check your indentation on the if home == "yes":, elif home == "no":
and else:.
Good work on the code. I like the readability.
This is probably a simple answer but I thought I'd ask anyway.
My code below is asking the user for a number and depending on the answer provided will print the grade that corresponds with the numbers.
I want to stop the loop (terminate the program) by having the user type in (999). I know the problem is in my if userScore >= 90" print ('A'). So when the user enters the 999, the computer takes it as an A.
Is there a shortcut to fix this?
(PS I added the breaks to every line because when they were not there the outputs kept repeating endlessly.)
userScore = float(input('Enter the score or type "999" to quit: '))
while True:
try:
if userScore >= 90:
print ("You earned an A")
break
elif userScore >= 80:
print ("You earned a B")
break
elif userScore >= 70:
print ("You earned a C")
break
elif userScore >= 60:
print ("You earned a D")
break
elif userScore <= 59.9:
print ("You earned an F")
break
except:
if userScore == '999':
break
main()
Don't use try except. Try except is meant for error handling. This can be handled using a simple while loop.
userScore = float(input('Enter the score or type "999" to quit: '))
while userScore!=999:
if userScore >= 90:
print ("You earned an A")
break
elif userScore >= 80:
print ("You earned a B")
break
elif userScore >= 70:
print ("You earned a C")
break
elif userScore >= 60:
print ("You earned a D")
break
elif userScore <= 59.9:
print ("You earned an F")
break
main() # Why is this even required?
Here is what you are trying to accomplish. It is explained in the comments.
while True:
#This part gets the user input. It waits until the user enters a valid number input.
while True:
prelim = input('Enter the score or type "999" to quit: ')
try:
prelim = int(prelim)
except:
print("Please enter a valid input.")
else:
#if the input can be converted into a number, then this is our final input value
userScore = float(prelim)
break
#The first thing we should check is if the user wants to exit. This way it won't print out an answer then exit.
if userScore == 999:
break
if userScore >= 90:
print ("You earned an A")
elif userScore >= 80:
print ("You earned a B")
elif userScore >= 70:
print ("You earned a C")
elif userScore >= 60:
print ("You earned a D")
elif userScore <= 59.9:
print ("You earned an F")