Python Forum

Full Version: Beginner requiring help please
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi

Am using lockdown to teach myslef Python (mainly using youtube, although have ordered a few books)

Please could somebody show/tell me how I would convert this into code or point me in the direction of where i could find the answer

Variable = 0
user inputs Y or N
if user input = Y then let variable = variable + 4

I appreciate many newbies will be asking for help at them minute but would greatly appreciate any help at all

Thanks

w4ldom4ths
Variable = 0 is Python. If the variable is not already defined in the current scope (read about namespaces and scope) it creates the variable, the it assigns the variable the value zero.

For a console program you can use answer = Input('Would you like to play a game?')

for the comparison there are lots of ways to compare strings depending on how strict you want to be with the input. At the very least I would allow entering 'Y', 'Yes', 'y', 'yes', 'YES'. Maybe I would allow anything that starts with an upper or lower case 'y' to be Y and everything else is N
if answer[0] in('Y', 'y'):
    # do stuff
else:
    # do other stuff
Other ways to do this involve using regular expressions (regex) or you can convert the input to upper or lower case before making the comparison.

You should look at the official python documentation. It is online here:

https://docs.python.org/3/reference/index.html

You should also familiarize yourself with the standard library:

https://docs.python.org/3/library/index.html
You should check the validity of condition, like in spoken language: if this condition is met add 4 to that value.

>>> spam = 0                                                                        
>>> bacon = 'Y'                                                                     
>>> if bacon == 'Y': 
...    spam += 4 
...                                                                                
>>> spam                                                                           
4
Thank You both for your help.

Much appreciated