how to execute different print function based on the users input

2024/7/6 22:07:03

I am a complete beginner to coding and python so It is probably very simple. So my problem is that am learning how to put if and else function based on the users input and i dont know how to connect between the two.

age = input("enter your age: ")
yes = "welcome"
no = "too bad then"
ans = [yes, no]
if age == "18":print(yes)
else: input("you're not old enough, would you like to enter anyways?: {ans} ")if yes:print(yes)else:print(no)

this is the code i made based on what ive learned so far it is probably full of mistake. I wanted to connect the 'if' and 'else' function to the input("you're not old enough, would you like to enter anyways?: {ans} ") the answer would be yes or no which would print diffrent things.

Answer

Note that when using or, as soon as the first expression (in the order specified) is True, the next expressions are ignored since the result will be True regardless. The same happens when using and; as soon as a False is found, the next expressions are ignored since the result will be False

For your specific question the solution is:

if int(input("enter your age: ")) >= 18 or input("you're not old enough, would you like to enter anyways? ").lower().startswith('y'):print("welcome")  
else: print("too bad then")

for a more general-purpose task (writing an interpreter or similar) you need to use function pointers and a look-up table (usually a dictionary). Here is a working example:

import math
import timedef add(*args):"Adds numbers together"if len(args)>0:print(sum((float(arg) for arg in args)))def mult(*args):"Multiplies numbers together"if len(args)>0:print(math.prod((float(arg) for arg in args)))def nothing(*args):passdef alias(*args):"Creates a new alias for a given action"action, alias, *_ = argsif action not in LUT:print("Cannot create an alias for an undefined action!")else:aliases[alias]=actionprint(f"Successfully created alias '{alias}' for '{action}'")def print_help(*args):"Displays valid options and what they do"for keyword in LUT:doc = LUT[keyword].__doc__print(f"{keyword} : {doc if doc is not None else '?'}")print(f"To exit the program, type any one of: {', '.join(termination_keywords)}")def print_aliases(*args):groupings= {action : [] for action in LUT}for alias in aliases:groupings[aliases[alias]].append(alias)for action, aliases_ in groupings.items():if len(aliases_)>0:print(f"{action} : {', '.join(aliases_)}")# Look Up Table
LUT = {'help':print_help,'add':add,'mult':mult,'nop' : nothing,'alias' : alias,'print_aliases': print_aliases}aliases = {'+':'add','sum':'add','total': 'add','*':'mult','multiply':'mult','prod':'mult','nothing' : 'nop','pass': 'nop'
}termination_keywords = {'end','exit','quit','q'}print(f"""Enter your the desired action and its arguments as space seperated values.
For example: add 1 2 3 4 5Defined actions are:""")
print_help()
# Sometimes the input is displayed before the help is done printing, a small delay fixes the issue
time.sleep(0.5)while True:print("#"*20)action, *args = input("What do you want to do? ").split(' ')action = action.lower()if action in termination_keywords:break;if action in LUT:LUT[action](*args)elif action in aliases:LUT[aliases[action]](*args)else:print("Undefined action!")
https://en.xdnf.cn/q/119854.html

Related Q&A

matplotlib - AttributeError: module numbers has no attribute Integral

I am a newbie to python and i am trying to learn online. I tried importing matplotlib on python 3.6 but i keep getting this error:problem in matplotlib - AttributeError: module numbers has no attribute…

How to extract social information from a given website?

I have a Website URL Like www.example.comI want to collect social information from this website like : facebook url (facebook.com/example ), twitter url ( twitter.com/example ) etc., if available anywh…

Check if string is of nine digits then exit function in python

I have a function in python that returns different output of strings (Text). And I have different parts that I should check for the string and if the string is of nine digits or contains 9 digits then …

How to extract quotations from text using NLTK [duplicate]

This question already has answers here:RegEx: Grabbing values between quotation marks(20 answers)Closed 8 years ago.I have a project wherein I need to extract quotations from a huge set of articles . H…

takes exactly 2 arguments (1 given) when including self [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

scipy.optimize.curve_fit a definite integral function with scipy.integrate.quad

If I have a function that the independent variable is the upper limit of an definite integral of a mathematical model. This mathematical model has the parameters I want to do regression. This mathemati…

MAC OS - os.system(command) display nothing

When I run IDLE (python 3.8) :>>> import os >>> os.system("ls") 0 >>> os.system(echo "test") 0 >>> os.system("users") 0 >>> Bu…

Flask App will not load app.py (The file/path provided (app) does not appear to exist)

My flask app is outputting no content for the for() block and i dont know why.I tested my query in app.py , here is app.py:# mysql config app.config[MYSQL_DATABASE_USER] = user app.config[MYSQL_DATABAS…

how to create from month Gtk.Calendar a week calendar and display the notes in each day in python

I have created a calendar app with month and week view in python. In month view, I can write notes in each day, store them in a dictionary and save the dictionary in to disk so I can read it any time.…

How to access inner attribute class from outer class?

As title. the class set a attribute value inside inner class. then, access that inner attribute class from outer function. In below, attribute sets with inner function set_error. then, use outer functi…